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();
}
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.");
}
}
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);
}
}
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;
}
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);
});
}
Aggregations