-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathParseObject.java
4055 lines (3657 loc) · 158 KB
/
ParseObject.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.parse;
import android.os.Bundle;
import bolts.Capture;
import bolts.Continuation;
import bolts.Task;
import bolts.TaskCompletionSource;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
/**
* The {@code ParseObject} is a local representation of data that can be saved and retrieved from
* the Parse cloud.
* <p/>
* The basic workflow for creating new data is to construct a new {@code ParseObject}, use
* {@link #put(String, Object)} to fill it with data, and then use {@link #saveInBackground()} to
* persist to the cloud.
* <p/>
* The basic workflow for accessing existing data is to use a {@link ParseQuery} to specify which
* existing data to retrieve.
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class ParseObject {
/**
* Default name for pinning if not specified.
*
* @see #pin()
* @see #unpin()
*/
public static final String DEFAULT_PIN = "_default";
/*
REST JSON Keys
*/
public static final String KEY_OBJECT_ID = "objectId";
public static final String KEY_CREATED_AT = "createdAt";
public static final String KEY_UPDATED_AT = "updatedAt";
static final String KEY_IS_DELETING_EVENTUALLY = "__isDeletingEventually";
private static final String AUTO_CLASS_NAME = "_Automatic";
private static final String TAG = "ParseObject";
private static final String KEY_CLASS_NAME = "className";
private static final String KEY_ACL = "ACL";
/*
Internal JSON Keys - Used to store internal data when persisting {@code ParseObject}s locally.
*/
private static final String KEY_COMPLETE = "__complete";
private static final String KEY_OPERATIONS = "__operations";
// Array of keys selected when querying for the object. Helps decoding nested {@code ParseObject}s
// correctly, and helps constructing the {@code State.availableKeys()} set.
private static final String KEY_SELECTED_KEYS = "__selectedKeys";
// Because Grantland messed up naming this... We'll only try to read from this for backward
// compat, but I think we can be safe to assume any deleteEventuallys from long ago are obsolete
// and not check after a while
private static final String KEY_IS_DELETING_EVENTUALLY_OLD = "isDeletingEventually";
private static final ThreadLocal<String> isCreatingPointerForObjectId =
new ThreadLocal<String>() {
@Override
protected String initialValue() {
return null;
}
};
/*
* This is used only so that we can pass it to createWithoutData as the objectId to make it create
* an un-fetched pointer that has no objectId. This is useful only in the context of the offline
* store, where you can have an un-fetched pointer for an object that can later be fetched from the
* store.
*/
private static final String NEW_OFFLINE_OBJECT_ID_PLACEHOLDER =
"*** Offline Object ***";
final Object mutex = new Object();
final TaskQueue taskQueue = new TaskQueue();
final LinkedList<ParseOperationSet> operationSetQueue;
// Cached State
private final Map<String, Object> estimatedData;
private final ParseMulticastDelegate<ParseObject> saveEvent = new ParseMulticastDelegate<>();
String localId;
boolean isDeleted;
boolean isDeleting; // Since delete ops are queued, we don't need a counter.
//TODO (grantland): Derive this off the EventuallyPins as opposed to +/- count.
int isDeletingEventually;
private State state;
private boolean ldsEnabledWhenParceling;
/**
* The base class constructor to call in subclasses. Uses the class name specified with the
* {@link ParseClassName} annotation on the subclass.
*/
protected ParseObject() {
this(AUTO_CLASS_NAME);
}
/**
* Constructs a new {@code ParseObject} with no data in it. A {@code ParseObject} constructed in
* this way will not have an objectId and will not persist to the database until {@link #save()}
* is called.
* <p>
* Class names must be alphanumerical plus underscore, and start with a letter. It is recommended
* to name classes in <code>PascalCaseLikeThis</code>.
*
* @param theClassName The className for this {@code ParseObject}.
*/
public ParseObject(String theClassName) {
// We use a ThreadLocal rather than passing a parameter so that createWithoutData can do the
// right thing with subclasses. It's ugly and terrible, but it does provide the development
// experience we generally want, so... yeah. Sorry to whomever has to deal with this in the
// future. I pinky-swear we won't make a habit of this -- you believe me, don't you?
String objectIdForPointer = isCreatingPointerForObjectId.get();
if (theClassName == null) {
throw new IllegalArgumentException(
"You must specify a Parse class name when creating a new ParseObject.");
}
if (AUTO_CLASS_NAME.equals(theClassName)) {
theClassName = getSubclassingController().getClassName(getClass());
}
// If this is supposed to be created by a factory but wasn't, throw an exception.
if (!getSubclassingController().isSubclassValid(theClassName, getClass())) {
throw new IllegalArgumentException(
"You must create this type of ParseObject using ParseObject.create() or the proper subclass.");
}
operationSetQueue = new LinkedList<>();
operationSetQueue.add(new ParseOperationSet());
estimatedData = new HashMap<>();
State.Init<?> builder = newStateBuilder(theClassName);
// When called from new, assume hasData for the whole object is true.
if (objectIdForPointer == null) {
setDefaultValues();
builder.isComplete(true);
} else {
if (!objectIdForPointer.equals(NEW_OFFLINE_OBJECT_ID_PLACEHOLDER)) {
builder.objectId(objectIdForPointer);
}
builder.isComplete(false);
}
// This is a new untouched object, we don't need cache rebuilding, etc.
state = builder.build();
OfflineStore store = Parse.getLocalDatastore();
if (store != null) {
store.registerNewObject(this);
}
}
private static ParseObjectController getObjectController() {
return ParseCorePlugins.getInstance().getObjectController();
}
private static LocalIdManager getLocalIdManager() {
return ParseCorePlugins.getInstance().getLocalIdManager();
}
private static ParseObjectSubclassingController getSubclassingController() {
return ParseCorePlugins.getInstance().getSubclassingController();
}
/**
* Creates a new {@code ParseObject} based upon a class name. If the class name is a special type
* (e.g. for {@code ParseUser}), then the appropriate type of {@code ParseObject} is returned.
*
* @param className The class of object to create.
* @return A new {@code ParseObject} for the given class name.
*/
public static ParseObject create(String className) {
return getSubclassingController().newInstance(className);
}
/**
* Creates a new {@code ParseObject} based upon a subclass type. Note that the object will be
* created based upon the {@link ParseClassName} of the given subclass type. For example, calling
* create(ParseUser.class) may create an instance of a custom subclass of {@code ParseUser}.
*
* @param subclass The class of object to create.
* @return A new {@code ParseObject} based upon the class name of the given subclass type.
*/
@SuppressWarnings("unchecked")
public static <T extends ParseObject> T create(Class<T> subclass) {
return (T) create(getSubclassingController().getClassName(subclass));
}
/**
* Creates a reference to an existing {@code ParseObject} for use in creating associations between
* {@code ParseObject}s. Calling {@link #isDataAvailable()} on this object will return
* {@code false} until {@link #fetchIfNeeded()} or {@link #fetch()} has been called. No network
* request will be made.
*
* @param className The object's class.
* @param objectId The object id for the referenced object.
* @return A {@code ParseObject} without data.
*/
public static ParseObject createWithoutData(String className, String objectId) {
OfflineStore store = Parse.getLocalDatastore();
try {
if (objectId == null) {
isCreatingPointerForObjectId.set(NEW_OFFLINE_OBJECT_ID_PLACEHOLDER);
} else {
isCreatingPointerForObjectId.set(objectId);
}
ParseObject object = null;
if (store != null && objectId != null) {
object = store.getObject(className, objectId);
}
if (object == null) {
object = create(className);
if (object.hasChanges()) {
throw new IllegalStateException(
"A ParseObject subclass default constructor must not make changes "
+ "to the object that cause it to be dirty."
);
}
}
return object;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Failed to create instance of subclass.", e);
} finally {
isCreatingPointerForObjectId.set(null);
}
}
/**
* Creates a reference to an existing {@code ParseObject} for use in creating associations between
* {@code ParseObject}s. Calling {@link #isDataAvailable()} on this object will return
* {@code false} until {@link #fetchIfNeeded()} or {@link #fetch()} has been called. No network
* request will be made.
*
* @param subclass The {@code ParseObject} subclass to create.
* @param objectId The object id for the referenced object.
* @return A {@code ParseObject} without data.
*/
@SuppressWarnings({"unused", "unchecked"})
public static <T extends ParseObject> T createWithoutData(Class<T> subclass, String objectId) {
return (T) createWithoutData(getSubclassingController().getClassName(subclass), objectId);
}
/**
* Registers a custom subclass type with the Parse SDK, enabling strong-typing of those
* {@code ParseObject}s whenever they appear. Subclasses must specify the {@link ParseClassName}
* annotation and have a default constructor.
*
* @param subclass The subclass type to register.
*/
public static void registerSubclass(Class<? extends ParseObject> subclass) {
getSubclassingController().registerSubclass(subclass);
}
/* package for tests */
static void unregisterSubclass(Class<? extends ParseObject> subclass) {
getSubclassingController().unregisterSubclass(subclass);
}
/**
* Adds a task to the queue for all of the given objects.
*/
static <T> Task<T> enqueueForAll(final List<? extends ParseObject> objects,
Continuation<Void, Task<T>> taskStart) {
// The task that will be complete when all of the child queues indicate they're ready to start.
final TaskCompletionSource<Void> readyToStart = new TaskCompletionSource<>();
// First, we need to lock the mutex for the queue for every object. We have to hold this
// from at least when taskStart() is called to when obj.taskQueue enqueue is called, so
// that saves actually get executed in the order they were setup by taskStart().
// The locks have to be sorted so that we always acquire them in the same order.
// Otherwise, there's some risk of deadlock.
List<Lock> locks = new ArrayList<>(objects.size());
for (ParseObject obj : objects) {
locks.add(obj.taskQueue.getLock());
}
LockSet lock = new LockSet(locks);
lock.lock();
try {
// The task produced by TaskStart
final Task<T> fullTask;
try {
// By running this immediately, we allow everything prior to toAwait to run before waiting
// for all of the queues on all of the objects.
fullTask = taskStart.then(readyToStart.getTask());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
// Add fullTask to each of the objects' queues.
final List<Task<Void>> childTasks = new ArrayList<>();
for (ParseObject obj : objects) {
obj.taskQueue.enqueue(new Continuation<Void, Task<T>>() {
@Override
public Task<T> then(Task<Void> task) {
childTasks.add(task);
return fullTask;
}
});
}
// When all of the objects' queues are ready, signal fullTask that it's ready to go on.
Task.whenAll(childTasks).continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) {
readyToStart.setResult(null);
return null;
}
});
return fullTask;
} finally {
lock.unlock();
}
}
/**
* Converts a {@code ParseObject.State} to a {@code ParseObject}.
*
* @param state The {@code ParseObject.State} to convert from.
* @return A {@code ParseObject} instance.
*/
static <T extends ParseObject> T from(State state) {
@SuppressWarnings("unchecked")
T object = (T) ParseObject.createWithoutData(state.className(), state.objectId());
synchronized (object.mutex) {
State newState;
if (state.isComplete()) {
newState = state;
} else {
newState = object.getState().newBuilder().apply(state).build();
}
object.setState(newState);
}
return object;
}
/**
* Creates a new {@code ParseObject} based on data from the Parse server.
*
* @param json The object's data.
* @param defaultClassName The className of the object, if none is in the JSON.
* @param decoder Delegate for knowing how to decode the values in the JSON.
* @param selectedKeys Set of keys selected when quering for this object. If none, the object is assumed to
* be complete, i.e. this is all the data for the object on the server.
*/
public static <T extends ParseObject> T fromJSON(JSONObject json, String defaultClassName,
ParseDecoder decoder,
Set<String> selectedKeys) {
if (selectedKeys != null && !selectedKeys.isEmpty()) {
JSONArray keys = new JSONArray(selectedKeys);
try {
json.put(KEY_SELECTED_KEYS, keys);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
return fromJSON(json, defaultClassName, decoder);
}
/**
* Creates a new {@code ParseObject} based on data from the Parse server.
*
* @param json The object's data. It is assumed to be complete, unless the JSON has the
* {@link #KEY_SELECTED_KEYS} key.
* @param defaultClassName The className of the object, if none is in the JSON.
* @param decoder Delegate for knowing how to decode the values in the JSON.
*/
public static <T extends ParseObject> T fromJSON(JSONObject json, String defaultClassName,
ParseDecoder decoder) {
String className = json.optString(KEY_CLASS_NAME, defaultClassName);
if (className == null) {
return null;
}
String objectId = json.optString(KEY_OBJECT_ID, null);
boolean isComplete = !json.has(KEY_SELECTED_KEYS);
@SuppressWarnings("unchecked")
T object = (T) ParseObject.createWithoutData(className, objectId);
State newState = object.mergeFromServer(object.getState(), json, decoder, isComplete);
object.setState(newState);
return object;
}
//region Getter/Setter helper methods
/**
* Method used by parse server webhooks implementation to convert raw JSON to Parse Object
* <p>
* Method is used by parse server webhooks implementation to create a
* new {@code ParseObject} from the incoming json payload. The method is different from
* {@link #fromJSON(JSONObject, String, ParseDecoder, Set)} ()} in that it calls
* {@link #build(JSONObject, ParseDecoder)} which populates operation queue
* rather then the server data from the incoming JSON, as at external server the incoming
* JSON may not represent the actual server data. Also it handles
* {@link ParseFieldOperations} separately.
*
* @param json The object's data.
* @param decoder Delegate for knowing how to decode the values in the JSON.
*/
static <T extends ParseObject> T fromJSONPayload(
JSONObject json, ParseDecoder decoder) {
String className = json.optString(KEY_CLASS_NAME);
if (className == null || ParseTextUtils.isEmpty(className)) {
return null;
}
String objectId = json.optString(KEY_OBJECT_ID, null);
@SuppressWarnings("unchecked")
T object = (T) ParseObject.createWithoutData(className, objectId);
object.build(json, decoder);
return object;
}
/**
* This deletes all of the objects from the given List.
*/
private static <T extends ParseObject> Task<Void> deleteAllAsync(
final List<T> objects, final String sessionToken) {
if (objects.size() == 0) {
return Task.forResult(null);
}
// Create a list of unique objects based on objectIds
int objectCount = objects.size();
final List<ParseObject> uniqueObjects = new ArrayList<>(objectCount);
final HashSet<String> idSet = new HashSet<>();
for (int i = 0; i < objectCount; i++) {
ParseObject obj = objects.get(i);
if (!idSet.contains(obj.getObjectId())) {
idSet.add(obj.getObjectId());
uniqueObjects.add(obj);
}
}
return enqueueForAll(uniqueObjects, new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> toAwait) {
return deleteAllAsync(uniqueObjects, sessionToken, toAwait);
}
});
}
private static <T extends ParseObject> Task<Void> deleteAllAsync(
final List<T> uniqueObjects, final String sessionToken, Task<Void> toAwait) {
return toAwait.continueWithTask(new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> task) {
int objectCount = uniqueObjects.size();
List<State> states = new ArrayList<>(objectCount);
for (int i = 0; i < objectCount; i++) {
ParseObject object = uniqueObjects.get(i);
object.validateDelete();
states.add(object.getState());
}
List<Task<Void>> batchTasks = getObjectController().deleteAllAsync(states, sessionToken);
List<Task<Void>> tasks = new ArrayList<>(objectCount);
for (int i = 0; i < objectCount; i++) {
Task<Void> batchTask = batchTasks.get(i);
final T object = uniqueObjects.get(i);
tasks.add(batchTask.onSuccessTask(new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(final Task<Void> batchTask) {
return object.handleDeleteResultAsync().continueWithTask(new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> task) {
return batchTask;
}
});
}
}));
}
return Task.whenAll(tasks);
}
});
}
/**
* Deletes each object in the provided list. This is faster than deleting each object individually
* because it batches the requests.
*
* @param objects The objects to delete.
* @throws ParseException Throws an exception if the server returns an error or is inaccessible.
*/
public static <T extends ParseObject> void deleteAll(List<T> objects) throws ParseException {
ParseTaskUtils.wait(deleteAllInBackground(objects));
}
/**
* Deletes each object in the provided list. This is faster than deleting each object individually
* because it batches the requests.
*
* @param objects The objects to delete.
* @param callback The callback method to execute when completed.
*/
public static <T extends ParseObject> void deleteAllInBackground(List<T> objects, DeleteCallback callback) {
ParseTaskUtils.callbackOnMainThreadAsync(deleteAllInBackground(objects), callback);
}
/**
* Deletes each object in the provided list. This is faster than deleting each object individually
* because it batches the requests.
*
* @param objects The objects to delete.
* @return A {@link bolts.Task} that is resolved when deleteAll completes.
*/
public static <T extends ParseObject> Task<Void> deleteAllInBackground(final List<T> objects) {
return ParseUser.getCurrentSessionTokenAsync().onSuccessTask(new Continuation<String, Task<Void>>() {
@Override
public Task<Void> then(Task<String> task) {
String sessionToken = task.getResult();
return deleteAllAsync(objects, sessionToken);
}
});
}
/**
* Finds all of the objects that are reachable from child, including child itself, and adds them
* to the given mutable array. It traverses arrays and json objects.
*
* @param node An kind object to search for children.
* @param dirtyChildren The array to collect the {@code ParseObject}s into.
* @param dirtyFiles The array to collect the {@link ParseFile}s into.
* @param alreadySeen The set of all objects that have already been seen.
* @param alreadySeenNew The set of new objects that have already been seen since the last existing object.
*/
private static void collectDirtyChildren(Object node,
final Collection<ParseObject> dirtyChildren,
final Collection<ParseFile> dirtyFiles,
final Set<ParseObject> alreadySeen,
final Set<ParseObject> alreadySeenNew) {
new ParseTraverser() {
@Override
protected boolean visit(Object node) {
// If it's a file, then add it to the list if it's dirty.
if (node instanceof ParseFile) {
if (dirtyFiles == null) {
return true;
}
ParseFile file = (ParseFile) node;
if (file.getUrl() == null) {
dirtyFiles.add(file);
}
return true;
}
// If it's anything other than a file, then just continue;
if (!(node instanceof ParseObject)) {
return true;
}
if (dirtyChildren == null) {
return true;
}
// For files, we need to handle recursion manually to find cycles of new objects.
ParseObject object = (ParseObject) node;
Set<ParseObject> seen = alreadySeen;
Set<ParseObject> seenNew = alreadySeenNew;
// Check for cycles of new objects. Any such cycle means it will be
// impossible to save this collection of objects, so throw an exception.
if (object.getObjectId() != null) {
seenNew = new HashSet<>();
} else {
if (seenNew.contains(object)) {
throw new RuntimeException("Found a circular dependency while saving.");
}
seenNew = new HashSet<>(seenNew);
seenNew.add(object);
}
// Check for cycles of any object. If this occurs, then there's no
// problem, but we shouldn't recurse any deeper, because it would be
// an infinite recursion.
if (seen.contains(object)) {
return true;
}
seen = new HashSet<>(seen);
seen.add(object);
// Recurse into this object's children looking for dirty children.
// We only need to look at the child object's current estimated data,
// because that's the only data that might need to be saved now.
collectDirtyChildren(object.estimatedData, dirtyChildren, dirtyFiles, seen, seenNew);
if (object.isDirty(false)) {
dirtyChildren.add(object);
}
return true;
}
}.setYieldRoot(true).traverse(node);
}
//endregion
/**
* Helper version of collectDirtyChildren so that callers don't have to add the internally used
* parameters.
*/
private static void collectDirtyChildren(Object node, Collection<ParseObject> dirtyChildren,
Collection<ParseFile> dirtyFiles) {
collectDirtyChildren(node, dirtyChildren, dirtyFiles,
new HashSet<ParseObject>(),
new HashSet<ParseObject>());
}
/**
* This saves all of the objects and files reachable from the given object. It does its work in
* multiple waves, saving as many as possible in each wave. If there's ever an error, it just
* gives up, sets error, and returns NO.
*/
private static Task<Void> deepSaveAsync(final Object object, final String sessionToken) {
Set<ParseObject> objects = new HashSet<>();
Set<ParseFile> files = new HashSet<>();
collectDirtyChildren(object, objects, files);
// This has to happen separately from everything else because ParseUser.save() is
// special-cased to work for lazy users, but new users can't be created by
// ParseMultiCommand's regular save.
Set<ParseUser> users = new HashSet<>();
for (ParseObject o : objects) {
if (o instanceof ParseUser) {
ParseUser user = (ParseUser) o;
if (user.isLazy()) {
users.add((ParseUser) o);
}
}
}
objects.removeAll(users);
// objects will need to wait for files to be complete since they may be nested children.
final AtomicBoolean filesComplete = new AtomicBoolean(false);
List<Task<Void>> tasks = new ArrayList<>();
for (ParseFile file : files) {
tasks.add(file.saveAsync(sessionToken, null, null));
}
Task<Void> filesTask = Task.whenAll(tasks).continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) {
filesComplete.set(true);
return null;
}
});
// objects will need to wait for users to be complete since they may be nested children.
final AtomicBoolean usersComplete = new AtomicBoolean(false);
tasks = new ArrayList<>();
for (final ParseUser user : users) {
tasks.add(user.saveAsync(sessionToken));
}
Task<Void> usersTask = Task.whenAll(tasks).continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) {
usersComplete.set(true);
return null;
}
});
final Capture<Set<ParseObject>> remaining = new Capture<>(objects);
Task<Void> objectsTask = Task.forResult(null).continueWhile(new Callable<Boolean>() {
@Override
public Boolean call() {
return remaining.get().size() > 0;
}
}, new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> task) {
// Partition the objects into two sets: those that can be save immediately,
// and those that rely on other objects to be created first.
final List<ParseObject> current = new ArrayList<>();
final Set<ParseObject> nextBatch = new HashSet<>();
for (ParseObject obj : remaining.get()) {
if (obj.canBeSerialized()) {
current.add(obj);
} else {
nextBatch.add(obj);
}
}
remaining.set(nextBatch);
if (current.size() == 0 && filesComplete.get() && usersComplete.get()) {
// We do cycle-detection when building the list of objects passed to this function, so
// this should never get called. But we should check for it anyway, so that we get an
// exception instead of an infinite loop.
throw new RuntimeException("Unable to save a ParseObject with a relation to a cycle.");
}
// Package all save commands together
if (current.size() == 0) {
return Task.forResult(null);
}
return enqueueForAll(current, new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> toAwait) {
return saveAllAsync(current, sessionToken, toAwait);
}
});
}
});
return Task.whenAll(Arrays.asList(filesTask, usersTask, objectsTask));
}
private static <T extends ParseObject> Task<Void> saveAllAsync(
final List<T> uniqueObjects, final String sessionToken, Task<Void> toAwait) {
return toAwait.continueWithTask(new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> task) {
int objectCount = uniqueObjects.size();
List<State> states = new ArrayList<>(objectCount);
List<ParseOperationSet> operationsList = new ArrayList<>(objectCount);
List<ParseDecoder> decoders = new ArrayList<>(objectCount);
for (int i = 0; i < objectCount; i++) {
ParseObject object = uniqueObjects.get(i);
object.updateBeforeSave();
object.validateSave();
states.add(object.getState());
operationsList.add(object.startSave());
final Map<String, ParseObject> fetchedObjects = object.collectFetchedObjects();
decoders.add(new KnownParseObjectDecoder(fetchedObjects));
}
List<Task<State>> batchTasks = getObjectController().saveAllAsync(
states, operationsList, sessionToken, decoders);
List<Task<Void>> tasks = new ArrayList<>(objectCount);
for (int i = 0; i < objectCount; i++) {
Task<State> batchTask = batchTasks.get(i);
final T object = uniqueObjects.get(i);
final ParseOperationSet operations = operationsList.get(i);
tasks.add(batchTask.continueWithTask(new Continuation<State, Task<Void>>() {
@Override
public Task<Void> then(final Task<State> batchTask) {
State result = batchTask.getResult(); // will be null on failure
return object.handleSaveResultAsync(result, operations).continueWithTask(new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> task) {
if (task.isFaulted() || task.isCancelled()) {
return task;
}
// We still want to propagate batchTask errors
return batchTask.makeVoid();
}
});
}
}));
}
return Task.whenAll(tasks);
}
});
}
/**
* Saves each object in the provided list. This is faster than saving each object individually
* because it batches the requests.
*
* @param objects The objects to save.
* @throws ParseException Throws an exception if the server returns an error or is inaccessible.
*/
public static <T extends ParseObject> void saveAll(List<T> objects) throws ParseException {
ParseTaskUtils.wait(saveAllInBackground(objects));
}
/**
* Saves each object in the provided list to the server in a background thread. This is preferable
* to using saveAll, unless your code is already running from a background thread.
*
* @param objects The objects to save.
* @param callback {@code callback.done(e)} is called when the save completes.
*/
public static <T extends ParseObject> void saveAllInBackground(List<T> objects, SaveCallback callback) {
ParseTaskUtils.callbackOnMainThreadAsync(saveAllInBackground(objects), callback);
}
/**
* Saves each object in the provided list to the server in a background thread. This is preferable
* to using saveAll, unless your code is already running from a background thread.
*
* @param objects The objects to save.
* @return A {@link bolts.Task} that is resolved when saveAll completes.
*/
public static <T extends ParseObject> Task<Void> saveAllInBackground(final List<T> objects) {
return ParseUser.getCurrentUserAsync().onSuccessTask(new Continuation<ParseUser, Task<String>>() {
@Override
public Task<String> then(Task<ParseUser> task) {
final ParseUser current = task.getResult();
if (current == null) {
return Task.forResult(null);
}
if (!current.isLazy()) {
return Task.forResult(current.getSessionToken());
}
// The current user is lazy/unresolved. If it is attached to any of the objects via ACL,
// we'll need to resolve/save it before proceeding.
for (ParseObject object : objects) {
if (!object.isDataAvailable(KEY_ACL)) {
continue;
}
final ParseACL acl = object.getACL(false);
if (acl == null) {
continue;
}
final ParseUser user = acl.getUnresolvedUser();
if (user != null && user.isCurrentUser()) {
// We only need to find one, since there's only one current user.
return user.saveAsync(null).onSuccess(new Continuation<Void, String>() {
@Override
public String then(Task<Void> task) {
if (acl.hasUnresolvedUser()) {
throw new IllegalStateException("ACL has an unresolved ParseUser. "
+ "Save or sign up before attempting to serialize the ACL.");
}
return user.getSessionToken();
}
});
}
}
// There were no objects with ACLs pointing to unresolved users.
return Task.forResult(null);
}
}).onSuccessTask(new Continuation<String, Task<Void>>() {
@Override
public Task<Void> then(Task<String> task) {
final String sessionToken = task.getResult();
return deepSaveAsync(objects, sessionToken);
}
});
}
/**
* Fetches all the objects that don't have data in the provided list in the background.
*
* @param objects The list of objects to fetch.
* @return A {@link bolts.Task} that is resolved when fetchAllIfNeeded completes.
*/
public static <T extends ParseObject> Task<List<T>> fetchAllIfNeededInBackground(
final List<T> objects) {
return fetchAllAsync(objects, true);
}
/**
* Fetches all the objects that don't have data in the provided list.
*
* @param objects The list of objects to fetch.
* @return The list passed in for convenience.
* @throws ParseException Throws an exception if the server returns an error or is inaccessible.
*/
public static <T extends ParseObject> List<T> fetchAllIfNeeded(List<T> objects)
throws ParseException {
return ParseTaskUtils.wait(fetchAllIfNeededInBackground(objects));
}
//region LDS-processing methods.
/**
* Fetches all the objects that don't have data in the provided list in the background.
*
* @param objects The list of objects to fetch.
* @param callback {@code callback.done(result, e)} is called when the fetch completes.
*/
public static <T extends ParseObject> void fetchAllIfNeededInBackground(final List<T> objects,
FindCallback<T> callback) {
ParseTaskUtils.callbackOnMainThreadAsync(fetchAllIfNeededInBackground(objects), callback);
}
private static <T extends ParseObject> Task<List<T>> fetchAllAsync(
final List<T> objects, final boolean onlyIfNeeded) {
return ParseUser.getCurrentUserAsync().onSuccessTask(new Continuation<ParseUser, Task<List<T>>>() {
@Override
public Task<List<T>> then(Task<ParseUser> task) {
final ParseUser user = task.getResult();
return enqueueForAll(objects, new Continuation<Void, Task<List<T>>>() {
@Override
public Task<List<T>> then(Task<Void> task) {
return fetchAllAsync(objects, user, onlyIfNeeded, task);
}
});
}
});
}
/**
* @param onlyIfNeeded If enabled, will only fetch if the object has an objectId and
* !isDataAvailable, otherwise it requires objectIds and will fetch regardless
* of data availability.
*/
// TODO(grantland): Convert to ParseUser.State
private static <T extends ParseObject> Task<List<T>> fetchAllAsync(
final List<T> objects, final ParseUser user, final boolean onlyIfNeeded, Task<Void> toAwait) {
if (objects.size() == 0) {
return Task.forResult(objects);
}
List<String> objectIds = new ArrayList<>();
String className = null;
for (T object : objects) {
if (onlyIfNeeded && object.isDataAvailable()) {
continue;
}
if (className != null && !object.getClassName().equals(className)) {
throw new IllegalArgumentException("All objects should have the same class");
}
className = object.getClassName();
String objectId = object.getObjectId();
if (objectId != null) {
objectIds.add(object.getObjectId());
} else if (!onlyIfNeeded) {
throw new IllegalArgumentException("All objects must exist on the server");
}
}
if (objectIds.size() == 0) {
return Task.forResult(objects);
}
final ParseQuery<T> query = ParseQuery.<T>getQuery(className)
.whereContainedIn(KEY_OBJECT_ID, objectIds);
return toAwait.continueWithTask(new Continuation<Void, Task<List<T>>>() {
@Override
public Task<List<T>> then(Task<Void> task) {
return query.findAsync(query.getBuilder().build(), user, null);
}
}).onSuccess(new Continuation<List<T>, List<T>>() {
@Override
public List<T> then(Task<List<T>> task) throws Exception {
Map<String, T> resultMap = new HashMap<>();
for (T o : task.getResult()) {
resultMap.put(o.getObjectId(), o);
}
for (T object : objects) {
if (onlyIfNeeded && object.isDataAvailable()) {
continue;
}
T newObject = resultMap.get(object.getObjectId());
if (newObject == null) {
throw new ParseException(
ParseException.OBJECT_NOT_FOUND,
"Object id " + object.getObjectId() + " does not exist");
}
if (!Parse.isLocalDatastoreEnabled()) {
// We only need to merge if LDS is disabled, since single instance will do the merging
// for us.
object.mergeFromObject(newObject);
}
}
return objects;
}
});
}
//endregion
/**
* Fetches all the objects in the provided list in the background.
*
* @param objects The list of objects to fetch.
* @return A {@link bolts.Task} that is resolved when fetch completes.
*/
public static <T extends ParseObject> Task<List<T>> fetchAllInBackground(final List<T> objects) {
return fetchAllAsync(objects, false);
}
/**
* Fetches all the objects in the provided list.
*
* @param objects The list of objects to fetch.
* @return The list passed in.
* @throws ParseException Throws an exception if the server returns an error or is inaccessible.
*/
public static <T extends ParseObject> List<T> fetchAll(List<T> objects) throws ParseException {
return ParseTaskUtils.wait(fetchAllInBackground(objects));
}
/**