-
-
Notifications
You must be signed in to change notification settings - Fork 735
/
ParseObject.java
4404 lines (3987 loc) · 152 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 android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import bolts.Capture;
import bolts.Continuation;
import bolts.Task;
import bolts.TaskCompletionSource;
/**
* 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.
*/
public class ParseObject implements Parcelable {
private static final String AUTO_CLASS_NAME = "_Automatic";
/* package */ static final String VERSION_NAME = BuildConfig.VERSION_NAME;
private static final String TAG = "ParseObject";
/*
REST JSON Keys
*/
private static final String KEY_OBJECT_ID = "objectId";
private static final String KEY_CLASS_NAME = "className";
private static final String KEY_ACL = "ACL";
private static final String KEY_CREATED_AT = "createdAt";
private static final String KEY_UPDATED_AT = "updatedAt";
/*
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";
/* package */ static final String KEY_IS_DELETING_EVENTUALLY = "__isDeletingEventually";
// 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 ParseObjectController getObjectController() {
return ParseCorePlugins.getInstance().getObjectController();
}
private static LocalIdManager getLocalIdManager() {
return ParseCorePlugins.getInstance().getLocalIdManager();
}
private static ParseObjectSubclassingController getSubclassingController() {
return ParseCorePlugins.getInstance().getSubclassingController();
}
static class State {
public static Init<?> newBuilder(String className) {
if ("_User".equals(className)) {
return new ParseUser.State.Builder();
}
return new Builder(className);
}
/* package */ static State createFromParcel(Parcel source, ParseParcelDecoder decoder) {
String className = source.readString();
if ("_User".equals(className)) {
return new ParseUser.State(source, className, decoder);
}
return new State(source, className, decoder);
}
static abstract class Init<T extends Init> {
private final String className;
private String objectId;
private long createdAt = -1;
private long updatedAt = -1;
private boolean isComplete;
private Set<String> availableKeys = new HashSet<>();
/* package */ Map<String, Object> serverData = new HashMap<>();
public Init(String className) {
this.className = className;
}
/* package */ Init(State state) {
className = state.className();
objectId = state.objectId();
createdAt = state.createdAt();
updatedAt = state.updatedAt();
availableKeys = Collections.synchronizedSet(state.availableKeys());
for (String key : state.keySet()) {
serverData.put(key, state.get(key));
availableKeys.add(key);
}
isComplete = state.isComplete();
}
/* package */ abstract T self();
/* package */ abstract <S extends State> S build();
public T objectId(String objectId) {
this.objectId = objectId;
return self();
}
public T createdAt(Date createdAt) {
this.createdAt = createdAt.getTime();
return self();
}
public T createdAt(long createdAt) {
this.createdAt = createdAt;
return self();
}
public T updatedAt(Date updatedAt) {
this.updatedAt = updatedAt.getTime();
return self();
}
public T updatedAt(long updatedAt) {
this.updatedAt = updatedAt;
return self();
}
public T isComplete(boolean complete) {
isComplete = complete;
return self();
}
public T put(String key, Object value) {
serverData.put(key, value);
availableKeys.add(key);
return self();
}
public T remove(String key) {
serverData.remove(key);
return self();
}
public T availableKeys(Collection<String> keys) {
for (String key : keys) {
availableKeys.add(key);
}
return self();
}
public T clear() {
objectId = null;
createdAt = -1;
updatedAt = -1;
isComplete = false;
serverData.clear();
availableKeys.clear();
return self();
}
/**
* Applies a {@code State} on top of this {@code Builder} instance.
*
* @param other The {@code State} to apply over this instance.
* @return A new {@code Builder} instance.
*/
public T apply(State other) {
if (other.objectId() != null) {
objectId(other.objectId());
}
if (other.createdAt() > 0) {
createdAt(other.createdAt());
}
if (other.updatedAt() > 0) {
updatedAt(other.updatedAt());
}
isComplete(isComplete || other.isComplete());
for (String key : other.keySet()) {
put(key, other.get(key));
}
availableKeys(other.availableKeys());
return self();
}
public T apply(ParseOperationSet operations) {
for (String key : operations.keySet()) {
ParseFieldOperation operation = operations.get(key);
Object oldValue = serverData.get(key);
Object newValue = operation.apply(oldValue, key);
if (newValue != null) {
put(key, newValue);
} else {
remove(key);
}
}
return self();
}
}
/* package */ static class Builder extends Init<Builder> {
public Builder(String className) {
super(className);
}
public Builder(State state) {
super(state);
}
@Override
/* package */ Builder self() {
return this;
}
public State build() {
return new State(this);
}
}
private final String className;
private final String objectId;
private final long createdAt;
private final long updatedAt;
private final Map<String, Object> serverData;
private final Set<String> availableKeys;
private final boolean isComplete;
/* package */ State(Init<?> builder) {
className = builder.className;
objectId = builder.objectId;
createdAt = builder.createdAt;
updatedAt = builder.updatedAt > 0
? builder.updatedAt
: createdAt;
serverData = Collections.unmodifiableMap(new HashMap<>(builder.serverData));
isComplete = builder.isComplete;
availableKeys = Collections.synchronizedSet(builder.availableKeys);
}
/* package */ State(Parcel parcel, String clazz, ParseParcelDecoder decoder) {
className = clazz; // Already read
objectId = parcel.readByte() == 1 ? parcel.readString() : null;
createdAt = parcel.readLong();
long updated = parcel.readLong();
updatedAt = updated > 0 ? updated : createdAt;
int size = parcel.readInt();
HashMap<String, Object> map = new HashMap<>();
for (int i = 0; i < size; i++) {
String key = parcel.readString();
Object obj = decoder.decode(parcel);
map.put(key, obj);
}
serverData = Collections.unmodifiableMap(map);
isComplete = parcel.readByte() == 1;
List<String> available = new ArrayList<>();
parcel.readStringList(available);
availableKeys = new HashSet<>(available);
}
@SuppressWarnings("unchecked")
public <T extends Init<?>> T newBuilder() {
return (T) new Builder(this);
}
public String className() {
return className;
}
public String objectId() {
return objectId;
}
public long createdAt() {
return createdAt;
}
public long updatedAt() {
return updatedAt;
}
public boolean isComplete() {
return isComplete;
}
public Object get(String key) {
return serverData.get(key);
}
public Set<String> keySet() {
return serverData.keySet();
}
// Available keys for this object. With respect to keySet(), this includes also keys that are
// undefined in the server, but that should be accessed without throwing.
// These extra keys come e.g. from ParseQuery.selectKeys(). Selected keys must be available to
// get() methods even if undefined, for consistency with complete objects.
// For a complete object, this set is equal to keySet().
public Set<String> availableKeys() {
return availableKeys;
}
protected void writeToParcel(Parcel dest, ParseParcelEncoder encoder) {
dest.writeString(className);
dest.writeByte(objectId != null ? (byte) 1 : 0);
if (objectId != null) {
dest.writeString(objectId);
}
dest.writeLong(createdAt);
dest.writeLong(updatedAt);
dest.writeInt(serverData.size());
Set<String> keys = serverData.keySet();
for (String key : keys) {
dest.writeString(key);
encoder.encode(serverData.get(key), dest);
}
dest.writeByte(isComplete ? (byte) 1 : 0);
dest.writeStringList(new ArrayList<>(availableKeys));
}
@Override
public String toString() {
return String.format(Locale.US, "%s@%s[" +
"className=%s, objectId=%s, createdAt=%d, updatedAt=%d, isComplete=%s, " +
"serverData=%s, availableKeys=%s]",
getClass().getName(),
Integer.toHexString(hashCode()),
className,
objectId,
createdAt,
updatedAt,
isComplete,
serverData,
availableKeys);
}
}
/* package */ final Object mutex = new Object();
/* package */ final TaskQueue taskQueue = new TaskQueue();
private State state;
/* package */ final LinkedList<ParseOperationSet> operationSetQueue;
// Cached State
private final Map<String, Object> estimatedData;
/* package */ String localId;
private final ParseMulticastDelegate<ParseObject> saveEvent = new ParseMulticastDelegate<>();
/* package */ boolean isDeleted;
/* package */ boolean isDeleting; // Since delete ops are queued, we don't need a counter.
//TODO (grantland): Derive this off the EventuallyPins as opposed to +/- count.
/* package */ int isDeletingEventually;
private boolean ldsEnabledWhenParceling;
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 unfetched pointer that has no objectId. This is useful only in the context of the offline
* store, where you can have an unfetched pointer for an object that can later be fetched from the
* store.
*/
/* package */ private static final String NEW_OFFLINE_OBJECT_ID_PLACEHOLDER =
"*** Offline Object ***";
/**
* 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);
}
}
/**
* 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 #refresh()} 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 #refresh()} 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) throws Exception {
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) throws Exception {
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.
*/
/* package */ static <T extends ParseObject> T from(ParseObject.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.
*/
/* package */ 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.
*/
/* package */ 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;
}
/**
* Method used by parse server webhooks implementation to convert raw JSON to Parse Object
*
* 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.
*/
/* package */ 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;
}
//region Getter/Setter helper methods
/* package */ State.Init<?> newStateBuilder(String className) {
return new State.Builder(className);
}
/* package */ State getState() {
synchronized (mutex) {
return state;
}
}
/**
* Updates the current state of this object as well as updates our in memory cached state.
*
* @param newState The new state.
*/
/* package */ void setState(State newState) {
synchronized (mutex) {
setState(newState, true);
}
}
private void setState(State newState, boolean notifyIfObjectIdChanges) {
synchronized (mutex) {
String oldObjectId = state.objectId();
String newObjectId = newState.objectId();
state = newState;
if (notifyIfObjectIdChanges && !ParseTextUtils.equals(oldObjectId, newObjectId)) {
notifyObjectIdChanged(oldObjectId, newObjectId);
}
rebuildEstimatedData();
}
}
/**
* Accessor to the class name.
*/
public String getClassName() {
synchronized (mutex) {
return state.className();
}
}
/**
* This reports time as the server sees it, so that if you make changes to a {@code ParseObject}, then
* wait a while, and then call {@link #save()}, the updated time will be the time of the
* {@link #save()} call rather than the time the object was changed locally.
*
* @return The last time this object was updated on the server.
*/
public Date getUpdatedAt() {
long updatedAt = getState().updatedAt();
return updatedAt > 0
? new Date(updatedAt)
: null;
}
/**
* This reports time as the server sees it, so that if you create a {@code ParseObject}, then wait a
* while, and then call {@link #save()}, the creation time will be the time of the first
* {@link #save()} call rather than the time the object was created locally.
*
* @return The first time this object was saved on the server.
*/
public Date getCreatedAt() {
long createdAt = getState().createdAt();
return createdAt > 0
? new Date(createdAt)
: null;
}
//endregion
/**
* Returns a set view of the keys contained in this object. This does not include createdAt,
* updatedAt, authData, or objectId. It does include things like username and ACL.
*/
public Set<String> keySet() {
synchronized (mutex) {
return Collections.unmodifiableSet(estimatedData.keySet());
}
}
/**
* Copies all of the operations that have been performed on another object since its last save
* onto this one.
*/
/* package */ void copyChangesFrom(ParseObject other) {
synchronized (mutex) {
ParseOperationSet operations = other.operationSetQueue.getFirst();
for (String key : operations.keySet()) {
performOperation(key, operations.get(key));
}
}
}
/* package */ void mergeFromObject(ParseObject other) {
synchronized (mutex) {
// If they point to the same instance, we don't need to merge.
if (this == other) {
return;
}
State copy = other.getState().newBuilder().build();
// We don't want to notify if an objectId changed here since we utilize this method to merge
// an anonymous current user with a new ParseUser instance that's calling signUp(). This
// doesn't make any sense and we should probably remove that code in ParseUser.
// Otherwise, there shouldn't be any objectId changes here since this method is only otherwise
// used in fetchAll.
setState(copy, false);
}
}
/**
* Clears changes to this object's {@code key} made since the last call to {@link #save()} or
* {@link #saveInBackground()}.
*
* @param key The {@code key} to revert changes for.
*/
public void revert(String key) {
synchronized (mutex) {
if (isDirty(key)) {
currentOperations().remove(key);
rebuildEstimatedData();
}
}
}
/**
* Clears any changes to this object made since the last call to {@link #save()} or
* {@link #saveInBackground()}.
*/
public void revert() {
synchronized (mutex) {
if (isDirty()) {
currentOperations().clear();
rebuildEstimatedData();
}
}
}
/**
* Deep traversal on this object to grab a copy of any object referenced by this object. These
* instances may have already been fetched, and we don't want to lose their data when refreshing
* or saving.
*
* @return the map mapping from objectId to {@code ParseObject} which has been fetched.
*/
private Map<String, ParseObject> collectFetchedObjects() {
final Map<String, ParseObject> fetchedObjects = new HashMap<>();
ParseTraverser traverser = new ParseTraverser() {
@Override
protected boolean visit(Object object) {
if (object instanceof ParseObject) {
ParseObject parseObj = (ParseObject) object;
State state = parseObj.getState();
if (state.objectId() != null && state.isComplete()) {
fetchedObjects.put(state.objectId(), parseObj);
}
}
return true;
}
};
traverser.traverse(estimatedData);
return fetchedObjects;
}
/**
* Helper method called by {@link #fromJSONPayload(JSONObject, ParseDecoder)}
*
* The method helps webhooks implementation to build Parse object from raw JSON payload.
* It is different from {@link #mergeFromServer(State, JSONObject, ParseDecoder, boolean)}
* as the method saves the key value pairs (other than className, objectId, updatedAt and
* createdAt) in the operation queue rather than the server data. It also handles
* {@link ParseFieldOperations} differently.
*
* @param json : JSON object to be converted to Parse object
* @param decoder : Decoder to be used for Decoding JSON
*/
/* package */ void build(JSONObject json, ParseDecoder decoder) {
try {
State.Builder builder = new State.Builder(state)
.isComplete(true);
builder.clear();
Iterator<?> keys = json.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
/*
__className: Used by fromJSONPayload, should be stripped out by the time it gets here...
*/
if (key.equals(KEY_CLASS_NAME)) {
continue;
}
if (key.equals(KEY_OBJECT_ID)) {
String newObjectId = json.getString(key);
builder.objectId(newObjectId);
continue;
}
if (key.equals(KEY_CREATED_AT)) {
builder.createdAt(ParseDateFormat.getInstance().parse(json.getString(key)));
continue;
}
if (key.equals(KEY_UPDATED_AT)) {
builder.updatedAt(ParseDateFormat.getInstance().parse(json.getString(key)));
continue;
}
Object value = json.get(key);
Object decodedObject = decoder.decode(value);
if (decodedObject instanceof ParseFieldOperation) {
performOperation(key, (ParseFieldOperation)decodedObject);
}
else {
put(key, decodedObject);
}
}
setState(builder.build());
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* Merges from JSON in REST format.
* Updates this object with data from the server.
*
* @see #toJSONObjectForSaving(State, ParseOperationSet, ParseEncoder)
*/
/* package */ State mergeFromServer(
State state, JSONObject json, ParseDecoder decoder, boolean completeData) {
try {
// If server data is complete, consider this object to be fetched.
State.Init<?> builder = state.newBuilder();
if (completeData) {
builder.clear();
}
builder.isComplete(state.isComplete() || completeData);
Iterator<?> keys = json.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
/*
__type: Returned by queries and cloud functions to designate body is a ParseObject
__className: Used by fromJSON, should be stripped out by the time it gets here...
*/
if (key.equals("__type") || key.equals(KEY_CLASS_NAME)) {
continue;
}
if (key.equals(KEY_OBJECT_ID)) {