Search in sources :

Example 26 with RealmException

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

the class Realm method createOrUpdateObjectFromJson.

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

Example 27 with RealmException

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

the class Realm method createOrUpdateObjectFromJson.

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

Example 28 with RealmException

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

the class Table method addEmptyRowWithPrimaryKey.

/**
     * Adds an empty row to the table and set the primary key with the given value.
     *
     * @param primaryKeyValue the primary key value.
     * @param validation set to {@code false} to skip all validations. This is currently used by bulk insert which
     *                     has its own validations.
     * @return the row index.
     */
public long addEmptyRowWithPrimaryKey(Object primaryKeyValue, boolean validation) {
    if (validation) {
        checkImmutable();
        checkHasPrimaryKey();
    }
    long primaryKeyColumnIndex = getPrimaryKey();
    RealmFieldType type = getColumnType(primaryKeyColumnIndex);
    long rowIndex;
    // Adds with primary key initially set.
    if (primaryKeyValue == null) {
        switch(type) {
            case STRING:
            case INTEGER:
                if (validation && findFirstNull(primaryKeyColumnIndex) != NO_MATCH) {
                    throwDuplicatePrimaryKeyException("null");
                }
                rowIndex = nativeAddEmptyRow(nativePtr, 1);
                if (type == RealmFieldType.STRING) {
                    nativeSetStringUnique(nativePtr, primaryKeyColumnIndex, rowIndex, null);
                } else {
                    nativeSetNullUnique(nativePtr, primaryKeyColumnIndex, rowIndex);
                }
                break;
            default:
                throw new RealmException("Cannot check for duplicate rows for unsupported primary key type: " + type);
        }
    } else {
        switch(type) {
            case STRING:
                if (!(primaryKeyValue instanceof String)) {
                    throw new IllegalArgumentException("Primary key value is not a String: " + primaryKeyValue);
                }
                if (validation && findFirstString(primaryKeyColumnIndex, (String) primaryKeyValue) != NO_MATCH) {
                    throwDuplicatePrimaryKeyException(primaryKeyValue);
                }
                rowIndex = nativeAddEmptyRow(nativePtr, 1);
                nativeSetStringUnique(nativePtr, primaryKeyColumnIndex, rowIndex, (String) primaryKeyValue);
                break;
            case INTEGER:
                long pkValue;
                try {
                    pkValue = Long.parseLong(primaryKeyValue.toString());
                } catch (RuntimeException e) {
                    throw new IllegalArgumentException("Primary key value is not a long: " + primaryKeyValue);
                }
                if (validation && findFirstLong(primaryKeyColumnIndex, pkValue) != NO_MATCH) {
                    throwDuplicatePrimaryKeyException(pkValue);
                }
                rowIndex = nativeAddEmptyRow(nativePtr, 1);
                nativeSetLongUnique(nativePtr, primaryKeyColumnIndex, rowIndex, pkValue);
                break;
            default:
                throw new RealmException("Cannot check for duplicate rows for unsupported primary key type: " + type);
        }
    }
    return rowIndex;
}
Also used : RealmFieldType(io.realm.RealmFieldType) RealmException(io.realm.exceptions.RealmException)

Example 29 with RealmException

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

the class BulkInsertTests method insert_invalidRealmModel.

@Test
public void insert_invalidRealmModel() {
    InvalidRealmModel invalidRealmModel = new InvalidRealmModel();
    realm.beginTransaction();
    try {
        realm.insert(invalidRealmModel);
        fail("Expected Missing Proxy Class Exception");
    } catch (RealmException ignored) {
    } finally {
        realm.cancelTransaction();
    }
}
Also used : InvalidRealmModel(io.realm.entities.pojo.InvalidRealmModel) RealmException(io.realm.exceptions.RealmException) Test(org.junit.Test)

Example 30 with RealmException

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

the class DynamicRealmObjectTests method untypedSetter_illegalImplicitConversionThrows.

@Test
public void untypedSetter_illegalImplicitConversionThrows() {
    realm.beginTransaction();
    AllJavaTypes obj = realm.createObject(AllJavaTypes.class, 0);
    DynamicRealmObject dObj = new DynamicRealmObject(obj);
    try {
        for (SupportedType type : SupportedType.values()) {
            try {
                switch(type) {
                    case SHORT:
                        dObj.set(AllJavaTypes.FIELD_SHORT, "foo");
                        break;
                    case INT:
                        dObj.set(AllJavaTypes.FIELD_INT, "foo");
                        break;
                    case LONG:
                        dObj.set(AllJavaTypes.FIELD_ID, "foo");
                        break;
                    case FLOAT:
                        dObj.set(AllJavaTypes.FIELD_FLOAT, "foo");
                        break;
                    case DOUBLE:
                        dObj.set(AllJavaTypes.FIELD_DOUBLE, "foo");
                        break;
                    case DATE:
                        dObj.set(AllJavaTypes.FIELD_DATE, "foo");
                        break;
                    // Boolean is special as it returns false for all strings != "true"
                    case BOOLEAN:
                    case BYTE:
                    case OBJECT:
                    case LIST:
                    case STRING:
                    case BINARY:
                        continue;
                    default:
                        fail("Unknown type: " + type);
                }
                fail(type + " failed");
            } catch (IllegalArgumentException ignored) {
            } catch (RealmException e) {
                if (!(e.getCause() instanceof ParseException)) {
                    // Providing "foo" to the date parser will blow up with a RealmException
                    // and the cause will be a ParseException.
                    fail(type + " failed");
                }
            }
        }
    } finally {
        realm.cancelTransaction();
    }
}
Also used : ParseException(java.text.ParseException) AllJavaTypes(io.realm.entities.AllJavaTypes) RealmException(io.realm.exceptions.RealmException) Test(org.junit.Test)

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