Search in sources :

Example 76 with DataStoreException

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

the class AppSyncClient method subscription.

private <T extends Model> Cancelable subscription(SubscriptionType subscriptionType, ModelSchema modelSchema, Consumer<String> onSubscriptionStarted, Consumer<GraphQLResponse<ModelWithMetadata<T>>> onNextResponse, Consumer<DataStoreException> onSubscriptionFailure, Action onSubscriptionCompleted) {
    final GraphQLRequest<ModelWithMetadata<T>> request;
    try {
        request = AppSyncRequestFactory.buildSubscriptionRequest(modelSchema, subscriptionType, authModeStrategyType);
    } catch (DataStoreException requestGenerationException) {
        onSubscriptionFailure.accept(requestGenerationException);
        return new NoOpCancelable();
    }
    final Consumer<GraphQLResponse<ModelWithMetadata<T>>> responseConsumer = response -> {
        if (response.hasErrors()) {
            onSubscriptionFailure.accept(new DataStoreException.GraphQLResponseException("Subscription error for " + modelSchema.getName() + ": " + response.getErrors(), response.getErrors()));
        } else {
            onNextResponse.accept(response);
        }
    };
    final Consumer<ApiException> failureConsumer = failure -> onSubscriptionFailure.accept(new DataStoreException("Error during subscription.", failure, "Evaluate details."));
    final Cancelable cancelable = api.subscribe(request, onSubscriptionStarted, responseConsumer, failureConsumer, onSubscriptionCompleted);
    if (cancelable != null) {
        return cancelable;
    }
    return new NoOpCancelable();
}
Also used : Amplify(com.amplifyframework.core.Amplify) AmplifyException(com.amplifyframework.AmplifyException) NonNull(androidx.annotation.NonNull) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Model(com.amplifyframework.core.model.Model) Action(com.amplifyframework.core.Action) ApiException(com.amplifyframework.api.ApiException) Logger(com.amplifyframework.logging.Logger) GraphQLBehavior(com.amplifyframework.api.graphql.GraphQLBehavior) DataStoreException(com.amplifyframework.datastore.DataStoreException) Consumer(com.amplifyframework.core.Consumer) Nullable(androidx.annotation.Nullable) Cancelable(com.amplifyframework.core.async.Cancelable) SubscriptionType(com.amplifyframework.api.graphql.SubscriptionType) AuthModeStrategyType(com.amplifyframework.api.aws.AuthModeStrategyType) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) ModelSchema(com.amplifyframework.core.model.ModelSchema) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) ApiCategoryBehavior(com.amplifyframework.api.ApiCategoryBehavior) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) DataStoreException(com.amplifyframework.datastore.DataStoreException) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) Cancelable(com.amplifyframework.core.async.Cancelable) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) ApiException(com.amplifyframework.api.ApiException)

Example 77 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException 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 78 with DataStoreException

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

the class ModelHelper method getValue.

/**
 * Uses reflection to get a property value on a <code>Model</code> by its <code>ModelField</code>
 * reference. This method prioritizes the property getter and fallback to the field itself
 * if a getter doesn't exist.
 *
 * @param model the model instance
 * @param field the model field
 * @param <M> the model concrete type
 * @return the field value or <code>null</code>
 * @throws DataStoreException in case of a error happens during the dynamic reflection calls
 */
public static <M extends Model> Object getValue(M model, ModelField field) throws DataStoreException {
    final Class<? extends Model> modelClass = model.getClass();
    final String fieldName = field.getName();
    final String getterName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
    try {
        final Method fieldGetter = modelClass.getMethod(getterName);
        return fieldGetter.invoke(model);
    } catch (Exception exception) {
        LOGGER.verbose(String.format("Could not find %s() on %s. Fallback to direct field access.", getterName, modelClass.getName()));
    }
    // fallback to direct field access
    try {
        final Field fieldReference = modelClass.getDeclaredField(fieldName);
        fieldReference.setAccessible(true);
        return fieldReference.get(model);
    } catch (Exception fallbackException) {
        throw new DataStoreException("Error when reading the property " + fieldName + " from class " + modelClass.getName(), fallbackException, AmplifyException.REPORT_BUG_TO_AWS_SUGGESTION);
    }
}
Also used : Field(java.lang.reflect.Field) ModelField(com.amplifyframework.core.model.ModelField) DataStoreException(com.amplifyframework.datastore.DataStoreException) Method(java.lang.reflect.Method) DataStoreException(com.amplifyframework.datastore.DataStoreException) AmplifyException(com.amplifyframework.AmplifyException)

Example 79 with DataStoreException

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

the class ModelProviderLocator method locate.

@SuppressWarnings({ "SameParameterValue", "unchecked" })
static ModelProvider locate(@NonNull String modelProviderClassName) throws DataStoreException {
    Objects.requireNonNull(modelProviderClassName);
    final Class<? extends ModelProvider> modelProviderClass;
    try {
        // noinspection unchecked It's very unlikely that someone cooked up a different type at this FQCN.
        modelProviderClass = (Class<? extends ModelProvider>) Class.forName(modelProviderClassName);
    } catch (ClassNotFoundException modelProviderClassNotFoundError) {
        throw new DataStoreException("Failed to find code-generated model provider.", modelProviderClassNotFoundError, "Validate that " + modelProviderClassName + " is built into your project.");
    }
    if (!ModelProvider.class.isAssignableFrom(modelProviderClass)) {
        throw new DataStoreException("Located class as " + modelProviderClass.getName() + ", but it does not implement " + ModelProvider.class.getName() + ".", "Validate that " + modelProviderClass.getName() + " has not been modified since the time " + "it was code-generated.");
    }
    final Method getInstanceMethod;
    try {
        getInstanceMethod = modelProviderClass.getDeclaredMethod(GET_INSTANCE_ACCESSOR_METHOD_NAME);
    } catch (NoSuchMethodException noGetInstanceMethodError) {
        throw new DataStoreException("Found a code-generated model provider = " + modelProviderClass.getName() + ", however " + "it had no static method named getInstance()!", noGetInstanceMethodError, "Validate that " + modelProviderClass.getName() + " has not been modified since the time " + "it was code-generated.");
    }
    final ModelProvider locatedModelProvider;
    try {
        locatedModelProvider = (ModelProvider) getInstanceMethod.invoke(null);
    } catch (IllegalAccessException getInstanceIsNotAccessibleError) {
        throw new DataStoreException("Tried to call " + modelProviderClass.getName() + GET_INSTANCE_ACCESSOR_METHOD_NAME + ", but " + "this method did not have public access.", getInstanceIsNotAccessibleError, "Validate that " + modelProviderClass.getName() + " has not been modified since the time " + "it was code-generated.");
    } catch (InvocationTargetException wrappedExceptionFromGetInstance) {
        throw new DataStoreException("An exception was thrown from " + modelProviderClass.getName() + GET_INSTANCE_ACCESSOR_METHOD_NAME + " while invoking via reflection.", wrappedExceptionFromGetInstance, "This is not expected to occur. Contact AWS.");
    }
    return locatedModelProvider;
}
Also used : DataStoreException(com.amplifyframework.datastore.DataStoreException) ModelProvider(com.amplifyframework.core.model.ModelProvider) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 80 with DataStoreException

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

the class ConflictResolver method resolve.

@NonNull
<T extends Model> Single<ModelWithMetadata<T>> resolve(@NonNull PendingMutation<T> pendingMutation, @NonNull AppSyncConflictUnhandledError<T> conflictUnhandledError) {
    final DataStoreConflictHandler conflictHandler;
    try {
        conflictHandler = configurationProvider.getConfiguration().getConflictHandler();
    } catch (DataStoreException badConfigurationProvider) {
        return Single.error(badConfigurationProvider);
    }
    ModelWithMetadata<T> serverData = conflictUnhandledError.getServerVersion();
    ModelMetadata metadata = serverData.getSyncMetadata();
    T local = getMutatedModelFromSerializedModel(pendingMutation);
    T remote = getServerModel(serverData, pendingMutation.getMutatedItem());
    ConflictData<T> conflictData = ConflictData.create(local, remote);
    return Single.<ConflictResolutionDecision<? extends Model>>create(emitter -> conflictHandler.onConflictDetected(conflictData, emitter::onSuccess)).flatMap(decision -> {
        @SuppressWarnings("unchecked") ConflictResolutionDecision<T> typedDecision = (ConflictResolutionDecision<T>) decision;
        return resolveModelAndMetadata(conflictData, metadata, typedDecision);
    });
}
Also used : DataStoreConfigurationProvider(com.amplifyframework.datastore.DataStoreConfigurationProvider) Single(io.reactivex.rxjava3.core.Single) DataStoreConflictHandler(com.amplifyframework.datastore.DataStoreConflictHandler) SerializedModel(com.amplifyframework.core.model.SerializedModel) NonNull(androidx.annotation.NonNull) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) Model(com.amplifyframework.core.model.Model) AppSync(com.amplifyframework.datastore.appsync.AppSync) AppSyncConflictUnhandledError(com.amplifyframework.datastore.appsync.AppSyncConflictUnhandledError) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) ConflictData(com.amplifyframework.datastore.DataStoreConflictHandler.ConflictData) GsonFactory(com.amplifyframework.util.GsonFactory) Objects(java.util.Objects) DataStoreException(com.amplifyframework.datastore.DataStoreException) Type(java.lang.reflect.Type) Gson(com.google.gson.Gson) ModelSchema(com.amplifyframework.core.model.ModelSchema) ModelMetadata(com.amplifyframework.datastore.appsync.ModelMetadata) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) ConflictResolutionDecision(com.amplifyframework.datastore.DataStoreConflictHandler.ConflictResolutionDecision) DataStoreException(com.amplifyframework.datastore.DataStoreException) ConflictResolutionDecision(com.amplifyframework.datastore.DataStoreConflictHandler.ConflictResolutionDecision) DataStoreConflictHandler(com.amplifyframework.datastore.DataStoreConflictHandler) ModelMetadata(com.amplifyframework.datastore.appsync.ModelMetadata) NonNull(androidx.annotation.NonNull)

Aggregations

DataStoreException (com.amplifyframework.datastore.DataStoreException)89 Test (org.junit.Test)52 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)36 Consumer (com.amplifyframework.core.Consumer)32 List (java.util.List)32 Cancelable (com.amplifyframework.core.async.Cancelable)31 Model (com.amplifyframework.core.model.Model)31 ArrayList (java.util.ArrayList)31 AmplifyException (com.amplifyframework.AmplifyException)29 ModelSchema (com.amplifyframework.core.model.ModelSchema)28 Collections (java.util.Collections)28 Action (com.amplifyframework.core.Action)27 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)27 TimeUnit (java.util.concurrent.TimeUnit)25 Post (com.amplifyframework.testmodels.commentsblog.Post)23 PostStatus (com.amplifyframework.testmodels.commentsblog.PostStatus)23 Arrays (java.util.Arrays)23 Assert.assertEquals (org.junit.Assert.assertEquals)23 ObserveQueryOptions (com.amplifyframework.core.model.query.ObserveQueryOptions)22 DataStoreQuerySnapshot (com.amplifyframework.datastore.DataStoreQuerySnapshot)21