Search in sources :

Example 31 with AmplifyException

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

the class StorageComponentTest method setup.

/**
 * Sets up Storage category by registering a mock AWSS3StoragePlugin
 * instance to Amplify and configuring.
 *
 * @throws AmplifyException if Amplify fails to configure with mock
 *                          Storage category configuration.
 */
@Before
public void setup() throws AmplifyException {
    this.storage = new StorageCategory();
    this.storageService = mock(StorageService.class);
    StorageService.Factory storageServiceFactory = (context, region, bucket) -> storageService;
    CognitoAuthProvider cognitoAuthProvider = mock(CognitoAuthProvider.class);
    doReturn(RandomString.string()).when(cognitoAuthProvider).getIdentityId();
    this.storage.addPlugin(new AWSS3StoragePlugin(storageServiceFactory, cognitoAuthProvider, new AWSS3StoragePluginConfiguration.Builder().build()));
    this.storage.configure(buildConfiguration(), getApplicationContext());
    this.storage.initialize(getApplicationContext());
}
Also used : TransferState(com.amazonaws.mobileconnectors.s3.transferutility.TransferState) AmplifyException(com.amplifyframework.AmplifyException) ApplicationProvider.getApplicationContext(androidx.test.core.app.ApplicationProvider.getApplicationContext) StorageCategory(com.amplifyframework.storage.StorageCategory) StorageDownloadFileResult(com.amplifyframework.storage.result.StorageDownloadFileResult) StorageListResult(com.amplifyframework.storage.result.StorageListResult) URL(java.net.URL) Date(java.util.Date) RunWith(org.junit.runner.RunWith) RandomBytes(com.amplifyframework.testutils.random.RandomBytes) StorageUploadInputStreamResult(com.amplifyframework.storage.result.StorageUploadInputStreamResult) TransferListener(com.amazonaws.mobileconnectors.s3.transferutility.TransferListener) StorageItem(com.amplifyframework.storage.StorageItem) StorageException(com.amplifyframework.storage.StorageException) JSONException(org.json.JSONException) StorageUploadFileResult(com.amplifyframework.storage.result.StorageUploadFileResult) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) Mockito.doAnswer(org.mockito.Mockito.doAnswer) StorageService(com.amplifyframework.storage.s3.service.StorageService) AWSS3StoragePluginConfiguration(com.amplifyframework.storage.s3.configuration.AWSS3StoragePluginConfiguration) TransferObserver(com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver) Mockito.anyString(org.mockito.Mockito.anyString) Mockito.doReturn(org.mockito.Mockito.doReturn) Before(org.junit.Before) MalformedURLException(java.net.MalformedURLException) StorageRemoveResult(com.amplifyframework.storage.result.StorageRemoveResult) Test(org.junit.Test) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) File(java.io.File) StorageCategoryConfiguration(com.amplifyframework.storage.StorageCategoryConfiguration) RobolectricTestRunner(org.robolectric.RobolectricTestRunner) Await(com.amplifyframework.testutils.Await) RandomString(com.amplifyframework.testutils.random.RandomString) StorageGetUrlResult(com.amplifyframework.storage.result.StorageGetUrlResult) Mockito.anyInt(org.mockito.Mockito.anyInt) Mockito.any(org.mockito.Mockito.any) RandomTempFile(com.amplifyframework.testutils.random.RandomTempFile) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) Mockito.mock(org.mockito.Mockito.mock) StorageCategory(com.amplifyframework.storage.StorageCategory) AWSS3StoragePluginConfiguration(com.amplifyframework.storage.s3.configuration.AWSS3StoragePluginConfiguration) StorageService(com.amplifyframework.storage.s3.service.StorageService) Before(org.junit.Before)

Example 32 with AmplifyException

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

the class AppSyncRequestFactory method buildMutation.

/**
 * Builds a mutation.
 * @param schema the model schema for the mutation
 * @param mutationType Type of mutation, e.g. {@link MutationType#CREATE}
 * @param <M> Type of model being mutated
 * @return Mutation doc
 */
private static <M extends Model> AppSyncGraphQLRequest<ModelWithMetadata<M>> buildMutation(ModelSchema schema, Map<String, Object> inputMap, QueryPredicate predicate, MutationType mutationType, AuthModeStrategyType strategyType) throws DataStoreException {
    try {
        String graphQlTypeName = schema.getName();
        AppSyncGraphQLRequest.Builder builder = AppSyncGraphQLRequest.builder().modelClass(schema.getModelClass()).modelSchema(schema).operation(mutationType).requestAuthorizationStrategyType(strategyType).requestOptions(new DataStoreGraphQLRequestOptions()).responseType(TypeMaker.getParameterizedType(ModelWithMetadata.class, schema.getModelClass()));
        String inputType = Casing.capitalize(mutationType.toString()) + Casing.capitalizeFirst(graphQlTypeName) + // CreateTodoInput
        "Input!";
        builder.variable("input", inputType, inputMap);
        if (!QueryPredicates.all().equals(predicate)) {
            String conditionType = "Model" + Casing.capitalizeFirst(graphQlTypeName) + "ConditionInput";
            builder.variable("condition", conditionType, parsePredicate(predicate));
        }
        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) AppSyncGraphQLRequest(com.amplifyframework.api.aws.AppSyncGraphQLRequest)

Example 33 with AmplifyException

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

the class AuthRuleRequestDecorator method decorate.

/**
 * Decorate given GraphQL request instance with additional variables for owner-based or
 * group-based authorization.
 *
 * This will only work if the request is compliant with the AppSync specifications.
 * @param request an instance of {@link GraphQLRequest}.
 * @param authType the mode of authorization being used to authorize the request
 * @param <R> The type of data contained in the GraphQLResponse expected from this request.
 * @return the input request with additional variables that specify model's owner and/or
 *          groups
 * @throws ApiException If an error is encountered while processing the auth rules associated
 *          with the request or if the authorization fails
 */
public <R> GraphQLRequest<R> decorate(@NonNull GraphQLRequest<R> request, @NonNull AuthorizationType authType) throws ApiException {
    if (!(request instanceof AppSyncGraphQLRequest)) {
        return request;
    }
    AppSyncGraphQLRequest<R> appSyncRequest = (AppSyncGraphQLRequest<R>) request;
    AuthRule ownerRuleWithReadRestriction = null;
    Map<String, Set<String>> readAuthorizedGroupsMap = new HashMap<>();
    // and it's not clear what a good solution would be until AppSync supports real time filters.
    for (AuthRule authRule : appSyncRequest.getModelSchema().getAuthRules()) {
        if (isReadRestrictingOwner(authRule)) {
            if (ownerRuleWithReadRestriction == null) {
                ownerRuleWithReadRestriction = authRule;
            } else {
                throw new ApiAuthException("Detected multiple owner type auth rules with a READ operation", "We currently do not support this use case. Please limit your type to just one owner " + "auth rule with a READ operation restriction.");
            }
        } else if (isReadRestrictingStaticGroup(authRule)) {
            // Group read-restricting groups by the claim name
            String groupClaim = authRule.getGroupClaimOrDefault();
            List<String> groups = authRule.getGroups();
            Set<String> readAuthorizedGroups = readAuthorizedGroupsMap.get(groupClaim);
            if (readAuthorizedGroups != null) {
                readAuthorizedGroups.addAll(groups);
            } else {
                readAuthorizedGroupsMap.put(groupClaim, new HashSet<>(groups));
            }
        }
    }
    // them.
    if (ownerRuleWithReadRestriction != null && userNotInReadRestrictingGroups(readAuthorizedGroupsMap, authType)) {
        String idClaim = ownerRuleWithReadRestriction.getIdentityClaimOrDefault();
        String key = ownerRuleWithReadRestriction.getOwnerFieldOrDefault();
        String value = getIdentityValue(idClaim, authType);
        try {
            return appSyncRequest.newBuilder().variable(key, "String!", value).build();
        } catch (AmplifyException error) {
            // This should not happen normally
            throw new ApiAuthException("Failed to set owner field on AppSyncGraphQLRequest.", error, AmplifyException.REPORT_BUG_TO_AWS_SUGGESTION);
        }
    }
    return request;
}
Also used : ApiAuthException(com.amplifyframework.api.ApiException.ApiAuthException) HashSet(java.util.HashSet) Set(java.util.Set) AmplifyException(com.amplifyframework.AmplifyException) HashMap(java.util.HashMap) AppSyncGraphQLRequest(com.amplifyframework.api.aws.AppSyncGraphQLRequest) ArrayList(java.util.ArrayList) List(java.util.List) AuthRule(com.amplifyframework.core.model.AuthRule) HashSet(java.util.HashSet)

Example 34 with AmplifyException

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

the class AppSyncGraphQLRequestFactory method buildMutation.

/**
 * Creates a {@link GraphQLRequest} that represents a mutation of a given type.
 *
 * @param model the model instance.
 * @param predicate the model predicate.
 * @param type the mutation type.
 * @param <R> the response type.
 * @param <T> the concrete model type.
 * @return a valid {@link GraphQLRequest} instance.
 * @throws IllegalStateException when the model schema does not contain the expected information.
 */
public static <R, T extends Model> GraphQLRequest<R> buildMutation(T model, QueryPredicate predicate, MutationType type) {
    try {
        Class<? extends Model> modelClass = model.getClass();
        ModelSchema schema = ModelSchema.fromModelClass(modelClass);
        String graphQlTypeName = schema.getName();
        AppSyncGraphQLRequest.Builder builder = AppSyncGraphQLRequest.builder().operation(type).modelClass(modelClass).requestOptions(new ApiGraphQLRequestOptions()).responseType(modelClass);
        String inputType = Casing.capitalize(type.toString()) + Casing.capitalizeFirst(graphQlTypeName) + // CreateTodoInput
        "Input!";
        if (MutationType.DELETE.equals(type)) {
            builder.variable("input", inputType, getDeleteMutationInputMap(schema, model));
        } else {
            builder.variable("input", inputType, getMapOfFieldNameAndValues(schema, model));
        }
        if (!QueryPredicates.all().equals(predicate)) {
            String conditionType = "Model" + Casing.capitalizeFirst(graphQlTypeName) + "ConditionInput";
            builder.variable("condition", conditionType, parsePredicate(predicate));
        }
        return builder.build();
    } catch (AmplifyException exception) {
        throw new IllegalStateException("Could not generate a schema for the specified class", exception);
    }
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) AmplifyException(com.amplifyframework.AmplifyException)

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