Search in sources :

Example 6 with AmplifyException

use of com.amplifyframework.AmplifyException in project amplify-android by aws-amplify.

the class AnalyticsPinpointInstrumentedTest method setUp.

/**
 * Configure the Amplify framework.
 *
 * @throws AmplifyException From Amplify configuration.
 */
@BeforeClass
public static void setUp() throws AmplifyException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Exception> asyncException = new AtomicReference<>();
    Context context = getApplicationContext();
    AWSMobileClient.getInstance().initialize(context, new AWSConfiguration(context), new Callback<UserStateDetails>() {

        @Override
        public void onResult(UserStateDetails result) {
            latch.countDown();
        }

        @Override
        public void onError(Exception exception) {
            asyncException.set(exception);
            latch.countDown();
        }
    });
    try {
        if (latch.await(AUTH_TIMEOUT, TimeUnit.SECONDS)) {
            if (asyncException.get() != null) {
                fail("Failed to instantiate AWSMobileClient");
            }
        } else {
            fail("Failed to instantiate AWSMobileClient within " + AUTH_TIMEOUT + " seconds");
        }
    } catch (InterruptedException error) {
        fail("Failed to instantiate AWSMobileClient");
    }
    AWSPinpointAnalyticsPlugin plugin = new AWSPinpointAnalyticsPlugin((Application) context, AWSMobileClient.getInstance());
    Amplify.addPlugin(plugin);
    Amplify.configure(context);
    analyticsClient = plugin.getAnalyticsClient();
    targetingClient = plugin.getTargetingClient();
}
Also used : Context(android.content.Context) ApplicationProvider.getApplicationContext(androidx.test.core.app.ApplicationProvider.getApplicationContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) AWSConfiguration(com.amazonaws.mobile.config.AWSConfiguration) UserStateDetails(com.amazonaws.mobile.client.UserStateDetails) AmplifyException(com.amplifyframework.AmplifyException) JSONException(org.json.JSONException) BeforeClass(org.junit.BeforeClass)

Example 7 with AmplifyException

use of com.amplifyframework.AmplifyException in project amplify-android by aws-amplify.

the class AppSyncGraphQLRequestFactory method getMapOfFieldNameAndValues.

private static Map<String, Object> getMapOfFieldNameAndValues(@NonNull ModelSchema schema, @NonNull Model instance) throws AmplifyException {
    if (!instance.getClass().getSimpleName().equals(schema.getName())) {
        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.");
    }
    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();
        Object fieldValue = extractFieldValue(fieldName, instance, schema);
        final ModelAssociation association = schema.getAssociations().get(fieldName);
        if (association == null) {
            result.put(fieldName, fieldValue);
        } else if (association.isOwner()) {
            Model target = (Model) Objects.requireNonNull(fieldValue);
            result.put(association.getTargetName(), target.getId());
        }
    // Ignore if field is associated, but is not a "belongsTo" relationship
    }
    /*
         * 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) ModelAssociation(com.amplifyframework.core.model.ModelAssociation) ModelField(com.amplifyframework.core.model.ModelField) HashMap(java.util.HashMap) Model(com.amplifyframework.core.model.Model) AuthRule(com.amplifyframework.core.model.AuthRule)

Example 8 with AmplifyException

use of com.amplifyframework.AmplifyException in project amplify-android by aws-amplify.

the class AppSyncGraphQLRequestFactory method extractFieldValue.

private static Object extractFieldValue(String fieldName, Model instance, ModelSchema schema) throws AmplifyException {
    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) AmplifyException(com.amplifyframework.AmplifyException)

Example 9 with AmplifyException

use of com.amplifyframework.AmplifyException 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 10 with AmplifyException

use of com.amplifyframework.AmplifyException in project amplify-android by aws-amplify.

the class AppSyncRequestFactory method buildUpdateRequest.

static <M extends Model> AppSyncGraphQLRequest<ModelWithMetadata<M>> buildUpdateRequest(ModelSchema schema, M model, Integer version, QueryPredicate predicate, AuthModeStrategyType strategyType) throws DataStoreException {
    try {
        Map<String, Object> inputMap = new HashMap<>();
        inputMap.put("_version", version);
        inputMap.putAll(getMapOfFieldNameAndValues(schema, model));
        return buildMutation(schema, inputMap, predicate, MutationType.UPDATE, strategyType);
    } catch (AmplifyException amplifyException) {
        throw new DataStoreException("Failed to get fields for model.", amplifyException, "Validate your model file.");
    }
}
Also used : DataStoreException(com.amplifyframework.datastore.DataStoreException) AmplifyException(com.amplifyframework.AmplifyException) HashMap(java.util.HashMap)

Aggregations

AmplifyException (com.amplifyframework.AmplifyException)34 DataStoreException (com.amplifyframework.datastore.DataStoreException)14 Model (com.amplifyframework.core.model.Model)10 ModelSchema (com.amplifyframework.core.model.ModelSchema)10 SerializedModel (com.amplifyframework.core.model.SerializedModel)10 HashMap (java.util.HashMap)9 Test (org.junit.Test)9 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)8 Collections (java.util.Collections)7 TimeUnit (java.util.concurrent.TimeUnit)7 Assert.assertEquals (org.junit.Assert.assertEquals)7 Mockito.mock (org.mockito.Mockito.mock)7 DataStoreConfiguration (com.amplifyframework.datastore.DataStoreConfiguration)6 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)6 JSONException (org.json.JSONException)6 StorageItemChange (com.amplifyframework.datastore.storage.StorageItemChange)5 Post (com.amplifyframework.testmodels.commentsblog.Post)5 ArrayList (java.util.ArrayList)5 JSONObject (org.json.JSONObject)5 Context (android.content.Context)4