Java 类io.realm.exceptions.RealmException 实例源码

项目:GitHub    文件:Realm.java   
/**
 * 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.
 */
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);
        }
    }
}
项目:GitHub    文件:Realm.java   
/**
 * 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 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 {@link InputStream} 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 failure to read JSON.
 * @see #createObjectFromJson(Class, java.io.InputStream)
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public <E extends RealmModel> E createOrUpdateObjectFromJson(Class<E> clazz, InputStream in) {
    //noinspection ConstantConditions
    if (clazz == null || in == null) {
        return null;
    }
    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);
        JSONObject json = new JSONObject(scanner.next());
        return createOrUpdateObjectFromJson(clazz, json);
    } catch (JSONException e) {
        throw new RealmException("Failed to read JSON", e);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}
项目:GitHub    文件:Realm.java   
/**
 * 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 (OsObjectStore.getPrimaryKeyForObject(
            sharedRealm, configuration.getSchemaMediator().getSimpleClassName(clazz)) != null) {
        throw new RealmException(String.format(Locale.US, "'%s' has a primary key, use" +
                " 'createObject(Class<E>, Object)' instead.", table.getClassName()));
    }
    return configuration.getSchemaMediator().newInstance(clazz, this,
            OsObject.create(table),
            schema.getColumnInfo(clazz),
            acceptDefaultValue, excludeFields);
}
项目:GitHub    文件:Realm.java   
/**
 * If the Realm is a partially synchronized Realm, fetch and synchronize the objects of a given
 * object type that match the given query (in string format).
 *
 * The results will be returned asynchronously in the callback.
 *
 * @param clazz the class to query.
 * @param query string query.
 * @param callback A callback used to vend the results of a partial sync fetch.
 * @throws IllegalStateException if it is called from a non-Looper or {@link IntentService} thread.
 * @throws IllegalStateException if called from a non-synchronized (Realm Object Server) Realm.
 */
@Beta
public <E extends RealmModel> void subscribeToObjects(final Class<E> clazz, String query, final PartialSyncCallback<E> callback) {
    checkIfValid();
    if (!configuration.isSyncConfiguration()) {
        throw new IllegalStateException("Partial sync is only available for synchronized Realm (Realm Object Server)");
    }

    sharedRealm.capabilities.checkCanDeliverNotification(BaseRealm.LISTENER_NOT_ALLOWED_MESSAGE);

    String className = configuration.getSchemaMediator().getSimpleClassName(clazz);
    OsSharedRealm.PartialSyncCallback internalCallback = new OsSharedRealm.PartialSyncCallback(className) {
        @Override
        public void onSuccess(OsResults osResults) {
            RealmResults<E> results = new RealmResults<>(Realm.this, osResults, clazz);
            callback.onSuccess(results);
        }

        @Override
        public void onError(RealmException error) {
            callback.onError(error);
        }
    };

    sharedRealm.registerPartialSyncQuery(query, internalCallback);
}
项目:GitHub    文件:OsObject.java   
/**
 * Create an object in the given table which has a primary key column defined, and set the primary key with given
 * value.
 *
 * @param table the table where the object is created. This table must be atached to {@link OsSharedRealm}.
 * @return a newly created {@code UncheckedRow}.
 */
public static UncheckedRow createWithPrimaryKey(Table table, @Nullable Object primaryKeyValue) {
    long primaryKeyColumnIndex = getAndVerifyPrimaryKeyColumnIndex(table);
    RealmFieldType type = table.getColumnType(primaryKeyColumnIndex);
    final OsSharedRealm sharedRealm = table.getSharedRealm();

    if (type == RealmFieldType.STRING) {
        if (primaryKeyValue != null && !(primaryKeyValue instanceof String)) {
            throw new IllegalArgumentException("Primary key value is not a String: " + primaryKeyValue);
        }
        return new UncheckedRow(sharedRealm.context, table,
                nativeCreateNewObjectWithStringPrimaryKey(sharedRealm.getNativePtr(), table.getNativePtr(),
                        primaryKeyColumnIndex, (String) primaryKeyValue));

    } else if (type == RealmFieldType.INTEGER) {
        long value = primaryKeyValue == null ? 0 : Long.parseLong(primaryKeyValue.toString());
        return new UncheckedRow(sharedRealm.context, table,
                nativeCreateNewObjectWithLongPrimaryKey(sharedRealm.getNativePtr(), table.getNativePtr(),
                        primaryKeyColumnIndex, value, primaryKeyValue == null));
    } else {
        throw new RealmException("Cannot check for duplicate rows for unsupported primary key type: " + type);
    }
}
项目:GitHub    文件:OsObject.java   
/**
 * Create an object in the given table which has a primary key column defined, and set the primary key with given
 * value.
 * This is used for the fast bulk insertion.
 *
 * @param table the table where the object is created.
 * @param primaryKeyColumnIndex the column index of primary key field.
 * @param primaryKeyValue the primary key value.
 * @return a newly created {@code UncheckedRow}.
 */
// FIXME: Proxy could just pass the pk index here which is much faster.
public static long createRowWithPrimaryKey(Table table, long primaryKeyColumnIndex, Object primaryKeyValue) {
    RealmFieldType type = table.getColumnType(primaryKeyColumnIndex);
    final OsSharedRealm sharedRealm = table.getSharedRealm();

    if (type == RealmFieldType.STRING) {
        if (primaryKeyValue != null && !(primaryKeyValue instanceof String)) {
            throw new IllegalArgumentException("Primary key value is not a String: " + primaryKeyValue);
        }
        return nativeCreateRowWithStringPrimaryKey(sharedRealm.getNativePtr(), table.getNativePtr(),
                primaryKeyColumnIndex, (String) primaryKeyValue);

    } else if (type == RealmFieldType.INTEGER) {
        long value = primaryKeyValue == null ? 0 : Long.parseLong(primaryKeyValue.toString());
        return nativeCreateRowWithLongPrimaryKey(sharedRealm.getNativePtr(), table.getNativePtr(),
                primaryKeyColumnIndex, value, primaryKeyValue == null);
    } else {
        throw new RealmException("Cannot check for duplicate rows for unsupported primary key type: " + type);
    }
}
项目:GitHub    文件:ColumnIndices.java   
/**
 * Returns the {@link ColumnInfo} for the passed class name.
 *
 * @param simpleClassName the simple name of the class for which to get the ColumnInfo.
 * @return the corresponding {@link ColumnInfo} object.
 * @throws io.realm.exceptions.RealmException if the class cannot be found in the schema.
 */
@Nonnull
public ColumnInfo getColumnInfo(String simpleClassName) {
    ColumnInfo columnInfo = simpleClassNameToColumnInfoMap.get(simpleClassName);
    if (columnInfo == null) {
        Set<Class<? extends RealmModel>> modelClasses = mediator.getModelClasses();
        for (Class<? extends RealmModel> modelClass : modelClasses) {
            if (mediator.getSimpleClassName(modelClass).equals(simpleClassName)) {
                columnInfo = getColumnInfo(modelClass);
                simpleClassNameToColumnInfoMap.put(simpleClassName, columnInfo);
                break;
            }
        }
    }
    if (columnInfo == null) {
        throw new RealmException(
                String.format(Locale.US, "'%s' doesn't exist in current schema.", simpleClassName));
    }
    return columnInfo;
}
项目:GitHub    文件:RealmJsonTests.java   
@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());
}
项目:GitHub    文件:RealmJsonTests.java   
@Test
public void createOrUpdateObjectFromJson_streamInvalidJson() throws IOException {
    assumeThat(Build.VERSION.SDK_INT, greaterThanOrEqualTo(Build.VERSION_CODES.HONEYCOMB));

    AllTypesPrimaryKey obj = new AllTypesPrimaryKey();
    obj.setColumnLong(1);
    realm.beginTransaction();
    realm.copyToRealm(obj);
    realm.commitTransaction();

    InputStream in = TestHelper.loadJsonFromAssets(context, "all_types_invalid.json");
    realm.beginTransaction();
    try {
        realm.createOrUpdateObjectFromJson(AllTypesPrimaryKey.class, in);
        fail();
    } catch (RealmException ignored) {
    } finally {
        realm.commitTransaction();
        in.close();
    }
}
项目:GitHub    文件:RealmJsonTests.java   
@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());
}
项目:GitHub    文件:LinkingObjectsManagedTests.java   
@Test
public void json_updateObject() {
    realm.beginTransaction();
    AllJavaTypes child = realm.createObject(AllJavaTypes.class, 1);
    AllJavaTypes parent = realm.createObject(AllJavaTypes.class, 2);
    parent.setFieldObject(child);
    realm.commitTransaction();

    RealmResults<AllJavaTypes> parents = child.getObjectParents();
    assertNotNull(parents);
    assertEquals(1, parents.size());
    assertTrue(parents.contains(parent));

    realm.beginTransaction();
    try {
        realm.createOrUpdateAllFromJson(AllJavaTypes.class, "[{ \"fieldId\" : 1, \"objectParents\" : null }]");
    } catch (RealmException e) {
        fail("Failed loading JSON" + e);
    }
    realm.commitTransaction();

    parents = child.getObjectParents();
    assertNotNull(parents);
    assertEquals(1, parents.size());
    assertTrue(parents.contains(parent));
}
项目:GitHub    文件:LinkingObjectsManagedTests.java   
@Test
public void json_updateList() {
    realm.beginTransaction();
    AllJavaTypes child = realm.createObject(AllJavaTypes.class, 1);
    AllJavaTypes parent = realm.createObject(AllJavaTypes.class, 2);
    parent.getFieldList().add(child);
    realm.commitTransaction();

    RealmResults<AllJavaTypes> parents = child.getListParents();
    assertNotNull(parents);
    assertEquals(1, parents.size());
    assertTrue(parents.contains(parent));

    realm.beginTransaction();
    try {
        realm.createOrUpdateAllFromJson(AllJavaTypes.class, "[{ \"fieldId\" : 1, \"listParents\" : null }]");
    } catch (RealmException e) {
        fail("Failed loading JSON" + e);
    }
    realm.commitTransaction();

    parents = child.getListParents();
    assertNotNull(parents);
    assertEquals(1, parents.size());
    assertTrue(parents.contains(parent));
}
项目:ocreader    文件:Queries.java   
public static void setItemsUnread(Realm realm, final boolean newUnread, final Item... items) {
    realm.executeTransaction(realm1 -> {
        try {
            for (Item item : items) {
                /* If the item has a fingerprint, mark all items with the same fingerprint
                  as read
                 */
                if(item.getFingerprint() == null) {
                    item.setUnread(newUnread);
                } else {
                    RealmResults<Item> sameItems = realm1.where(Item.class)
                            .equalTo(Item.FINGERPRINT, item.getFingerprint())
                            .equalTo(Item.UNREAD, !newUnread)
                            .findAll();
                    for(Item sameItem: sameItems) {
                        sameItem.setUnread(newUnread);
                    }
                }
            }
        } catch (RealmException e) {
            Log.e(TAG, "Failed to set item as unread", e);
        } finally {
            checkAlarm(realm1);
        }
    });
}
项目:orchextra-android-sdk    文件:OrchextraStatusDBDataSourceImpl.java   
@Override public BusinessObject<OrchextraStatus> saveStatus(OrchextraStatus orchextraStatus) {
  Realm realm = realmDefaultInstance.createRealmInstance(context);
  OrchextraStatus result = null;
  try {
    realm.beginTransaction();
    result = orchextraStatusUpdater.saveStatus(realm, orchextraStatus);
    //TODO Store crm and session
  } catch (RealmException re) {
    return new BusinessObject<>(null, BusinessError.createKoInstance(re.getMessage()));
  } finally {
    if (realm != null) {
      realm.commitTransaction();
      realm.close();
    }
  }
  return new BusinessObject<>(result, BusinessError.createOKInstance());
}
项目:orchextra-android-sdk    文件:OrchextraStatusDBDataSourceImpl.java   
@Override public BusinessObject<OrchextraStatus> loadStatus() {
  Realm realm = realmDefaultInstance.createRealmInstance(context);
  OrchextraStatus result = null;
  try {
    result = orchextraStatusReader.readStatus(realm);
    //TODO retrieve crm and session
  } catch (NotFountRealmObjectException exception) {
    orchextraLogger.log(
        "orchextraStatus info not present, new data will be created: " + exception.getMessage(),
        OrchextraSDKLogLevel.WARN);
    return new BusinessObject<>(OrchextraStatus.getInstance(), BusinessError.createOKInstance());
  } catch (RealmException re) {
    return new BusinessObject<>(null, BusinessError.createKoInstance(re.getMessage()));
  } finally {
    if (realm != null) {
      realm.close();
    }
  }
  return new BusinessObject<>(result, BusinessError.createOKInstance());
}
项目:orchextra-android-sdk    文件:SessionDBDataSourceImpl.java   
@Override public boolean saveSdkAuthCredentials(SdkAuthCredentials sdkAuthCredentials) {
  Realm realm = realmDefaultInstance.createRealmInstance(context);

  try {
    realm.beginTransaction();
    sessionUpdater.updateSdkAuthCredentials(realm, sdkAuthCredentials);
  } catch (RealmException re) {
    return false;
  } finally {
    if (realm != null) {
      realm.commitTransaction();
      realm.close();
    }
  }

  return true;
}
项目:orchextra-android-sdk    文件:SessionDBDataSourceImpl.java   
@Override public boolean saveSdkAuthResponse(SdkAuthData sdkAuthData) {
  Realm realm = realmDefaultInstance.createRealmInstance(context);

  try {
    realm.beginTransaction();
    sessionUpdater.updateSdkAuthResponse(realm, sdkAuthData);
  } catch (RealmException re) {
    return false;
  } finally {
    if (realm != null) {
      realm.commitTransaction();
      realm.close();
    }
  }

  return true;
}
项目:orchextra-android-sdk    文件:SessionDBDataSourceImpl.java   
@Override public boolean saveClientAuthCredentials(ClientAuthCredentials clientAuthCredentials) {
  Realm realm = realmDefaultInstance.createRealmInstance(context);

  try {
    realm.beginTransaction();
    sessionUpdater.updateClientAuthCredentials(realm, clientAuthCredentials);
  } catch (RealmException re) {
    return false;
  } finally {
    if (realm != null) {
      realm.commitTransaction();
      realm.close();
    }
  }

  return true;
}
项目:orchextra-android-sdk    文件:SessionDBDataSourceImpl.java   
@Override public boolean saveClientAuthResponse(ClientAuthData clientAuthData) {
  Realm realm = realmDefaultInstance.createRealmInstance(context);

  try {
    realm.beginTransaction();
    sessionUpdater.updateClientAuthResponse(realm, clientAuthData);
  } catch (RealmException re) {
    return false;
  } finally {
    if (realm != null) {
      realm.commitTransaction();
      realm.close();
    }
  }

  return true;
}
项目:orchextra-android-sdk    文件:SessionDBDataSourceImpl.java   
@Override public boolean saveUser(CrmUser crmUser) {
  Realm realm = realmDefaultInstance.createRealmInstance(context);

  try {
    realm.beginTransaction();
    sessionUpdater.updateCrm(realm, crmUser);
  } catch (RealmException re) {
    return false;
  } finally {
    if (realm != null) {
      realm.commitTransaction();
      realm.close();
    }
  }

  return true;
}
项目:orchextra-android-sdk    文件:SessionDBDataSourceImpl.java   
@Override public boolean storeCrm(CrmUser crmUser) {
  Realm realm = realmDefaultInstance.createRealmInstance(context);

  try {
    realm.beginTransaction();
    sessionUpdater.updateCrm(realm, crmUser);
  } catch (RealmException re) {
    return false;
  } finally {
    if (realm != null) {
      realm.commitTransaction();
      realm.close();
    }
  }
  return true;
}
项目:orchextra-android-sdk    文件:SessionDBDataSourceImpl.java   
@Override
public void clearAuthenticatedSdk() {
  Realm realm = realmDefaultInstance.createRealmInstance(context);
  try {
    realm.beginTransaction();
    realm.clear(SdkAuthCredentialsRealm.class);
    realm.clear(SdkAuthRealm.class);
  } catch (RealmException re) {

  } finally {
    if (realm != null) {
      realm.commitTransaction();
      realm.close();
    }
  }
}
项目:GitHub    文件:DynamicRealm.java   
/**
 * 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);
    String pkField = OsObjectStore.getPrimaryKeyForObject(sharedRealm, className);
    // Check and throw the exception earlier for a better exception message.
    if (pkField != null) {
        throw new RealmException(String.format(Locale.US,
                "'%s' has a primary key field '%s', use  'createObject(String, Object)' instead.",
                className, pkField));
    }

    return new DynamicRealmObject(this, CheckedRow.getFromRow(OsObject.create(table)));
}
项目:GitHub    文件:Realm.java   
/**
 * 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.
 * @see #createOrUpdateAllFromJson(Class, java.io.InputStream)
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
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();
        }
    }
}
项目:GitHub    文件:Realm.java   
/**
 * 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.
 */
@Nullable
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
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;
}
项目:GitHub    文件:OsSharedRealm.java   
/**
 * Called from JNI when the partial sync callback is invoked from the ObjectStore.
 *
 * @param error            if the partial sync query failed to register.
 * @param nativeResultsPtr pointer to the {@code Results} of the partial sync query.
 * @param callback         the callback registered from the user to notify the success/error of the partial sync query.
 */
@SuppressWarnings("unused")
private void runPartialSyncRegistrationCallback(@Nullable String error, long nativeResultsPtr,
                                                PartialSyncCallback callback) {
    if (error != null) {
        callback.onError(new RealmException(error));
    } else {
        @SuppressWarnings("ConstantConditions")
        Table table = getTable(Table.getTableNameForClass(callback.className));
        OsResults results = new OsResults(this, table, nativeResultsPtr);
        callback.onSuccess(results);
    }
}
项目:GitHub    文件:RealmConfiguration.java   
/**
 * Setting this will create an in-memory Realm instead of saving it to disk. In-memory Realms might still use
 * disk space if memory is running low, but all files created by an in-memory Realm will be deleted when the
 * Realm is closed.
 * <p>
 * Note that because in-memory Realms are not persisted, you must be sure to hold on to at least one non-closed
 * reference to the in-memory Realm object with the specific name as long as you want the data to last.
 */
public Builder inMemory() {
    if (!Util.isEmptyString(assetFilePath)) {
        throw new RealmException("Realm can not use in-memory configuration if asset file is present.");
    }

    this.durability = OsRealmConfig.Durability.MEM_ONLY;

    return this;
}
项目:GitHub    文件:RealmTests.java   
@Test
public void createObject_cannotCreateDynamicRealmObject() {
    realm.beginTransaction();
    try {
        realm.createObject(DynamicRealmObject.class);
        fail();
    } catch (RealmException ignored) {
    }
}
项目:GitHub    文件:RealmJsonTests.java   
@Test
public void createObjectFromJson_stringFaultyJsonThrows() {
    realm.beginTransaction();
    try {
        realm.createObjectFromJson(Dog.class, "{ name \"Foo\" }");
        fail("Faulty JSON should result in a RealmException");
    } catch (RealmException ignored) {
    } finally {
        realm.commitTransaction();
    }
}
项目:GitHub    文件:RealmJsonTests.java   
@Test
public void createAllFromJson_stringArrayFaultyJsonThrows() {
    realm.beginTransaction();
    try {
        realm.createAllFromJson(Dog.class, "[{ name : \"Foo\" ]");
        fail("Faulty JSON should result in a RealmException");
    } catch (RealmException ignored) {
    } finally {
        realm.commitTransaction();
    }
}
项目:GitHub    文件:RealmJsonTests.java   
@Test
public void createObjectFromJson_streamNullJson() throws IOException {
    assumeThat(Build.VERSION.SDK_INT, greaterThanOrEqualTo(Build.VERSION_CODES.HONEYCOMB));

    InputStream in = TestHelper.loadJsonFromAssets(context, "all_types_invalid.json");
    realm.beginTransaction();
    try {
        realm.createObjectFromJson(AnnotationTypes.class, in);
        fail();
    } catch (RealmException ignored) {
    } finally {
        realm.commitTransaction();
        in.close();
    }
}
项目:GitHub    文件:RealmJsonTests.java   
@Test
public void createOrUpdateAllFromJson_streamInvalidJSonCurlyBracketThrows() throws IOException {
    assumeThat(Build.VERSION.SDK_INT, greaterThanOrEqualTo(Build.VERSION_CODES.HONEYCOMB));

    try {
        realm.createOrUpdateAllFromJson(AllTypesPrimaryKey.class, TestHelper.stringToStream("{"));
        fail();
    } catch (RealmException ignored) {
    }
}
项目:GitHub    文件:RealmJsonTests.java   
@Test
public void createOrUpdateObjectFromJson_invalidInputString() throws IOException {
    TestHelper.populateSimpleAllTypesPrimaryKey(realm);

    realm.beginTransaction();
    try {
        realm.createOrUpdateObjectFromJson(AllTypesPrimaryKey.class, "{ \"columnLong\" : 1,");
        fail();
    } catch (RealmException ignored) {
    } finally {
        realm.commitTransaction();
    }
}
项目:GitHub    文件:RealmJsonTests.java   
@Test
public void createOrUpdateAllFromJson_streamInvalidJSonBracketThrows() throws IOException {
    assumeThat(Build.VERSION.SDK_INT, greaterThanOrEqualTo(Build.VERSION_CODES.HONEYCOMB));

    try {
        realm.createOrUpdateAllFromJson(AllTypesPrimaryKey.class, TestHelper.stringToStream("["));
        fail();
    } catch (RealmException ignored) {
    }
}
项目:GitHub    文件:RealmJsonTests.java   
@Test
public void createOrUpdateAllFromJson_inputStringInvalidJson() {
    realm.beginTransaction();
    try {
        realm.createOrUpdateAllFromJson(AllTypesPrimaryKey.class, "{ \"columnLong\" : 1");
        fail();
    } catch (RealmException ignored) {
    } finally {
        realm.commitTransaction();
    }
}
项目:GitHub    文件:RealmConfigurationTests.java   
@Test
public void assetFileWithInMemoryConfig() {
    // Ensures that there is no data.
    Realm.deleteRealm(new RealmConfiguration.Builder(context).build());

    try {
        new RealmConfiguration.Builder(context).assetFile("asset_file.realm").inMemory().build();
        fail();
    } catch (RealmException ignored) {
    }
}
项目:GitHub    文件:JsonUtilsTest.java   
public void testParseInvalidDateShouldThrowRealmException() {
    String invalidLongDate = "123abc";
    try {
        Date d = JsonUtils.stringToDate(invalidLongDate);
        fail("Should fail with a RealmException.");
    } catch (RealmException e) {
        assertNotNull(e);
        assertTrue(e.getCause() instanceof ParseException);
    }
}
项目:GitHub    文件:JsonUtilsTest.java   
public void testParseInvalidNumericDateShouldThrowRealmException() {
    String invalidLongDate = "2342347289374398342759873495743"; // not a date.
    try {
        Date d = JsonUtils.stringToDate(invalidLongDate);
        fail("Should fail with a RealmException.");
    } catch (RealmException e) {
        assertNotNull(e);
        assertTrue(e.getCause() instanceof NumberFormatException);
    }
}
项目:GitHub    文件:RealmObjectTests.java   
@Test
public void setter_changePrimaryKeyThrows() {
    realm.beginTransaction();
    AllJavaTypes allJavaTypes = realm.createObject(AllJavaTypes.class, 42);
    thrown.expect(RealmException.class);
    allJavaTypes.setFieldId(111);
    realm.cancelTransaction();
}
项目:GitHub    文件:BulkInsertTests.java   
@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();
    }
}