Search in sources :

Example 11 with AmplifyException

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

the class AppSyncRequestFactory method buildSyncRequest.

/**
 * Builds the query document for base and delta sync.
 * If you provide lastSyncTime, it builds a delta sync, where the delta is computed
 * against the provided time. Otherwise, if you provide a null lastSyncTime, a
 * request doc is generated for a base sync.
 * @param modelSchema Schema Class for which we want to sync.
 * @param lastSync The last time synced. If not provided, do a base query.
 *                 If provided, do a delta query.
 * @param <T> The type of objects we are syncing
 * @return A string which contains a GraphQL query doc for an base/delta sync
 * @throws DataStoreException On Failure to inspect
 */
@NonNull
static <T> AppSyncGraphQLRequest<T> buildSyncRequest(@NonNull final ModelSchema modelSchema, @Nullable final Long lastSync, @Nullable final Integer limit, @NonNull final QueryPredicate predicate, @NonNull final AuthModeStrategyType strategyType) throws DataStoreException {
    try {
        AppSyncGraphQLRequest.Builder builder = AppSyncGraphQLRequest.builder().modelClass(modelSchema.getModelClass()).modelSchema(modelSchema).operation(QueryType.SYNC).requestAuthorizationStrategyType(strategyType).requestOptions(new DataStoreGraphQLRequestOptions()).responseType(TypeMaker.getParameterizedType(PaginatedResult.class, ModelWithMetadata.class, modelSchema.getModelClass()));
        if (lastSync != null) {
            builder.variable("lastSync", "AWSTimestamp", lastSync);
        }
        if (limit != null) {
            builder.variable("limit", "Int", limit);
        }
        if (!QueryPredicates.all().equals(predicate)) {
            String filterType = "Model" + Casing.capitalizeFirst(modelSchema.getName()) + "FilterInput";
            QueryPredicate syncPredicate = predicate;
            if (!(syncPredicate instanceof QueryPredicateGroup)) {
                // When a filter is provided, wrap it with a predicate group of type AND.  By doing this, it enables
                // AppSync to optimize the request by performing a DynamoDB query instead of a scan.  If the
                // provided syncPredicate is already a QueryPredicateGroup, this is not needed.  If the provided
                // group is of type AND, the optimization will occur.  If the top level group is OR or NOT, the
                // optimization is not possible anyway.
                syncPredicate = QueryPredicateGroup.andOf(syncPredicate);
            }
            builder.variable("filter", filterType, parsePredicate(syncPredicate));
        }
        return builder.build();
    } 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) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) AppSyncGraphQLRequest(com.amplifyframework.api.aws.AppSyncGraphQLRequest) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) QueryPredicateGroup(com.amplifyframework.core.model.query.predicate.QueryPredicateGroup) NonNull(androidx.annotation.NonNull)

Example 12 with AmplifyException

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

the class AppSyncRequestFactory method buildDeletionRequest.

static <M extends Model> AppSyncGraphQLRequest<ModelWithMetadata<M>> buildDeletionRequest(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(getDeleteMutationInputMap(schema, model));
        return buildMutation(schema, inputMap, predicate, MutationType.DELETE, 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)

Example 13 with AmplifyException

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

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

the class TestStorageCategory method create.

/**
 * Creates an instance of {@link StorageCategory} using the provided configuration resource.
 * @param context Android Context
 * @param resourceId Android resource ID for a configuration file
 * @return A StorageCategory instance using the provided configuration
 */
static StorageCategory create(@NonNull Context context, @RawRes int resourceId) {
    Objects.requireNonNull(context);
    final StorageCategory storageCategory = new StorageCategory();
    try {
        storageCategory.addPlugin(new AWSS3StoragePlugin(new TestCognitoAuthProvider()));
        CategoryConfiguration storageConfiguration = AmplifyConfiguration.fromConfigFile(context, resourceId).forCategoryType(CategoryType.STORAGE);
        storageCategory.configure(storageConfiguration, context);
    // storageCategory.initialize(context); // Doesn't do anything right now.
    } catch (AmplifyException initializationFailure) {
        throw new RuntimeException(initializationFailure);
    }
    return storageCategory;
}
Also used : AmplifyException(com.amplifyframework.AmplifyException) StorageCategory(com.amplifyframework.storage.StorageCategory) CategoryConfiguration(com.amplifyframework.core.category.CategoryConfiguration)

Example 15 with AmplifyException

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

the class AmplifyConfiguration method configsFromJson.

private static Map<String, CategoryConfiguration> configsFromJson(JSONObject json) throws AmplifyException {
    final List<CategoryConfiguration> possibleConfigs = Arrays.asList(new AnalyticsCategoryConfiguration(), new ApiCategoryConfiguration(), new AuthCategoryConfiguration(), new DataStoreCategoryConfiguration(), new GeoCategoryConfiguration(), new HubCategoryConfiguration(), new LoggingCategoryConfiguration(), new PredictionsCategoryConfiguration(), new StorageCategoryConfiguration());
    final Map<String, CategoryConfiguration> actualConfigs = new HashMap<>();
    try {
        for (CategoryConfiguration possibleConfig : possibleConfigs) {
            String categoryJsonKey = possibleConfig.getCategoryType().getConfigurationKey();
            if (json.has(categoryJsonKey)) {
                possibleConfig.populateFromJSON(json.getJSONObject(categoryJsonKey));
                actualConfigs.put(categoryJsonKey, possibleConfig);
            }
        }
    } catch (JSONException error) {
        throw new AmplifyException("Could not parse amplifyconfiguration.json ", error, "Check any modifications made to the file.");
    }
    return Immutable.of(actualConfigs);
}
Also used : DataStoreCategoryConfiguration(com.amplifyframework.datastore.DataStoreCategoryConfiguration) StorageCategoryConfiguration(com.amplifyframework.storage.StorageCategoryConfiguration) AmplifyException(com.amplifyframework.AmplifyException) PredictionsCategoryConfiguration(com.amplifyframework.predictions.PredictionsCategoryConfiguration) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) AuthCategoryConfiguration(com.amplifyframework.auth.AuthCategoryConfiguration) LoggingCategoryConfiguration(com.amplifyframework.logging.LoggingCategoryConfiguration) AnalyticsCategoryConfiguration(com.amplifyframework.analytics.AnalyticsCategoryConfiguration) AuthCategoryConfiguration(com.amplifyframework.auth.AuthCategoryConfiguration) CategoryConfiguration(com.amplifyframework.core.category.CategoryConfiguration) GeoCategoryConfiguration(com.amplifyframework.geo.GeoCategoryConfiguration) DataStoreCategoryConfiguration(com.amplifyframework.datastore.DataStoreCategoryConfiguration) HubCategoryConfiguration(com.amplifyframework.hub.HubCategoryConfiguration) PredictionsCategoryConfiguration(com.amplifyframework.predictions.PredictionsCategoryConfiguration) StorageCategoryConfiguration(com.amplifyframework.storage.StorageCategoryConfiguration) ApiCategoryConfiguration(com.amplifyframework.api.ApiCategoryConfiguration) EmptyCategoryConfiguration(com.amplifyframework.core.category.EmptyCategoryConfiguration) JSONException(org.json.JSONException) GeoCategoryConfiguration(com.amplifyframework.geo.GeoCategoryConfiguration) AnalyticsCategoryConfiguration(com.amplifyframework.analytics.AnalyticsCategoryConfiguration) ApiCategoryConfiguration(com.amplifyframework.api.ApiCategoryConfiguration) HubCategoryConfiguration(com.amplifyframework.hub.HubCategoryConfiguration) LoggingCategoryConfiguration(com.amplifyframework.logging.LoggingCategoryConfiguration)

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