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();
}
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);
}
}
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;
}
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");
}
}
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));
}
Aggregations