Search in sources :

Example 21 with RealmException

use of io.realm.exceptions.RealmException in project realm-java by realm.

the class RealmJsonTests method createObjectFromJson_jsonException.

// Tests that given an exception everything up to the exception is saved.
@Test
public void createObjectFromJson_jsonException() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("columnString", "Foo");
    json.put("columnDate", "Boom");
    realm.beginTransaction();
    try {
        realm.createObjectFromJson(AllTypes.class, json);
        fail();
    } catch (RealmException ignored) {
    } finally {
        realm.commitTransaction();
    }
    AllTypes obj = realm.where(AllTypes.class).findFirst();
    assertEquals("Foo", obj.getColumnString());
    assertEquals(new Date(0), obj.getColumnDate());
}
Also used : JSONObject(org.json.JSONObject) AllTypes(io.realm.entities.AllTypes) RealmException(io.realm.exceptions.RealmException) Date(java.util.Date) Test(org.junit.Test)

Example 22 with RealmException

use of io.realm.exceptions.RealmException in project realm-java by realm.

the class RealmJsonTests method createOrUpdateObjectFromJson_invalidJsonObject.

@Test
public void createOrUpdateObjectFromJson_invalidJsonObject() throws JSONException {
    TestHelper.populateSimpleAllTypesPrimaryKey(realm);
    realm.beginTransaction();
    JSONObject json = new JSONObject();
    json.put("columnLong", "A");
    try {
        realm.createOrUpdateObjectFromJson(AllTypesPrimaryKey.class, json);
        fail();
    } catch (RealmException ignored) {
    } finally {
        realm.commitTransaction();
    }
    AllTypesPrimaryKey obj2 = realm.where(AllTypesPrimaryKey.class).findFirst();
    assertEquals("Foo", obj2.getColumnString());
}
Also used : JSONObject(org.json.JSONObject) RealmException(io.realm.exceptions.RealmException) AllTypesPrimaryKey(io.realm.entities.AllTypesPrimaryKey) Test(org.junit.Test)

Example 23 with RealmException

use of io.realm.exceptions.RealmException in project realm-java by realm.

the class DynamicRealm method createObject.

/**
     * Instantiates and adds a new object to the Realm.
     *
     * @param className the class name of the object to create.
     * @return the new object.
     * @throws RealmException if the object could not be created.
     */
public DynamicRealmObject createObject(String className) {
    checkIfValid();
    Table table = schema.getTable(className);
    // Check and throw the exception earlier for a better exception message.
    if (table.hasPrimaryKey()) {
        throw new RealmException(String.format("'%s' has a primary key, use" + " 'createObject(String, Object)' instead.", className));
    }
    long rowIndex = table.addEmptyRow();
    return get(DynamicRealmObject.class, className, rowIndex);
}
Also used : Table(io.realm.internal.Table) RealmException(io.realm.exceptions.RealmException)

Example 24 with RealmException

use of io.realm.exceptions.RealmException 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, final Realm.Transaction.OnSuccess onSuccess, final Realm.Transaction.OnError onError) {
    checkIfValid();
    if (transaction == null) {
        throw new IllegalArgumentException("Transaction should not be null");
    }
    // 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 SharedRealm (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;
            }
            SharedRealm.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 SharedRealm.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) RealmNotifier(io.realm.internal.RealmNotifier) SharedRealm(io.realm.internal.SharedRealm) RealmException(io.realm.exceptions.RealmException)

Example 25 with RealmException

use of io.realm.exceptions.RealmException in project realm-java by realm.

the class RealmConfiguration method getModuleMediator.

// Finds the mediator associated with a given module.
private static RealmProxyMediator getModuleMediator(String fullyQualifiedModuleClassName) {
    String[] moduleNameParts = fullyQualifiedModuleClassName.split("\\.");
    String moduleSimpleName = moduleNameParts[moduleNameParts.length - 1];
    String mediatorName = String.format("io.realm.%s%s", moduleSimpleName, "Mediator");
    Class<?> clazz;
    //noinspection TryWithIdenticalCatches
    try {
        clazz = Class.forName(mediatorName);
        Constructor<?> constructor = clazz.getDeclaredConstructors()[0];
        constructor.setAccessible(true);
        return (RealmProxyMediator) constructor.newInstance();
    } catch (ClassNotFoundException e) {
        throw new RealmException("Could not find " + mediatorName, e);
    } catch (InvocationTargetException e) {
        throw new RealmException("Could not create an instance of " + mediatorName, e);
    } catch (InstantiationException e) {
        throw new RealmException("Could not create an instance of " + mediatorName, e);
    } catch (IllegalAccessException e) {
        throw new RealmException("Could not create an instance of " + mediatorName, e);
    }
}
Also used : RealmProxyMediator(io.realm.internal.RealmProxyMediator) RealmException(io.realm.exceptions.RealmException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

RealmException (io.realm.exceptions.RealmException)31 Test (org.junit.Test)10 JSONException (org.json.JSONException)9 AllJavaTypes (io.realm.entities.AllJavaTypes)5 JSONObject (org.json.JSONObject)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 TargetApi (android.annotation.TargetApi)3 RealmConfiguration (io.realm.RealmConfiguration)3 AllTypesPrimaryKey (io.realm.entities.AllTypesPrimaryKey)3 Table (io.realm.internal.Table)3 Date (java.util.Date)3 Scanner (java.util.Scanner)3 JSONArray (org.json.JSONArray)3 Realm (io.realm.Realm)2 AllTypes (io.realm.entities.AllTypes)2 RealmPrimaryKeyConstraintException (io.realm.exceptions.RealmPrimaryKeyConstraintException)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 Method (java.lang.reflect.Method)2 ParseException (java.text.ParseException)2