Search in sources :

Example 1 with OsSharedRealm

use of io.realm.internal.OsSharedRealm in project realm-java by realm.

the class BaseRealm method migrateRealm.

/**
 * Migrates the Realm file defined by the given configuration using the provided migration block.
 *
 * @param configuration configuration for the Realm that should be migrated. If this is a SyncConfiguration this
 * method does nothing.
 * @param migration if set, this migration block will override what is set in {@link RealmConfiguration}.
 * @throws FileNotFoundException if the Realm file doesn't exist.
 * @throws IllegalArgumentException if the provided configuration is a {@code SyncConfiguration}.
 */
protected static void migrateRealm(final RealmConfiguration configuration, @Nullable final RealmMigration migration) throws FileNotFoundException {
    // noinspection ConstantConditions
    if (configuration == null) {
        throw new IllegalArgumentException("RealmConfiguration must be provided");
    }
    if (configuration.isSyncConfiguration()) {
        throw new IllegalArgumentException("Manual migrations are not supported for synced Realms");
    }
    if (migration == null && configuration.getMigration() == null) {
        throw new RealmMigrationNeededException(configuration.getPath(), "RealmMigration must be provided.");
    }
    final AtomicBoolean fileNotFound = new AtomicBoolean(false);
    RealmCache.invokeWithGlobalRefCount(configuration, new RealmCache.Callback() {

        @Override
        public void onResult(int count) {
            if (count != 0) {
                throw new IllegalStateException("Cannot migrate a Realm file that is already open: " + configuration.getPath());
            }
            File realmFile = new File(configuration.getPath());
            if (!realmFile.exists()) {
                fileNotFound.set(true);
                return;
            }
            RealmProxyMediator mediator = configuration.getSchemaMediator();
            OsSchemaInfo schemaInfo = new OsSchemaInfo(mediator.getExpectedObjectSchemaInfoMap().values());
            OsSharedRealm.MigrationCallback migrationCallback = null;
            final RealmMigration migrationToBeApplied = migration != null ? migration : configuration.getMigration();
            if (migrationToBeApplied != null) {
                migrationCallback = createMigrationCallback(migrationToBeApplied);
            }
            OsRealmConfig.Builder configBuilder = new OsRealmConfig.Builder(configuration).autoUpdateNotification(false).schemaInfo(schemaInfo).migrationCallback(migrationCallback);
            OsSharedRealm sharedRealm = null;
            try {
                sharedRealm = OsSharedRealm.getInstance(configBuilder, OsSharedRealm.VersionID.LIVE);
            } finally {
                if (sharedRealm != null) {
                    sharedRealm.close();
                }
            }
        }
    });
    if (fileNotFound.get()) {
        throw new FileNotFoundException("Cannot migrate a Realm file which doesn't exist: " + configuration.getPath());
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) RealmMigrationNeededException(io.realm.exceptions.RealmMigrationNeededException) OsSchemaInfo(io.realm.internal.OsSchemaInfo) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RealmProxyMediator(io.realm.internal.RealmProxyMediator) File(java.io.File) OsSharedRealm(io.realm.internal.OsSharedRealm)

Example 2 with OsSharedRealm

use of io.realm.internal.OsSharedRealm in project realm-java by realm.

the class BaseRealm method compactRealm.

/**
 * Compacts the Realm file defined by the given configuration.
 *
 * @param configuration configuration for the Realm to compact.
 * @return {@code true} if compaction succeeded, {@code false} otherwise.
 */
static boolean compactRealm(final RealmConfiguration configuration) {
    OsSharedRealm sharedRealm = OsSharedRealm.getInstance(configuration, OsSharedRealm.VersionID.LIVE);
    Boolean result = sharedRealm.compact();
    sharedRealm.close();
    return result;
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) OsSharedRealm(io.realm.internal.OsSharedRealm)

Example 3 with OsSharedRealm

use of io.realm.internal.OsSharedRealm in project realm-java by realm.

the class DynamicRealmModelRealmAnyOperator method getRealmModel.

@SuppressWarnings({ "unchecked", "TypeParameterUnusedInFormals" })
private static <T extends RealmModel> T getRealmModel(BaseRealm realm, NativeRealmAny nativeRealmAny) {
    OsSharedRealm sharedRealm = realm.getSharedRealm();
    String className = Table.getClassNameForTable(nativeRealmAny.getRealmModelTableName(sharedRealm));
    return realm.get((Class<T>) DynamicRealmObject.class, className, nativeRealmAny.getRealmModelRowKey());
}
Also used : OsSharedRealm(io.realm.internal.OsSharedRealm)

Example 4 with OsSharedRealm

use of io.realm.internal.OsSharedRealm in project realm-java by realm.

the class Realm method executeTransactionAsync.

/**
 * Similar to {@link #executeTransactionAsync(Transaction)}, but also accepts an OnSuccess and OnError callbacks.
 *
 * @param transaction {@link io.realm.Realm.Transaction} to execute.
 * @param onSuccess callback invoked when the transaction succeeds.
 * @param onError callback invoked when the transaction fails.
 * @return a {@link RealmAsyncTask} representing a cancellable task.
 * @throws IllegalArgumentException if the {@code transaction} is {@code null}, or if the realm is opened from
 * another thread.
 */
public RealmAsyncTask executeTransactionAsync(final Transaction transaction, @Nullable final Realm.Transaction.OnSuccess onSuccess, @Nullable final Realm.Transaction.OnError onError) {
    checkIfValid();
    // noinspection ConstantConditions
    if (transaction == null) {
        throw new IllegalArgumentException("Transaction should not be null");
    }
    if (isFrozen()) {
        throw new IllegalStateException("Write transactions on a frozen Realm is not allowed.");
    }
    // Avoid to call canDeliverNotification() in bg thread.
    final boolean canDeliverNotification = sharedRealm.capabilities.canDeliverNotification();
    // the results.
    if ((onSuccess != null || onError != null)) {
        sharedRealm.capabilities.checkCanDeliverNotification("Callback cannot be delivered on current thread.");
    }
    // We need to use the same configuration to open a background OsSharedRealm (i.e Realm)
    // to perform the transaction
    final RealmConfiguration realmConfiguration = getConfiguration();
    // We need to deliver the callback even if the Realm is closed. So acquire a reference to the notifier here.
    final RealmNotifier realmNotifier = sharedRealm.realmNotifier;
    final Future<?> pendingTransaction = asyncTaskExecutor.submitTransaction(new Runnable() {

        @Override
        public void run() {
            if (Thread.currentThread().isInterrupted()) {
                return;
            }
            OsSharedRealm.VersionID versionID = null;
            Throwable exception = null;
            final Realm bgRealm = Realm.getInstance(realmConfiguration);
            bgRealm.beginTransaction();
            try {
                transaction.execute(bgRealm);
                if (Thread.currentThread().isInterrupted()) {
                    return;
                }
                bgRealm.commitTransaction();
                // The bgRealm needs to be closed before post event to caller's handler to avoid concurrency
                // problem. This is currently guaranteed by posting callbacks later below.
                versionID = bgRealm.sharedRealm.getVersionID();
            } catch (final Throwable e) {
                exception = e;
            } finally {
                try {
                    if (bgRealm.isInTransaction()) {
                        bgRealm.cancelTransaction();
                    }
                } finally {
                    bgRealm.close();
                }
            }
            final Throwable backgroundException = exception;
            final OsSharedRealm.VersionID backgroundVersionID = versionID;
            // Cannot be interrupted anymore.
            if (canDeliverNotification) {
                if (backgroundVersionID != null && onSuccess != null) {
                    realmNotifier.post(new Runnable() {

                        @Override
                        public void run() {
                            if (isClosed()) {
                                // The caller Realm is closed. Just call the onSuccess. Since the new created Realm
                                // cannot be behind the background one.
                                onSuccess.onSuccess();
                                return;
                            }
                            if (sharedRealm.getVersionID().compareTo(backgroundVersionID) < 0) {
                                sharedRealm.realmNotifier.addTransactionCallback(new Runnable() {

                                    @Override
                                    public void run() {
                                        onSuccess.onSuccess();
                                    }
                                });
                            } else {
                                onSuccess.onSuccess();
                            }
                        }
                    });
                } else if (backgroundException != null) {
                    realmNotifier.post(new Runnable() {

                        @Override
                        public void run() {
                            if (onError != null) {
                                onError.onError(backgroundException);
                            } else {
                                throw new RealmException("Async transaction failed", backgroundException);
                            }
                        }
                    });
                }
            } else {
                if (backgroundException != null) {
                    // Throw in the worker thread since the caller thread cannot get notifications.
                    throw new RealmException("Async transaction failed", backgroundException);
                }
            }
        }
    });
    return new RealmAsyncTaskImpl(pendingTransaction, asyncTaskExecutor);
}
Also used : RealmAsyncTaskImpl(io.realm.internal.async.RealmAsyncTaskImpl) RealmException(io.realm.exceptions.RealmException) RealmNotifier(io.realm.internal.RealmNotifier) OsSharedRealm(io.realm.internal.OsSharedRealm)

Aggregations

OsSharedRealm (io.realm.internal.OsSharedRealm)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 RealmException (io.realm.exceptions.RealmException)1 RealmMigrationNeededException (io.realm.exceptions.RealmMigrationNeededException)1 OsSchemaInfo (io.realm.internal.OsSchemaInfo)1 RealmNotifier (io.realm.internal.RealmNotifier)1 RealmProxyMediator (io.realm.internal.RealmProxyMediator)1 RealmAsyncTaskImpl (io.realm.internal.async.RealmAsyncTaskImpl)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1