Search in sources :

Example 16 with SerializedModel

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

the class AppSyncRequestFactoryTest method validateMutationOnCreationSerializedModelNestsSerializedCustomType.

/**
 * 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 validateMutationOnCreationSerializedModelNestsSerializedCustomType() 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> addressSerializedData1 = new HashMap<>();
    addressSerializedData1.put("line1", "222 Somewhere far");
    addressSerializedData1.put("line2", "apt 3");
    addressSerializedData1.put("city", "SFO");
    addressSerializedData1.put("state", "CA");
    addressSerializedData1.put("postalCode", "94105");
    SerializedCustomType address1 = SerializedCustomType.builder().serializedData(addressSerializedData1).customTypeSchema(schemaRegistry.getCustomTypeSchemaMap().get("Address")).build();
    Map<String, Object> addressSerializedData2 = new HashMap<>();
    addressSerializedData2.put("line1", "333 Somewhere close");
    addressSerializedData2.put("line2", null);
    addressSerializedData2.put("city", "SEA");
    addressSerializedData2.put("state", "WA");
    addressSerializedData2.put("postalCode", "00000");
    SerializedCustomType address2 = SerializedCustomType.builder().serializedData(addressSerializedData2).customTypeSchema(schemaRegistry.getCustomTypeSchemaMap().get("Address")).build();
    ArrayList<SerializedCustomType> addressesList = new ArrayList<>();
    addressesList.add(address1);
    addressesList.add(address2);
    Map<String, Object> personSerializedData = new HashMap<>();
    personSerializedData.put("id", "123456");
    personSerializedData.put("name", "Tester Testing");
    personSerializedData.put("bio", bio);
    personSerializedData.put("mailingAddresses", addressesList);
    SerializedModel person = SerializedModel.builder().serializedData(personSerializedData).modelSchema(schemaRegistry.getModelSchemaForModelClass("Person")).build();
    String actual = AppSyncRequestFactory.buildCreationRequest(schemaRegistry.getModelSchemaForModelClass("Person"), person, DEFAULT_STRATEGY).getContent();
    JSONAssert.assertEquals(Resources.readAsString("create-nested-serialized-model-custom-type.txt"), actual, true);
    clearSerializedModelNestsSerializedCustomTypeSchemas();
}
Also used : HashMap(java.util.HashMap) SerializedCustomType(com.amplifyframework.core.model.SerializedCustomType) ArrayList(java.util.ArrayList) SerializedModel(com.amplifyframework.core.model.SerializedModel) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Test(org.junit.Test)

Example 17 with SerializedModel

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

the class SubscriptionProcessor method mergeEvent.

private Completable mergeEvent(SubscriptionEvent<? extends Model> event) {
    ModelWithMetadata<? extends Model> original = event.modelWithMetadata();
    if (original.getModel() instanceof SerializedModel) {
        SerializedModel originalModel = (SerializedModel) original.getModel();
        SerializedModel newModel = SerializedModel.builder().serializedData(SerializedModel.parseSerializedData(originalModel.getSerializedData(), event.modelSchema().getName(), schemaRegistry)).modelSchema(event.modelSchema()).build();
        return merger.merge(new ModelWithMetadata<>(newModel, original.getSyncMetadata()));
    } else {
        return merger.merge(original);
    }
}
Also used : SerializedModel(com.amplifyframework.core.model.SerializedModel)

Example 18 with SerializedModel

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

the class AppSyncRequestFactory method getMapOfFieldNameAndValues.

private static Map<String, Object> getMapOfFieldNameAndValues(@NonNull ModelSchema schema, @NonNull Model instance) throws AmplifyException {
    boolean isSerializedModel = instance instanceof SerializedModel;
    boolean hasMatchingModelName = instance.getClass().getSimpleName().equals(schema.getName());
    if (!(hasMatchingModelName || isSerializedModel)) {
        throw new AmplifyException("The object provided is not an instance of " + schema.getName() + ".", "Please provide an instance of " + schema.getName() + " that matches the schema type.");
    }
    Map<String, Object> result = new HashMap<>(extractFieldLevelData(schema, instance));
    /*
         * If the owner field exists on the model, and the value is null, it should be omitted when performing a
         * mutation because the AppSync server will automatically populate it using the authentication token provided
         * in the request header.  The logic below filters out the owner field if null for this scenario.
         */
    for (AuthRule authRule : schema.getAuthRules()) {
        if (AuthStrategy.OWNER.equals(authRule.getAuthStrategy())) {
            String ownerField = authRule.getOwnerFieldOrDefault();
            if (result.containsKey(ownerField) && result.get(ownerField) == null) {
                result.remove(ownerField);
            }
        }
    }
    return result;
}
Also used : AmplifyException(com.amplifyframework.AmplifyException) HashMap(java.util.HashMap) SerializedModel(com.amplifyframework.core.model.SerializedModel) AuthRule(com.amplifyframework.core.model.AuthRule)

Example 19 with SerializedModel

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

the class AppSyncRequestFactory method extractFieldValue.

private static Object extractFieldValue(String fieldName, Model instance, ModelSchema schema) throws AmplifyException {
    if (instance instanceof SerializedModel) {
        SerializedModel serializedModel = (SerializedModel) instance;
        Map<String, Object> serializedData = serializedModel.getSerializedData();
        ModelField field = schema.getFields().get(fieldName);
        Object fieldValue = serializedData.get(fieldName);
        if (fieldValue != null && field != null && field.isCustomType()) {
            return extractCustomTypeFieldValue(fieldName, serializedData.get(fieldName));
        }
        return fieldValue;
    }
    try {
        Field privateField = instance.getClass().getDeclaredField(fieldName);
        privateField.setAccessible(true);
        return privateField.get(instance);
    } catch (Exception exception) {
        throw new AmplifyException("An invalid field was provided. " + fieldName + " is not present in " + schema.getName(), exception, "Check if this model schema is a correct representation of the fields in the provided Object");
    }
}
Also used : ModelField(com.amplifyframework.core.model.ModelField) Field(java.lang.reflect.Field) AmplifyException(com.amplifyframework.AmplifyException) ModelField(com.amplifyframework.core.model.ModelField) SerializedModel(com.amplifyframework.core.model.SerializedModel) AmplifyException(com.amplifyframework.AmplifyException) DataStoreException(com.amplifyframework.datastore.DataStoreException)

Example 20 with SerializedModel

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

the class HybridAssociationSyncInstrumentationTest method associatedModelAreSyncedDownFromCloud.

/**
 * When the cloud sees an update to its data, the new data should be reflected in the
 * local store. What's more, we should be able to query for the updated data by its model names,
 * and expect to see the result, that way. This should hold for associated models, too.
 * @throws AmplifyException For a variety of reasons, including failure to build schema,
 *                          or bad interaction with API or DataStore
 */
@Ignore("It passes. Not automating due to operational concerns as noted in class-level @Ignore.")
@Test
public void associatedModelAreSyncedDownFromCloud() throws AmplifyException {
    // Create a BlogOwner on the remote system,
    // and wait for it to trickle back to the client.
    BlogOwner owner = BlogOwner.builder().name("Agent Texas").build();
    String ownerModelName = BlogOwner.class.getSimpleName();
    ModelSchema ownerSchema = schemaProvider.modelSchemas().get(ownerModelName);
    assertNotNull(ownerSchema);
    HubAccumulator ownerAccumulator = HubAccumulator.create(HubChannel.DATASTORE, receiptOf(owner.getId()), 1).start();
    appSync.create(owner, ownerSchema);
    ownerAccumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    // Now, validate that we see the data locally, when we query for serialized models
    // and by Java BlogOwners.
    Map<String, Object> expectedOwnerData = new HashMap<>();
    expectedOwnerData.put("id", owner.getId());
    expectedOwnerData.put("name", owner.getName());
    List<SerializedModel> actualSerializedOwners = hybridBehaviors.list(ownerSchema.getName());
    assertTrue(actualSerializedOwners.contains(SerializedModel.builder().serializedData(expectedOwnerData).modelSchema(ownerSchema).build()));
    assertTrue(normalBehaviors.list(BlogOwner.class).contains(owner));
    // Now, remotely save a model that has an association to the owner above.
    Blog blog = Blog.builder().name("Blog about Texas").owner(owner).build();
    String blogModelName = Blog.class.getSimpleName();
    ModelSchema blogSchema = schemaProvider.modelSchemas().get(blogModelName);
    assertNotNull(blogSchema);
    HubAccumulator blogAccumulator = HubAccumulator.create(HubChannel.DATASTORE, receiptOf(blog.getId()), 1).start();
    appSync.create(blog, blogSchema);
    blogAccumulator.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    // Validate that we can find the newly associated model locally, now.
    Map<String, Object> expectedBlogData = new HashMap<>();
    expectedBlogData.put("id", blog.getId());
    expectedBlogData.put("name", blog.getName());
    expectedBlogData.put("owner", SerializedModel.builder().serializedData(Collections.singletonMap("id", owner.getId())).modelSchema(null).build());
    List<SerializedModel> expectedSerializedBlogs = hybridBehaviors.list(blogSchema.getName());
    assertTrue(expectedSerializedBlogs.contains(SerializedModel.builder().serializedData(expectedBlogData).modelSchema(blogSchema).build()));
    assertTrue(normalBehaviors.list(Blog.class).contains(blog));
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) HashMap(java.util.HashMap) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) SerializedModel(com.amplifyframework.core.model.SerializedModel) Blog(com.amplifyframework.testmodels.commentsblog.Blog) Ignore(org.junit.Ignore) 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