-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Realm.java
2095 lines (1950 loc) · 95.9 KB
/
Realm.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 2014 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm;
import android.app.IntentService;
import android.content.Context;
import android.os.Build;
import android.os.SystemClock;
import android.util.JsonReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
import io.reactivex.Flowable;
import io.realm.annotations.RealmClass;
import io.realm.exceptions.RealmError;
import io.realm.exceptions.RealmException;
import io.realm.exceptions.RealmFileException;
import io.realm.exceptions.RealmMigrationNeededException;
import io.realm.exceptions.RealmPrimaryKeyConstraintException;
import io.realm.internal.ColumnIndices;
import io.realm.internal.ObjectServerFacade;
import io.realm.internal.OsObject;
import io.realm.internal.OsObjectStore;
import io.realm.internal.OsSchemaInfo;
import io.realm.internal.OsSharedRealm;
import io.realm.internal.RealmCore;
import io.realm.internal.RealmNotifier;
import io.realm.internal.RealmObjectProxy;
import io.realm.internal.RealmProxyMediator;
import io.realm.internal.Row;
import io.realm.internal.Table;
import io.realm.internal.Util;
import io.realm.internal.annotations.ObjectServer;
import io.realm.internal.async.RealmAsyncTaskImpl;
import io.realm.log.RealmLog;
/**
* The Realm class is the storage and transactional manager of your object persistent store. It is in charge of creating
* instances of your RealmObjects. Objects within a Realm can be queried and read at any time. Creating, modifying, and
* deleting objects must be done while inside a transaction. See {@link #executeTransaction(Transaction)}
* <p>
* The transactions ensure that multiple instances (on multiple threads) can access the same objects in a consistent
* state with full ACID guarantees.
* <p>
* It is important to remember to call the {@link #close()} method when done with a Realm instance. Failing to do so can
* lead to {@link java.lang.OutOfMemoryError} as the native resources cannot be freed.
* <p>
* Realm instances cannot be used across different threads. This means that you have to open an instance on each thread
* you want to use Realm. Realm instances are cached automatically per thread using reference counting, so as long as
* the reference count doesn't reach zero, calling {@link #getInstance(RealmConfiguration)} will just return the cached
* Realm and should be considered a lightweight operation.
* <p>
* For the UI thread this means that opening and closing Realms should occur in either onCreate/onDestroy or
* onStart/onStop.
* <p>
* Realm instances coordinate their state across threads using the {@link android.os.Handler} mechanism. This also means
* that Realm instances on threads without an {@link android.os.Looper} cannot receive updates unless {@link #refresh()}
* is manually called.
* <p>
* A standard pattern for working with Realm in Android activities can be seen below:
* <p>
* <pre>
* public class RealmApplication extends Application {
*
* \@Override
* public void onCreate() {
* super.onCreate();
*
* // The Realm file will be located in package's "files" directory.
* RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
* Realm.setDefaultConfiguration(realmConfig);
* }
* }
*
* public class RealmActivity extends Activity {
*
* private Realm realm;
*
* \@Override
* protected void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
* setContentView(R.layout.layout_main);
* realm = Realm.getDefaultInstance();
* }
*
* \@Override
* protected void onDestroy() {
* super.onDestroy();
* realm.close();
* }
* }
* </pre>
* <p>
* Realm supports String and byte fields containing up to 16 MB.
* <p>
*
* @see <a href="http://en.wikipedia.org/wiki/ACID">ACID</a>
* @see <a href="https://github.com/realm/realm-java/tree/master/examples">Examples using Realm</a>
*/
public class Realm extends BaseRealm {
private static final String NULL_CONFIG_MSG = "A non-null RealmConfiguration must be provided";
public static final String DEFAULT_REALM_NAME = RealmConfiguration.DEFAULT_REALM_NAME;
/**
* The required length for encryption keys used to encrypt Realm data.
*/
public static final int ENCRYPTION_KEY_LENGTH = 64;
private static final Object defaultConfigurationLock = new Object();
// guarded by `defaultConfigurationLock`
private static RealmConfiguration defaultConfiguration;
private final RealmSchema schema;
/**
* The constructor is private to enforce the use of the static one.
*
* @param cache the {@link RealmCache} associated to this Realm instance.
* @throws IllegalArgumentException if trying to open an encrypted Realm with the wrong key.
*/
private Realm(RealmCache cache, OsSharedRealm.VersionID version) {
super(cache, createExpectedSchemaInfo(cache.getConfiguration().getSchemaMediator()), version);
schema = new ImmutableRealmSchema(this,
new ColumnIndices(configuration.getSchemaMediator(), sharedRealm.getSchemaInfo()));
// FIXME: This is to work around the different behaviour between the read only Realms in the Object Store and
// in current java implementation. Opening a read only Realm with some missing schemas is allowed by Object
// Store and realm-cocoa. In that case, any query based on the missing schema should just return an empty
// results. Fix this together with https://github.com/realm/realm-java/issues/2953
if (configuration.isReadOnly()) {
RealmProxyMediator mediator = configuration.getSchemaMediator();
Set<Class<? extends RealmModel>> classes = mediator.getModelClasses();
for (Class<? extends RealmModel> clazz : classes) {
String tableName = Table.getTableNameForClass(mediator.getSimpleClassName(clazz));
if (!sharedRealm.hasTable(tableName)) {
sharedRealm.close();
throw new RealmMigrationNeededException(configuration.getPath(),
String.format(Locale.US, "Cannot open the read only Realm. '%s' is missing.",
Table.getClassNameForTable(tableName)));
}
}
}
}
private Realm(OsSharedRealm sharedRealm) {
super(sharedRealm);
schema = new ImmutableRealmSchema(this,
new ColumnIndices(configuration.getSchemaMediator(), sharedRealm.getSchemaInfo()));
}
private static OsSchemaInfo createExpectedSchemaInfo(RealmProxyMediator mediator) {
return new OsSchemaInfo(mediator.getExpectedObjectSchemaInfoMap().values());
}
/**
* {@inheritDoc}
*/
@Override
public Flowable<Realm> asFlowable() {
return configuration.getRxFactory().from(this);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
checkIfValid();
for (RealmObjectSchema clazz : schema.getAll()) {
if (!clazz.getClassName().startsWith("__") && clazz.getTable().size() > 0) {
return false;
}
}
return true;
}
/**
* Returns the schema for this Realm. The schema is immutable.
* Any attempt to modify it will result in an {@link UnsupportedOperationException}.
* <p>
* The schema can only be modified using {@link DynamicRealm#getSchema()} or through an migration.
*
* @return The {@link RealmSchema} for this Realm.
*/
@Override
public RealmSchema getSchema() {
return schema;
}
/**
* Initializes the Realm library and creates a default configuration that is ready to use. It is required to call
* this method before interacting with any other of the Realm API's.
* <p>
* A good place is in an {@link android.app.Application} subclass:
* <pre>
* {@code
* public class MyApplication extends Application {
* \@Override
* public void onCreate() {
* super.onCreate();
* Realm.init(this);
* }
* }
* }
* </pre>
* <p>
* Remember to register it in the {@code AndroidManifest.xml} file:
* <pre>
* {@code
* <?xml version="1.0" encoding="utf-8"?>
* <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.realm.example">
* <application android:name=".MyApplication">
* // ...
* </application>
* </manifest>
* }
* </pre>
*
* @param context the Application Context.
* @throws IllegalArgumentException if a {@code null} context is provided.
* @throws IllegalStateException if {@link Context#getFilesDir()} could not be found.
* @see #getDefaultInstance()
*/
public static synchronized void init(Context context) {
initializeRealm(context, "");
}
/**
* Initializes the Realm library and creates a default configuration that is ready to use. It is required to call
* this method before interacting with any other of the Realm API's.
* <p>
* A good place is in an {@link android.app.Application} subclass:
* <pre>
* {@code
* public class MyApplication extends Application {
* \@Override
* public void onCreate() {
* super.onCreate();
* Realm.init(this, "MyApp/" + BuildConfig.VERSION_NAME);
* }
* }
* }
* </pre>
* <p>
* Remember to register it in the {@code AndroidManifest.xml} file:
* <pre>
* {@code
* <?xml version="1.0" encoding="utf-8"?>
* <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.realm.example">
* <application android:name=".MyApplication">
* // ...
* </application>
* </manifest>
* }
* </pre>
*
* @param context the Application Context.
* @param userAgent optional user defined string that will be sent to the Realm Object Server
* as part of a {@code User-Agent} header when a session is established. This setting will not be
* used by non-synchronized Realms.
* @throws IllegalArgumentException if a {@code null} context or userAgent is provided.
* @throws IllegalStateException if {@link Context#getFilesDir()} could not be found.
* @see #getDefaultInstance()
*/
@ObjectServer
public static synchronized void init(Context context, String userAgent) {
//noinspection ConstantConditions
if (userAgent == null) {
throw new IllegalArgumentException("Non-null 'userAgent' required.");
}
initializeRealm(context, userAgent);
}
// Checks whether the app is an Instant App or not. It first it tries with the system
// `PackageManager.isInstantApp` available from SDK 26. If not available it tries to invoke,
// via reflection, `PackageManagerCompat.isInstantApp` as it has support back to SDK 21.
private static boolean isInstantApp(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return context.getPackageManager().isInstantApp();
} else {
try {
Class instantAppsClass = Class.forName("com.google.android.gms.instantapps.InstantApps");
Method getPackageManagerCompatMethod = instantAppsClass.getMethod("getPackageManagerCompat", Context.class);
Object packageManagerCompatInstance = getPackageManagerCompatMethod.invoke(null, context);
Class packageManagerClass = Class.forName("com.google.android.gms.instantapps.PackageManagerCompat");
Method isInstantAppMethod = packageManagerClass.getMethod("isInstantApp");
return (boolean) isInstantAppMethod.invoke(packageManagerCompatInstance);
} catch (Exception ignored) {
// PackageManagerCompat not found and could not determine if it is instant app
return false;
}
}
}
private static void initializeRealm(Context context, String userAgent) {
if (BaseRealm.applicationContext == null) {
//noinspection ConstantConditions
if (context == null) {
throw new IllegalArgumentException("Non-null context required.");
}
checkFilesDirAvailable(context);
// https://github.com/realm/realm-java/issues/7640
if (isInstantApp(context)) {
throw new RealmError("Could not initialize Realm: Instant apps are not currently supported.");
}
RealmCore.loadLibrary(context);
setDefaultConfiguration(new RealmConfiguration.Builder(context).build());
ObjectServerFacade.getSyncFacadeIfPossible().initialize(
context,
userAgent,
(configuration, versionID) -> RealmCache.createRealmOrGetFromCache(
configuration,
Realm.class,
versionID
),
Realm::createInstance);
if (context.getApplicationContext() != null) {
BaseRealm.applicationContext = context.getApplicationContext();
} else {
BaseRealm.applicationContext = context;
}
OsSharedRealm.initialize(new File(context.getFilesDir(), ".realm.temp"));
}
}
/**
* In some cases, Context.getFilesDir() is not available when the app launches the first time.
* This should never happen according to the official Android documentation, but the race condition wasn't fixed
* until Android 4.4.
* <p>
* This method attempts to fix that situation. If this doesn't work an {@link IllegalStateException} will be
* thrown.
* <p>
* See these links for further details:
* https://issuetracker.google.com/issues/36918154
* https://github.com/realm/realm-java/issues/4493#issuecomment-295349044
*/
private static void checkFilesDirAvailable(Context context) {
File filesDir = context.getFilesDir();
if (filesDir != null) {
if (filesDir.exists()) {
return; // Everything is fine. Escape as soon as possible
} else {
try {
// This was reported as working on some devices, which I really hope is just the race condition
// kicking in, otherwise something is seriously wrong with the permission system on those devices.
// We will try it anyway, since starting a loop will be slower by many magnitudes.
filesDir.mkdirs();
} catch (SecurityException ignored) {
}
}
}
if (filesDir == null || !filesDir.exists()) {
// Wait a "reasonable" amount of time before quitting.
// In this case we define reasonable as 200 ms (~12 dropped frames) before giving up (which most likely
// will result in the app crashing). This lag would only be seen in worst case scenarios, and then, only
// when the app is started the first time.
long[] timeoutsMs = new long[]{1, 2, 5, 10, 16}; // Exponential waits, capped at 16 ms;
long maxTotalWaitMs = 200;
long currentTotalWaitMs = 0;
int waitIndex = -1;
while (context.getFilesDir() == null || !context.getFilesDir().exists()) {
long waitMs = timeoutsMs[Math.min(++waitIndex, timeoutsMs.length - 1)];
SystemClock.sleep(waitMs);
currentTotalWaitMs += waitMs;
if (currentTotalWaitMs > maxTotalWaitMs) {
break;
}
}
}
// One final check before giving up
if (context.getFilesDir() == null || !context.getFilesDir().exists()) {
throw new IllegalStateException("Context.getFilesDir() returns " + context.getFilesDir() + " which is not an existing directory. See https://issuetracker.google.com/issues/36918154");
}
}
/**
* Realm static constructor that returns the Realm instance defined by the {@link io.realm.RealmConfiguration} set
* by {@link #setDefaultConfiguration(RealmConfiguration)}
*
* @return an instance of the Realm class.
* @throws java.lang.NullPointerException if no default configuration has been defined.
* @throws RealmMigrationNeededException if no migration has been provided by the default configuration and the
* @throws RealmFileException if an error happened when accessing the underlying Realm file.
* was set and the thread opening the Realm was interrupted while the download was in progress.
*/
// * @throws io.realm.exceptions.DownloadingRealmInterruptedException if {@link SyncConfiguration.Builder#waitForInitialRemoteData()}
// * RealmObject classes or version has has changed so a migration is required.
public static Realm getDefaultInstance() {
RealmConfiguration configuration = getDefaultConfiguration();
if (configuration == null) {
if (BaseRealm.applicationContext == null) {
throw new IllegalStateException("Call `Realm.init(Context)` before calling this method.");
} else {
throw new IllegalStateException("Set default configuration by using `Realm.setDefaultConfiguration(RealmConfiguration)`.");
}
}
return RealmCache.createRealmOrGetFromCache(configuration, Realm.class);
}
/**
* Realm static constructor that returns the Realm instance defined by provided {@link io.realm.RealmConfiguration}
*
* @param configuration {@link RealmConfiguration} used to open the Realm
* @return an instance of the Realm class
* @throws RealmMigrationNeededException if no migration has been provided by the configuration and the RealmObject
* classes or version has has changed so a migration is required.
* @throws RealmFileException if an error happened when accessing the underlying Realm file.
* @throws IllegalArgumentException if a null {@link RealmConfiguration} is provided.
* @see RealmConfiguration for details on how to configure a Realm.
*/
// * @throws io.realm.exceptions.DownloadingRealmInterruptedException if {@link SyncConfiguration.Builder#waitForInitialRemoteData()}
// * was set and the thread opening the Realm was interrupted while the download was in progress.
public static Realm getInstance(RealmConfiguration configuration) {
//noinspection ConstantConditions
if (configuration == null) {
throw new IllegalArgumentException(NULL_CONFIG_MSG);
}
return RealmCache.createRealmOrGetFromCache(configuration, Realm.class);
}
/**
* The creation of the first Realm instance per {@link RealmConfiguration} in a process can take some time as all
* initialization code need to run at that point (setting up the Realm, validating schemas and creating initial
* data). This method places the initialization work in a background thread and deliver the Realm instance
* to the caller thread asynchronously after the initialization is finished.
*
* @param configuration {@link RealmConfiguration} used to open the Realm.
* @param callback invoked to return the results.
* @throws IllegalArgumentException if a null {@link RealmConfiguration} or a null {@link Callback} is provided.
* @throws IllegalStateException if it is called from a non-Looper or {@link IntentService} thread.
* @return a {@link RealmAsyncTask} representing a cancellable task.
* @see Callback for more details.
*/
public static RealmAsyncTask getInstanceAsync(RealmConfiguration configuration,
Callback callback) {
//noinspection ConstantConditions
if (configuration == null) {
throw new IllegalArgumentException(NULL_CONFIG_MSG);
}
return RealmCache.createRealmOrGetFromCacheAsync(configuration, callback, Realm.class);
}
/**
* Sets the {@link io.realm.RealmConfiguration} used when calling {@link #getDefaultInstance()}.
*
* @param configuration the {@link io.realm.RealmConfiguration} to use as the default configuration.
* @throws IllegalArgumentException if a null {@link RealmConfiguration} is provided.
* @see RealmConfiguration for details on how to configure a Realm.
*/
public static void setDefaultConfiguration(RealmConfiguration configuration) {
//noinspection ConstantConditions
if (configuration == null) {
throw new IllegalArgumentException("A non-null RealmConfiguration must be provided");
}
synchronized (defaultConfigurationLock) {
defaultConfiguration = configuration;
}
}
/**
* Returns the default configuration for {@link #getDefaultInstance()}.
*
* @return default configuration object or {@code null} if no default configuration is specified.
*/
@Nullable
public static RealmConfiguration getDefaultConfiguration() {
synchronized (defaultConfigurationLock) {
return defaultConfiguration;
}
}
/**
* Removes the current default configuration (if any). Any further calls to {@link #getDefaultInstance()} will
* fail until a new default configuration has been set using {@link #setDefaultConfiguration(RealmConfiguration)}.
*/
public static void removeDefaultConfiguration() {
synchronized (defaultConfigurationLock) {
defaultConfiguration = null;
}
}
/**
* Creates a {@link Realm} instance without checking the existence in the {@link RealmCache}.
*
* @param cache the {@link RealmCache} where to create the realm in.
* @return a {@link Realm} instance.
*/
static Realm createInstance(RealmCache cache, OsSharedRealm.VersionID version) {
return new Realm(cache, version);
}
/**
* Creates a {@code Realm} instance directly from a {@link OsSharedRealm}. This {@code Realm} doesn't need to be
* closed.
*/
static Realm createInstance(OsSharedRealm sharedRealm) {
return new Realm(sharedRealm);
}
/**
* Creates a Realm object for each object in a JSON array. This must be done within a transaction.
* <p>
* JSON properties with unknown properties will be ignored. If a {@link RealmObject} field is not present in the
* JSON object the {@link RealmObject} field will be set to the default value for that type.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz type of Realm objects to create.
* @param json an array where each JSONObject must map to the specified class.
* @throws RealmException if mapping from JSON fails.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
public <E extends RealmModel> void createAllFromJson(Class<E> clazz, JSONArray json) {
//noinspection ConstantConditions
if (clazz == null || json == null) {
return;
}
checkIfValid();
for (int i = 0; i < json.length(); i++) {
try {
configuration.getSchemaMediator().createOrUpdateUsingJsonObject(clazz, this, json.getJSONObject(i), false);
} catch (JSONException e) {
throw new RealmException("Could not map JSON", e);
}
}
}
/**
* Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing
* object could not be found in the Realm, a new object will be created. This must happen within a transaction.
* If updating a {@link RealmObject} and a field is not found in the JSON object, that field will not be updated. If
* a new {@link RealmObject} is created and a field is not found in the JSON object, that field will be assigned the
* default value for the field type.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz type of {@link io.realm.RealmObject} to create or update. It must have a primary key defined.
* @param json array with object data.
* @throws IllegalArgumentException if trying to update a class without a {@link io.realm.annotations.PrimaryKey}.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws RealmException if unable to map JSON.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see #createAllFromJson(Class, org.json.JSONArray)
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, JSONArray json) {
//noinspection ConstantConditions
if (clazz == null || json == null) {
return;
}
checkIfValid();
checkHasPrimaryKey(clazz);
for (int i = 0; i < json.length(); i++) {
try {
configuration.getSchemaMediator().createOrUpdateUsingJsonObject(clazz, this, json.getJSONObject(i), true);
} catch (JSONException e) {
throw new RealmException("Could not map JSON", e);
}
}
}
/**
* Creates a Realm object for each object in a JSON array. This must be done within a transaction.
* JSON properties with unknown properties will be ignored. If a {@link RealmObject} field is not present in the
* JSON object the {@link RealmObject} field will be set to the default value for that type.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz type of Realm objects to create.
* @param json the JSON array as a String where each object can map to the specified class.
* @throws RealmException if mapping from JSON fails.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
public <E extends RealmModel> void createAllFromJson(Class<E> clazz, String json) {
//noinspection ConstantConditions
if (clazz == null || json == null || json.length() == 0) {
return;
}
JSONArray arr;
try {
arr = new JSONArray(json);
} catch (JSONException e) {
throw new RealmException("Could not create JSON array from string", e);
}
createAllFromJson(clazz, arr);
}
/**
* Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing
* object could not be found in the Realm, a new object will be created. This must happen within a transaction.
* If updating a {@link RealmObject} and a field is not found in the JSON object, that field will not be updated.
* If a new {@link RealmObject} is created and a field is not found in the JSON object, that field will be assigned
* the default value for the field type.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz type of {@link io.realm.RealmObject} to create or update. It must have a primary key defined.
* @param json string with an array of JSON objects.
* @throws IllegalArgumentException if trying to update a class without a {@link io.realm.annotations.PrimaryKey}.
* @throws RealmException if unable to create a JSON array from the json string.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see #createAllFromJson(Class, String)
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, String json) {
//noinspection ConstantConditions
if (clazz == null || json == null || json.length() == 0) {
return;
}
checkIfValid();
checkHasPrimaryKey(clazz);
JSONArray arr;
try {
arr = new JSONArray(json);
} catch (JSONException e) {
throw new RealmException("Could not create JSON array from string", e);
}
createOrUpdateAllFromJson(clazz, arr);
}
/**
* Creates a Realm object for each object in a JSON array. This must be done within a transaction.
* JSON properties with unknown properties will be ignored. If a {@link RealmObject} field is not present in the
* JSON object the {@link RealmObject} field will be set to the default value for that type.
* <p>
* This API is only available in API level 11 or later.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz type of Realm objects created.
* @param inputStream the JSON array as a InputStream. All objects in the array must be of the specified class.
* @throws RealmException if mapping from JSON fails.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws IOException if something was wrong with the input stream.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
public <E extends RealmModel> void createAllFromJson(Class<E> clazz, InputStream inputStream) throws IOException {
//noinspection ConstantConditions
if (clazz == null || inputStream == null) {
return;
}
checkIfValid();
JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
try {
reader.beginArray();
while (reader.hasNext()) {
configuration.getSchemaMediator().createUsingJsonStream(clazz, this, reader);
}
reader.endArray();
} finally {
reader.close();
}
}
/**
* Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing
* object could not be found in the Realm, a new object will be created. This must happen within a transaction.
* If updating a {@link RealmObject} and a field is not found in the JSON object, that field will not be updated.
* If a new {@link RealmObject} is created and a field is not found in the JSON object, that field will be assigned
* the default value for the field type.
* <p>
* This API is only available in API level 11 or later.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz type of {@link io.realm.RealmObject} to create or update. It must have a primary key defined.
* @param in the InputStream with a list of object data in JSON format.
* @throws IllegalArgumentException if trying to update a class without a {@link io.realm.annotations.PrimaryKey}.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws RealmException if unable to read JSON.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see #createOrUpdateAllFromJson(Class, java.io.InputStream)
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, InputStream in) {
//noinspection ConstantConditions
if (clazz == null || in == null) {
return;
}
checkIfValid();
checkHasPrimaryKey(clazz);
// As we need the primary key value we have to first parse the entire input stream as in the general
// case that value might be the last property. :(
Scanner scanner = null;
try {
scanner = getFullStringScanner(in);
JSONArray json = new JSONArray(scanner.next());
for (int i = 0; i < json.length(); i++) {
configuration.getSchemaMediator().createOrUpdateUsingJsonObject(clazz, this, json.getJSONObject(i), true);
}
} catch (JSONException e) {
throw new RealmException("Failed to read JSON", e);
} finally {
if (scanner != null) {
scanner.close();
}
}
}
/**
* Creates a Realm object pre-filled with data from a JSON object. This must be done inside a transaction. JSON
* properties with unknown properties will be ignored. If a {@link RealmObject} field is not present in the JSON
* object the {@link RealmObject} field will be set to the default value for that type.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz type of Realm object to create.
* @param json the JSONObject with object data.
* @return created object or {@code null} if no JSON data was provided.
* @throws RealmException if the mapping from JSON fails.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see #createOrUpdateObjectFromJson(Class, org.json.JSONObject)
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
@Nullable
public <E extends RealmModel> E createObjectFromJson(Class<E> clazz, JSONObject json) {
//noinspection ConstantConditions
if (clazz == null || json == null) {
return null;
}
checkIfValid();
try {
return configuration.getSchemaMediator().createOrUpdateUsingJsonObject(clazz, this, json, false);
} catch (JSONException e) {
throw new RealmException("Could not map JSON", e);
}
}
/**
* Tries to update an existing object defined by its primary key with new JSON data. If no existing object could be
* found a new object will be saved in the Realm. This must happen within a transaction. If updating a {@link RealmObject}
* and a field is not found in the JSON object, that field will not be updated. If a new {@link RealmObject} is
* created and a field is not found in the JSON object, that field will be assigned the default value for the field type.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz Type of {@link io.realm.RealmObject} to create or update. It must have a primary key defined.
* @param json {@link org.json.JSONObject} with object data.
* @return created or updated {@link io.realm.RealmObject}.
* @throws IllegalArgumentException if trying to update a class without a {@link io.realm.annotations.PrimaryKey}.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws RealmException if JSON data cannot be mapped.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see #createObjectFromJson(Class, org.json.JSONObject)
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
public <E extends RealmModel> E createOrUpdateObjectFromJson(Class<E> clazz, JSONObject json) {
//noinspection ConstantConditions
if (clazz == null || json == null) {
return null;
}
checkIfValid();
checkHasPrimaryKey(clazz);
try {
return configuration.getSchemaMediator().createOrUpdateUsingJsonObject(clazz, this, json, true);
} catch (JSONException e) {
throw new RealmException("Could not map JSON", e);
}
}
/**
* Creates a Realm object pre-filled with data from a JSON object. This must be done inside a transaction. JSON
* properties with unknown properties will be ignored. If a {@link RealmObject} field is not present in the JSON
* object the {@link RealmObject} field will be set to the default value for that type.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz type of Realm object to create.
* @param json the JSON string with object data.
* @return created object or {@code null} if JSON string was empty or null.
* @throws RealmException if mapping to json failed.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
@Nullable
public <E extends RealmModel> E createObjectFromJson(Class<E> clazz, String json) {
//noinspection ConstantConditions
if (clazz == null || json == null || json.length() == 0) {
return null;
}
JSONObject obj;
try {
obj = new JSONObject(json);
} catch (JSONException e) {
throw new RealmException("Could not create Json object from string", e);
}
return createObjectFromJson(clazz, obj);
}
/**
* Tries to update an existing object defined by its primary key with new JSON data. If no existing object could be
* found a new object will be saved in the Realm. This must happen within a transaction. If updating a
* {@link RealmObject} and a field is not found in the JSON object, that field will not be updated. If a new
* {@link RealmObject} is created and a field is not found in the JSON object, that field will be assigned the
* default value for the field type.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz type of {@link io.realm.RealmObject} to create or update. It must have a primary key defined.
* @param json string with object data in JSON format.
* @return created or updated {@link io.realm.RealmObject}.
* @throws IllegalArgumentException if trying to update a class without a {@link io.realm.annotations.PrimaryKey}.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws RealmException if JSON object cannot be mapped from the string parameter.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see #createObjectFromJson(Class, String)
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
public <E extends RealmModel> E createOrUpdateObjectFromJson(Class<E> clazz, String json) {
//noinspection ConstantConditions
if (clazz == null || json == null || json.length() == 0) {
return null;
}
checkIfValid();
checkHasPrimaryKey(clazz);
JSONObject obj;
try {
obj = new JSONObject(json);
} catch (JSONException e) {
throw new RealmException("Could not create Json object from string", e);
}
return createOrUpdateObjectFromJson(clazz, obj);
}
/**
* Creates a Realm object pre-filled with data from a JSON object. This must be done inside a transaction. JSON
* properties with unknown properties will be ignored. If a {@link RealmObject} field is not present in the JSON
* object the {@link RealmObject} field will be set to the default value for that type.
* <p>
* This API is only available in API level 11 or later.
*
* <p>
* This method currently does not support value list field.
*
* @param clazz type of Realm object to create.
* @param inputStream the JSON object data as a InputStream.
* @return created object or {@code null} if JSON string was empty or null.
* @throws RealmException if the mapping from JSON failed.
* @throws IllegalArgumentException if the JSON object doesn't have a primary key property but the corresponding
* {@link RealmObjectSchema} has a {@link io.realm.annotations.PrimaryKey} defined.
* @throws IOException if something went wrong with the input stream.
* @throws UnsupportedOperationException if the object to insert contains a {@link RealmDictionary} or
* a {@link RealmSet}.
* @see RealmSet
* @see RealmDictionary
* @see RealmMap
*/
@Nullable
public <E extends RealmModel> E createObjectFromJson(Class<E> clazz, InputStream inputStream) throws IOException {
//noinspection ConstantConditions
if (clazz == null || inputStream == null) {
return null;
}
checkIfValid();
E realmObject;
if (OsObjectStore.getPrimaryKeyForObject(
sharedRealm, configuration.getSchemaMediator().getSimpleClassName(clazz)) != null) {
// As we need the primary key value we have to first parse the entire input stream as in the general
// case that value might be the last property. :(
Scanner scanner = null;
try {
scanner = getFullStringScanner(inputStream);
JSONObject json = new JSONObject(scanner.next());
realmObject = configuration.getSchemaMediator().createOrUpdateUsingJsonObject(clazz, this, json, false);
} catch (JSONException e) {
throw new RealmException("Failed to read JSON", e);
} finally {
if (scanner != null) {
scanner.close();
}
}
} else {
JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
try {
realmObject = configuration.getSchemaMediator().createUsingJsonStream(clazz, this, reader);
} finally {
reader.close();
}
}
return realmObject;
}