use of com.amplifyframework.core.model.SerializedModel in project amplify-android by aws-amplify.
the class SerializedModelAdapter method serialize.
@Override
public JsonElement serialize(SerializedModel src, Type typeOfSrc, JsonSerializationContext context) {
ModelSchema schema = src.getModelSchema();
JsonObject result = new JsonObject();
result.add("id", context.serialize(src.getId()));
result.add("modelSchema", context.serialize(schema));
JsonObject serializedData = new JsonObject();
for (Map.Entry<String, Object> entry : src.getSerializedData().entrySet()) {
if (entry.getValue() instanceof SerializedModel) {
SerializedModel serializedModel = (SerializedModel) entry.getValue();
serializedData.add(entry.getKey(), new JsonPrimitive(serializedModel.getId()));
} else {
serializedData.add(entry.getKey(), context.serialize(entry.getValue()));
}
}
result.add("serializedData", serializedData);
return result;
}
use of com.amplifyframework.core.model.SerializedModel in project amplify-android by aws-amplify.
the class SQLiteStorageAdapter method query.
/**
* {@inheritDoc}
*/
@Override
public void query(@NonNull String modelName, @NonNull QueryOptions options, @NonNull Consumer<Iterator<? extends Model>> onSuccess, @NonNull Consumer<DataStoreException> onError) {
Objects.requireNonNull(modelName);
Objects.requireNonNull(options);
Objects.requireNonNull(onSuccess);
Objects.requireNonNull(onError);
threadPool.submit(() -> {
final ModelSchema modelSchema = schemaRegistry.getModelSchemaForModelClass(modelName);
try (Cursor cursor = sqlCommandProcessor.rawQuery(sqlCommandFactory.queryFor(modelSchema, options))) {
LOG.debug("Querying item for: " + modelName);
final List<Model> models = new ArrayList<>();
final SQLiteModelFieldTypeConverter converter = new SQLiteModelFieldTypeConverter(modelSchema, schemaRegistry, gson);
if (cursor == null) {
onError.accept(new DataStoreException("Error in getting a cursor to the table for class: " + modelName, AmplifyException.TODO_RECOVERY_SUGGESTION));
return;
}
if (cursor.moveToFirst()) {
do {
final Map<String, Object> data = converter.buildMapForModel(cursor);
final SerializedModel model = createSerializedModel(modelSchema, data);
models.add(model);
} while (cursor.moveToNext());
}
onSuccess.accept(models.iterator());
} catch (Exception exception) {
onError.accept(new DataStoreException("Error in querying the model.", exception, "See attached exception for details."));
}
});
}
use of com.amplifyframework.core.model.SerializedModel in project amplify-android by aws-amplify.
the class SQLiteStorageAdapter method query.
/**
* Helper method to synchronously query for a single model instance. Used before any save initiated by
* DATASTORE_API in order to determine which fields have changed.
* @param model a Model that we want to query for the same type and id in SQLite.
* @return the Model instance from SQLite, if it exists, otherwise null.
*/
private Model query(Model model) {
final String modelName = model.getModelName();
final ModelSchema schema = schemaRegistry.getModelSchemaForModelClass(modelName);
final SQLiteTable table = SQLiteTable.fromSchema(schema);
final String primaryKeyName = table.getPrimaryKey().getName();
final QueryPredicate matchId = QueryField.field(modelName, primaryKeyName).eq(model.getId());
Iterator<? extends Model> result = Single.<Iterator<? extends Model>>create(emitter -> {
if (model instanceof SerializedModel) {
query(model.getModelName(), Where.matches(matchId), emitter::onSuccess, emitter::onError);
} else {
query(model.getClass(), Where.matches(matchId), emitter::onSuccess, emitter::onError);
}
}).blockingGet();
return result.hasNext() ? result.next() : null;
}
use of com.amplifyframework.core.model.SerializedModel in project amplify-android by aws-amplify.
the class SQLiteStorageAdapter method save.
/**
* {@inheritDoc}
*/
@Override
public <T extends Model> void save(@NonNull T item, @NonNull StorageItemChange.Initiator initiator, @NonNull QueryPredicate predicate, @NonNull Consumer<StorageItemChange<T>> onSuccess, @NonNull Consumer<DataStoreException> onError) {
Objects.requireNonNull(item);
Objects.requireNonNull(initiator);
Objects.requireNonNull(predicate);
Objects.requireNonNull(onSuccess);
Objects.requireNonNull(onError);
threadPool.submit(() -> {
try {
final ModelSchema modelSchema = schemaRegistry.getModelSchemaForModelClass(item.getModelName());
final StorageItemChange.Type writeType;
SerializedModel patchItem = null;
if (sqlQueryProcessor.modelExists(item, QueryPredicates.all())) {
// if data exists already, then UPDATE the row
writeType = StorageItemChange.Type.UPDATE;
// Check if existing data meets the condition, only if a condition other than all() was provided.
if (!QueryPredicates.all().equals(predicate) && !sqlQueryProcessor.modelExists(item, predicate)) {
throw new DataStoreException("Save failed because condition did not match existing model instance.", "The save will continue to fail until the model instance is updated.");
}
if (initiator == StorageItemChange.Initiator.DATA_STORE_API) {
// When saving items via the DataStore API, compute a SerializedModel of the changed model.
// This is not necessary when save
// is initiated by the sync engine, so skip it for optimization to avoid the extra SQL query.
patchItem = SerializedModel.create(item, modelSchema);
}
} else if (!QueryPredicates.all().equals(predicate)) {
// insert not permitted with a condition
throw new DataStoreException("Conditional update must be performed against an already existing data. " + "Insertion is not permitted while using a predicate.", "Please save without specifying a predicate.");
} else {
// if data doesn't exist yet, then INSERT a new row
writeType = StorageItemChange.Type.CREATE;
}
// execute local save
writeData(item, writeType);
// publish successful save
StorageItemChange<T> change = StorageItemChange.<T>builder().item(item).patchItem(patchItem != null ? patchItem : SerializedModel.create(item, modelSchema)).modelSchema(modelSchema).type(writeType).predicate(predicate).initiator(initiator).build();
itemChangeSubject.onNext(change);
onSuccess.accept(change);
} catch (DataStoreException dataStoreException) {
onError.accept(dataStoreException);
} catch (Exception someOtherTypeOfException) {
String modelToString = item.getModelName() + "[id=" + item.getId() + "]";
DataStoreException dataStoreException = new DataStoreException("Error in saving the model: " + modelToString, someOtherTypeOfException, "See attached exception for details.");
onError.accept(dataStoreException);
}
});
}
use of com.amplifyframework.core.model.SerializedModel in project amplify-android by aws-amplify.
the class AppSyncRequestFactoryTest method validateMutationOnUpdateSerializedModelNestsSerializedCustomTypeWithOnlyChangedFields.
/**
* Validates creation of a serialized model nests serialized custom types.
*
* @throws JSONException from JSONAssert.assertEquals JSON parsing error
* @throws AmplifyException from ModelSchema.fromModelClass to convert model to schema
*/
@Test
public void validateMutationOnUpdateSerializedModelNestsSerializedCustomTypeWithOnlyChangedFields() throws JSONException, AmplifyException {
buildSerializedModelNestsSerializedCustomTypeSchemas();
SchemaRegistry schemaRegistry = SchemaRegistry.instance();
Map<String, Object> phoneSerializedData = new HashMap<>();
phoneSerializedData.put("country", "+1");
phoneSerializedData.put("area", "415");
phoneSerializedData.put("number", "6666666");
SerializedCustomType phone = SerializedCustomType.builder().serializedData(phoneSerializedData).customTypeSchema(schemaRegistry.getCustomTypeSchemaMap().get("Phone")).build();
Map<String, Object> bioSerializedData = new HashMap<>();
bioSerializedData.put("email", "test@testing.com");
bioSerializedData.put("phone", phone);
SerializedCustomType bio = SerializedCustomType.builder().serializedData(bioSerializedData).customTypeSchema(schemaRegistry.getCustomTypeSchemaMap().get("Bio")).build();
Map<String, Object> personSerializedData = new HashMap<>();
personSerializedData.put("id", "123456");
personSerializedData.put("bio", bio);
SerializedModel person = SerializedModel.builder().serializedData(personSerializedData).modelSchema(schemaRegistry.getModelSchemaForModelClass("Person")).build();
String actual = AppSyncRequestFactory.buildUpdateRequest(schemaRegistry.getModelSchemaForModelClass("Person"), person, 1, QueryPredicates.all(), DEFAULT_STRATEGY).getContent();
JSONAssert.assertEquals(Resources.readAsString("update-nested-serialized-model-custom-type.txt"), actual, true);
clearSerializedModelNestsSerializedCustomTypeSchemas();
}
Aggregations