Search in sources :

Example 31 with SerializedModel

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

the class AppSyncRequestFactoryTest method validateUpdateMutationOnlyContainsChangedFields.

/**
 * Verify that only the fields included in serializedData on the SerializedModel are included on the API request.
 * To test this, create a SerializedModel of a BlogOwner, which only has "id", and "name", not the "wea" field.
 * Then, verify that the request does not contain "wea" field.
 *
 * @throws JSONException from JSONAssert.assertEquals JSON parsing error
 * @throws AmplifyException from ModelSchema.fromModelClass to convert model to schema
 */
@Test
public void validateUpdateMutationOnlyContainsChangedFields() throws JSONException, AmplifyException {
    ModelSchema modelSchema = ModelSchema.fromModelClass(BlogOwner.class);
    Map<String, Object> serializedData = new HashMap<>();
    serializedData.put("id", "5aef1282-64d6-4fa8-ba2c-290f9d9c6973");
    serializedData.put("name", "John Smith");
    SerializedModel blogOwner = SerializedModel.builder().serializedData(serializedData).modelSchema(modelSchema).build();
    // Assert
    JSONAssert.assertEquals(Resources.readAsString("update-blog-owner-only-changed-fields.txt"), AppSyncRequestFactory.buildUpdateRequest(modelSchema, blogOwner, 1, QueryPredicates.all(), DEFAULT_STRATEGY).getContent(), true);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) HashMap(java.util.HashMap) SerializedModel(com.amplifyframework.core.model.SerializedModel) Test(org.junit.Test)

Example 32 with SerializedModel

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

the class AppSyncRequestFactory method extractFieldLevelData.

private static Map<String, Object> extractFieldLevelData(ModelSchema schema, Model instance) throws AmplifyException {
    final Map<String, Object> result = new HashMap<>();
    for (ModelField modelField : schema.getFields().values()) {
        if (modelField.isReadOnly()) {
            // Skip read only fields, since they should not be included on the input object.
            continue;
        }
        String fieldName = modelField.getName();
        final ModelAssociation association = schema.getAssociations().get(fieldName);
        if (instance instanceof SerializedModel && !((SerializedModel) instance).getSerializedData().containsKey(fieldName)) {
            // Skip fields that are not set, so that they are not set to null in the request.
            continue;
        }
        if (association == null) {
            result.put(fieldName, extractFieldValue(modelField.getName(), instance, schema));
        } else if (association.isOwner()) {
            String targetName = association.getTargetName();
            result.put(targetName, extractAssociateId(modelField, instance, schema));
        }
    // Ignore if field is associated, but is not a "belongsTo" relationship
    }
    return result;
}
Also used : ModelAssociation(com.amplifyframework.core.model.ModelAssociation) ModelField(com.amplifyframework.core.model.ModelField) HashMap(java.util.HashMap) SerializedModel(com.amplifyframework.core.model.SerializedModel)

Example 33 with SerializedModel

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

the class ConflictResolver method getMutatedModelFromSerializedModel.

/**
 * The local data representation coming from android app comes here as serialized model of the type user defined
 * model. For appsync request this data has to be converted to the user defined model. The local data representation
 * coming for flutter is a serialized model of type serialized model which needs to be passed as is.
 * Also if the data
 * is coming as user defined model it doesn't need to be converted.
 * @param pendingMutation pending mutation coming from mutation outbox.
 * @param <T> Type of the Pending mutation.
 * @return Model
 */
@SuppressWarnings("unchecked")
private <T extends Model> T getMutatedModelFromSerializedModel(@NonNull PendingMutation<T> pendingMutation) {
    T local = pendingMutation.getMutatedItem();
    if (local instanceof SerializedModel) {
        SerializedModel serializedModel = (SerializedModel) local;
        Type modelType = Objects.requireNonNull(((SerializedModel) pendingMutation.getMutatedItem()).getModelSchema()).getModelClass();
        if (modelType != SerializedModel.class) {
            Gson gson = GsonFactory.instance();
            String jsonString = gson.toJson(serializedModel.getSerializedData());
            local = gson.fromJson(jsonString, modelType);
        }
    }
    return local;
}
Also used : Type(java.lang.reflect.Type) Gson(com.google.gson.Gson) SerializedModel(com.amplifyframework.core.model.SerializedModel)

Example 34 with SerializedModel

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

the class SQLiteModelTree method descendantsOf.

/**
 * Returns a map of descendants of a set of models (of same type).
 * A model is a child of its parent if it uses its parent's ID as foreign key.
 * @param root Collection of models to query its descendants of.
 * @return List of models that are descendants of given models. These models will
 *          have the correct model type and ID, but no other field will be populated.
 */
<T extends Model> List<Model> descendantsOf(Collection<T> root) {
    if (Empty.check(root)) {
        return new ArrayList<>();
    }
    Map<ModelSchema, Set<String>> modelMap = new LinkedHashMap<>();
    Model rootModel = root.iterator().next();
    ModelSchema rootSchema = registry.getModelSchemaForModelClass(getModelName(rootModel));
    Set<String> rootIds = new HashSet<>();
    for (T model : root) {
        rootIds.add(model.getId());
    }
    recurseTree(modelMap, rootSchema, rootIds);
    List<Model> descendants = new ArrayList<>();
    for (Map.Entry<ModelSchema, Set<String>> entry : modelMap.entrySet()) {
        ModelSchema schema = entry.getKey();
        for (String id : entry.getValue()) {
            if (rootModel.getClass() == SerializedModel.class) {
                SerializedModel dummyItem = SerializedModel.builder().serializedData(Collections.singletonMap("id", id)).modelSchema(schema).build();
                descendants.add(dummyItem);
            } else {
                // Create dummy model instance using just the ID and model type
                String dummyJson = gson.toJson(Collections.singletonMap("id", id));
                Model dummyItem = gson.fromJson(dummyJson, schema.getModelClass());
                descendants.add(dummyItem);
            }
        }
    }
    return descendants;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ArrayList(java.util.ArrayList) SerializedModel(com.amplifyframework.core.model.SerializedModel) LinkedHashMap(java.util.LinkedHashMap) ModelSchema(com.amplifyframework.core.model.ModelSchema) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 35 with SerializedModel

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

the class SQLiteStorageAdapter method createSerializedModel.

/**
 * recursively creates nested SerializedModels from raw data.
 */
private SerializedModel createSerializedModel(ModelSchema modelSchema, Map<String, Object> data) {
    final Map<String, Object> serializedData = new HashMap<>();
    for (Map.Entry<String, Object> entry : data.entrySet()) {
        ModelField field = modelSchema.getFields().get(entry.getKey());
        if (field != null && entry.getValue() != null) {
            if (field.isModel()) {
                ModelAssociation association = modelSchema.getAssociations().get(entry.getKey());
                if (association != null) {
                    String associatedType = association.getAssociatedType();
                    final ModelSchema nestedModelSchema = schemaRegistry.getModelSchemaForModelClass(associatedType);
                    @SuppressWarnings("unchecked") SerializedModel model = createSerializedModel(nestedModelSchema, (Map<String, Object>) entry.getValue());
                    serializedData.put(entry.getKey(), model);
                }
            } else if (field.isCustomType()) {
                if (field.isArray()) {
                    @SuppressWarnings("unchecked") List<Map<String, Object>> listItems = (List<Map<String, Object>>) entry.getValue();
                    List<SerializedCustomType> listOfCustomType = getValueOfListCustomTypeField(field.getTargetType(), listItems);
                    serializedData.put(entry.getKey(), listOfCustomType);
                } else {
                    final CustomTypeSchema nestedCustomTypeSchema = schemaRegistry.getCustomTypeSchemaForCustomTypeClass(field.getTargetType());
                    @SuppressWarnings("unchecked") SerializedCustomType customType = createSerializedCustomType(nestedCustomTypeSchema, (Map<String, Object>) entry.getValue());
                    serializedData.put(entry.getKey(), customType);
                }
            } else {
                serializedData.put(entry.getKey(), entry.getValue());
            }
        }
    }
    return SerializedModel.builder().serializedData(serializedData).modelSchema(modelSchema).build();
}
Also used : CustomTypeSchema(com.amplifyframework.core.model.CustomTypeSchema) ModelAssociation(com.amplifyframework.core.model.ModelAssociation) HashMap(java.util.HashMap) SerializedCustomType(com.amplifyframework.core.model.SerializedCustomType) SerializedModel(com.amplifyframework.core.model.SerializedModel) ModelSchema(com.amplifyframework.core.model.ModelSchema) ModelField(com.amplifyframework.core.model.ModelField) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap)

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