Search in sources :

Example 6 with RealmException

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

the class Realm method createOrUpdateAllFromJson.

/**
     * 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.
     *
     * @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.
     * @see #createOrUpdateAllFromJson(Class, java.io.InputStream)
     */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, InputStream in) throws IOException {
    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();
        }
    }
}
Also used : Scanner(java.util.Scanner) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) RealmException(io.realm.exceptions.RealmException) TargetApi(android.annotation.TargetApi)

Example 7 with RealmException

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

the class Realm method createOrUpdateAllFromJson.

/**
     * 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.
     *
     * @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.
     * @see #createAllFromJson(Class, org.json.JSONArray)
     */
public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, JSONArray json) {
    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);
        }
    }
}
Also used : JSONException(org.json.JSONException) RealmException(io.realm.exceptions.RealmException)

Example 8 with RealmException

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

the class Realm method createObjectInternal.

/**
     * Same as {@link #createObject(Class)} but this does not check the thread.
     *
     * @param clazz the Class of the object to create.
     * @param acceptDefaultValue if {@code true}, default value of the object will be applied and
     *                           if {@code false}, it will be ignored.
     * @return the new object.
     * @throws RealmException if the primary key is defined in the model class or an object cannot be created.
     */
// Called from proxy classes.
<E extends RealmModel> E createObjectInternal(Class<E> clazz, boolean acceptDefaultValue, List<String> excludeFields) {
    Table table = schema.getTable(clazz);
    // Checks and throws the exception earlier for a better exception message.
    if (table.hasPrimaryKey()) {
        throw new RealmException(String.format("'%s' has a primary key, use" + " 'createObject(Class<E>, Object)' instead.", Table.tableNameToClassName(table.getName())));
    }
    long rowIndex = table.addEmptyRow();
    return get(clazz, rowIndex, acceptDefaultValue, excludeFields);
}
Also used : Table(io.realm.internal.Table) RealmException(io.realm.exceptions.RealmException)

Example 9 with RealmException

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

the class Realm method getDefaultModule.

/**
     * Returns the default Realm module. This module contains all Realm classes in the current project, but not those
     * from library or project dependencies. Realm classes in these should be exposed using their own module.
     *
     * @return the default Realm module or {@code null} if no default module exists.
     * @throws RealmException if unable to create an instance of the module.
     * @see io.realm.RealmConfiguration.Builder#modules(Object, Object...)
     */
public static Object getDefaultModule() {
    String moduleName = "io.realm.DefaultRealmModule";
    Class<?> clazz;
    //noinspection TryWithIdenticalCatches
    try {
        clazz = Class.forName(moduleName);
        Constructor<?> constructor = clazz.getDeclaredConstructors()[0];
        constructor.setAccessible(true);
        return constructor.newInstance();
    } catch (ClassNotFoundException e) {
        return null;
    } catch (InvocationTargetException e) {
        throw new RealmException("Could not create an instance of " + moduleName, e);
    } catch (InstantiationException e) {
        throw new RealmException("Could not create an instance of " + moduleName, e);
    } catch (IllegalAccessException e) {
        throw new RealmException("Could not create an instance of " + moduleName, e);
    }
}
Also used : InvocationTargetException(java.lang.reflect.InvocationTargetException) RealmException(io.realm.exceptions.RealmException)

Example 10 with RealmException

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

the class Realm method createObjectFromJson.

/**
     * 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.
     *
     * @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.
     */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public <E extends RealmModel> E createObjectFromJson(Class<E> clazz, InputStream inputStream) throws IOException {
    if (clazz == null || inputStream == null) {
        return null;
    }
    checkIfValid();
    E realmObject;
    Table table = schema.getTable(clazz);
    if (table.hasPrimaryKey()) {
        // 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;
}
Also used : Scanner(java.util.Scanner) Table(io.realm.internal.Table) JSONObject(org.json.JSONObject) InputStreamReader(java.io.InputStreamReader) JSONException(org.json.JSONException) JsonReader(android.util.JsonReader) RealmException(io.realm.exceptions.RealmException) TargetApi(android.annotation.TargetApi)

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