Search in sources :

Example 6 with SerializedModel

use of com.amplifyframework.core.model.SerializedModel in project amplify-android by aws-amplify.

the class InMemoryStorageAdapter method delete.

// item.getClass() -> Class<?>, but type is T. So cast as Class<T> is OK.
@SuppressWarnings("unchecked")
@Override
public <T extends Model> void delete(@NonNull final T item, @NonNull final StorageItemChange.Initiator initiator, @NonNull final QueryPredicate predicate, @NonNull final Consumer<StorageItemChange<T>> onSuccess, @NonNull final Consumer<DataStoreException> onError) {
    final int index = indexOf(item);
    if (index < 0) {
        onError.accept(new DataStoreException("This item was not found in the datastore: " + item.toString(), "Use save() function to create models to store."));
        return;
    }
    Model savedItem = items.remove(index);
    final ModelSchema schema;
    final SerializedModel patchItem;
    try {
        schema = ModelSchema.fromModelClass(item.getClass());
        patchItem = SerializedModel.create(savedItem, schema);
    } catch (AmplifyException schemaBuildFailure) {
        onError.accept(new DataStoreException("Failed to build model schema.", schemaBuildFailure, "Verify your model."));
        return;
    }
    if (!predicate.evaluate(savedItem)) {
        onError.accept(new DataStoreException("Conditional check failed.", "Verify that there is a saved model that matches the provided predicate."));
        return;
    }
    StorageItemChange<T> deletion = StorageItemChange.<T>builder().item((T) savedItem).patchItem(patchItem).modelSchema(schema).type(StorageItemChange.Type.DELETE).predicate(predicate).initiator(initiator).build();
    itemChangeStream.onNext(deletion);
    onSuccess.accept(deletion);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) DataStoreException(com.amplifyframework.datastore.DataStoreException) AmplifyException(com.amplifyframework.AmplifyException) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) SerializedModel(com.amplifyframework.core.model.SerializedModel)

Example 7 with SerializedModel

use of com.amplifyframework.core.model.SerializedModel in project amplify-android by aws-amplify.

the class InMemoryStorageAdapter method save.

@Override
public <T extends Model> void save(@NonNull final T item, @NonNull final StorageItemChange.Initiator initiator, @NonNull final QueryPredicate predicate, @NonNull final Consumer<StorageItemChange<T>> onSuccess, @NonNull final Consumer<DataStoreException> onError) {
    StorageItemChange.Type type = StorageItemChange.Type.CREATE;
    final int index = indexOf(item);
    Model savedItem = null;
    if (index > -1) {
        // There is an existing record with that ID; this is an update.
        type = StorageItemChange.Type.UPDATE;
        savedItem = items.get(index);
        if (!predicate.evaluate(savedItem)) {
            onError.accept(new DataStoreException("Conditional check failed.", "Verify that there is a saved model that matches the provided predicate."));
            return;
        } else {
            items.remove(index);
        }
    }
    final ModelSchema schema;
    final SerializedModel patchItem;
    try {
        schema = ModelSchema.fromModelClass(item.getClass());
        patchItem = SerializedModel.difference(item, savedItem, schema);
    } catch (AmplifyException schemaBuildFailure) {
        onError.accept(new DataStoreException("Failed to build model schema.", schemaBuildFailure, "Verify your model."));
        return;
    }
    items.add(item);
    StorageItemChange<T> change = StorageItemChange.<T>builder().item(item).patchItem(patchItem).modelSchema(schema).type(type).predicate(predicate).initiator(initiator).build();
    itemChangeStream.onNext(change);
    onSuccess.accept(change);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) DataStoreException(com.amplifyframework.datastore.DataStoreException) AmplifyException(com.amplifyframework.AmplifyException) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) SerializedModel(com.amplifyframework.core.model.SerializedModel)

Example 8 with SerializedModel

use of com.amplifyframework.core.model.SerializedModel in project amplify-android by aws-amplify.

the class ModelWithMetadataAdapterTest method adapterCanDeserializeJsonOfSerializedModelIntoMwm.

/**
 * The Gson adapter can be used to deserialize JSON into a ModelWithMetadata object.
 */
@Test
public void adapterCanDeserializeJsonOfSerializedModelIntoMwm() {
    // Arrange expected value
    Map<String, Object> postSerializedData = new HashMap<>();
    postSerializedData.put("comments", null);
    postSerializedData.put("created", "2022-02-19T00:05:26.607465000");
    postSerializedData.put("rating", 12);
    postSerializedData.put("blog", null);
    postSerializedData.put("title", "52 TITLE");
    postSerializedData.put("tags", null);
    postSerializedData.put("createdAt", "2022-02-19T00:05:33.564Z");
    postSerializedData.put("id", "21ee0180-60a4-45d9-b68e-018c260cc742");
    postSerializedData.put("updatedAt", "2022-03-04T05:36:26.629Z");
    SerializedModel model = SerializedModel.builder().serializedData(postSerializedData).modelSchema(null).build();
    Temporal.Timestamp lastChangedAt = new Temporal.Timestamp(1594858827, TimeUnit.SECONDS);
    ModelMetadata metadata = new ModelMetadata(model.getId(), false, 3, lastChangedAt);
    ModelWithMetadata<SerializedModel> expected = new ModelWithMetadata<>(model, metadata);
    // Arrange some JSON, and then try to deserialize it
    String json = Resources.readAsString("serialized-model-with-metadata.json");
    Type type = TypeMaker.getParameterizedType(ModelWithMetadata.class, SerializedModel.class);
    ModelWithMetadata<SerializedModel> actual = gson.fromJson(json, type);
    // Assert that the deserialized output matches out expected value
    Assert.assertEquals(expected, actual);
}
Also used : Type(java.lang.reflect.Type) Temporal(com.amplifyframework.core.model.temporal.Temporal) HashMap(java.util.HashMap) JSONObject(org.json.JSONObject) SerializedModel(com.amplifyframework.core.model.SerializedModel) Test(org.junit.Test)

Example 9 with SerializedModel

use of com.amplifyframework.core.model.SerializedModel in project amplify-android by aws-amplify.

the class SerializedModelAdapterTest method serdeForNestedSerializedModels.

/**
 * Tests serialization and deserialization of a model that contains an association to another
 * model.
 * @throws JSONException On illegal json found by JSONAssert
 */
@Test
public void serdeForNestedSerializedModels() throws JSONException {
    Map<String, Object> blogOwnerSerializedData = new HashMap<>();
    blogOwnerSerializedData.put("name", "A responsible blogger");
    blogOwnerSerializedData.put("id", "2cb080ce-bc93-44c6-aa77-f985af311afa");
    Map<String, Object> blogSerializedData = new HashMap<>();
    blogSerializedData.put("name", "A fine blog");
    blogSerializedData.put("owner", SerializedModel.builder().serializedData(Collections.singletonMap("id", blogOwnerSerializedData.get("id"))).modelSchema(null).build());
    blogSerializedData.put("id", "3d128fdd-17a8-45ea-a166-44f6712b86f4");
    SerializedModel blogAsSerializedModel = SerializedModel.builder().serializedData(blogSerializedData).modelSchema(modelSchemaForBlog()).build();
    String resourcePath = "serde-for-blog-in-serialized-model.json";
    String expectedJson = new JSONObject(Resources.readAsString(resourcePath)).toString(2);
    String actualJson = new JSONObject(gson.toJson(blogAsSerializedModel)).toString(2);
    Assert.assertEquals(expectedJson, actualJson);
    SerializedModel recovered = gson.fromJson(expectedJson, SerializedModel.class);
    Assert.assertEquals(blogAsSerializedModel, recovered);
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) JSONObject(org.json.JSONObject) SerializedModel(com.amplifyframework.core.model.SerializedModel) Test(org.junit.Test)

Example 10 with SerializedModel

use of com.amplifyframework.core.model.SerializedModel in project amplify-android by aws-amplify.

the class SerializedModelAdapterTest method serdeForSerializedModelWithTemporals.

/**
 * Tests serialization and deserialization of a simple model that contains temporal types.
 * @throws JSONException if Illegal JSON found in JSONAssert call
 */
@Test
public void serdeForSerializedModelWithTemporals() throws JSONException {
    Map<String, Object> serializedData = new HashMap<>();
    serializedData.put("id", "970f1b78-8786-4762-a43a-17c70f966684");
    serializedData.put("name", "Special meeting of the minds");
    serializedData.put("date", "2020-11-05Z");
    serializedData.put("dateTime", "2020-11-05T03:44:28Z");
    serializedData.put("time", "03:44:28Z");
    serializedData.put("timestamp", 1604547868);
    // Now, the real stuff. Build a serialized model, that we can serialize.
    SerializedModel serializedModel = SerializedModel.builder().serializedData(serializedData).modelSchema(modelSchemaForMeeting()).build();
    String expectedResourcePath = "serde-for-meeting-in-serialized-model.json";
    String expectedJson = Resources.readAsJson(expectedResourcePath).toString(2);
    String actualJson = new JSONObject(gson.toJson(serializedModel)).toString(2);
    JSONAssert.assertEquals(expectedJson, actualJson, true);
    SerializedModel recovered = gson.fromJson(expectedJson, SerializedModel.class);
    Assert.assertEquals(serializedModel, recovered);
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) JSONObject(org.json.JSONObject) SerializedModel(com.amplifyframework.core.model.SerializedModel) Test(org.junit.Test)

Aggregations

SerializedModel (com.amplifyframework.core.model.SerializedModel)37 Test (org.junit.Test)21 HashMap (java.util.HashMap)18 ModelSchema (com.amplifyframework.core.model.ModelSchema)16 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)8 AmplifyException (com.amplifyframework.AmplifyException)7 Model (com.amplifyframework.core.model.Model)7 DataStoreException (com.amplifyframework.datastore.DataStoreException)6 ModelField (com.amplifyframework.core.model.ModelField)5 ArrayList (java.util.ArrayList)5 ModelAssociation (com.amplifyframework.core.model.ModelAssociation)4 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)4 SerializedCustomType (com.amplifyframework.core.model.SerializedCustomType)4 StorageItemChange (com.amplifyframework.datastore.storage.StorageItemChange)4 Blog (com.amplifyframework.testmodels.commentsblog.Blog)4 HubAccumulator (com.amplifyframework.testutils.HubAccumulator)4 Map (java.util.Map)4 Ignore (org.junit.Ignore)4 Temporal (com.amplifyframework.core.model.temporal.Temporal)3 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)3