Search in sources :

Example 6 with ApiException

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

the class TimeoutWatchdog method start.

/**
 * Starts a new timer. If a timer is already in progress, it will be stopped,
 * without running to completion. Instead, the new timer will be used in its place.
 * @param timeoutAction An action to perform after a timeout has elapsed
 * @param timeoutMs After this period of time, action is performed
 */
synchronized void start(final Runnable timeoutAction, long timeoutMs) throws ApiException {
    if (timeoutAction == null) {
        throw new ApiException("Passed null action to watchdog.", AmplifyException.TODO_RECOVERY_SUGGESTION);
    } else if (timeoutMs <= 0) {
        throw new ApiException("timeoutMs must be > 0.", "Make sure you didn't set a negative timeout");
    }
    // If there's an existing timer, stop it.
    stop();
    // Now, make a new timer, and save the timeout.
    this.timeoutMs = timeoutMs;
    this.timeoutAction = timeoutAction;
    handler.postDelayed(this.timeoutAction, timeoutMs);
}
Also used : ApiException(com.amplifyframework.api.ApiException)

Example 7 with ApiException

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

the class AWSApiPluginConfigurationReader method parseConfigurationJson.

private static AWSApiPluginConfiguration parseConfigurationJson(JSONObject configurationJson) throws ApiException {
    final AWSApiPluginConfiguration.Builder configBuilder = AWSApiPluginConfiguration.builder();
    try {
        Iterator<String> apiSpecIterator = configurationJson.keys();
        while (apiSpecIterator.hasNext()) {
            final String apiName = apiSpecIterator.next();
            JSONObject apiSpec = configurationJson.getJSONObject(apiName);
            for (final String requiredKey : ConfigKey.requiredKeys()) {
                if (!apiSpec.has(requiredKey)) {
                    throw new ApiException("Failed to parse configuration, missing required key: " + requiredKey, AmplifyException.TODO_RECOVERY_SUGGESTION);
                }
            }
            final EndpointType endpointType = EndpointType.from(apiSpec.getString(ConfigKey.ENDPOINT_TYPE.key()));
            final AuthorizationType authorizationType = AuthorizationType.from(apiSpec.getString(ConfigKey.AUTHORIZATION_TYPE.key()));
            final ApiConfiguration.Builder apiConfigBuilder = ApiConfiguration.builder().endpointType(endpointType).endpoint(apiSpec.getString(ConfigKey.ENDPOINT.key())).region(apiSpec.getString(ConfigKey.REGION.key())).authorizationType(authorizationType);
            if (apiSpec.has(ConfigKey.API_KEY.key())) {
                apiConfigBuilder.apiKey(apiSpec.getString(ConfigKey.API_KEY.key()));
            }
            configBuilder.addApi(apiName, apiConfigBuilder.build());
        }
    } catch (JSONException | ApiException exception) {
        throw new ApiException("Failed to parse configuration JSON for AWS API Plugin", exception, "Check amplifyconfiguration.json to make sure the AWS API configuration section hasn't been " + "wrongly modified.");
    }
    return configBuilder.build();
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) ApiException(com.amplifyframework.api.ApiException)

Example 8 with ApiException

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

the class RxApiBindingTest method httpPostEmitsFailure.

/**
 * When the REST POST behavior emits a failure, the Rx binding
 * should do the same.
 * @throws InterruptedException If interrupted while test observer is awaiting terminal event
 */
@Test
public void httpPostEmitsFailure() throws InterruptedException {
    byte[] body = RandomString.string().getBytes();
    RestOptions options = RestOptions.builder().addBody(body).addPath("/some/path").build();
    ApiException expectedFailure = new ApiException("Expected", "Failure");
    doAnswer(invocation -> {
        final int positionOfFailureConsumer = 2;
        Consumer<ApiException> onFailure = invocation.getArgument(positionOfFailureConsumer);
        onFailure.accept(expectedFailure);
        return null;
    }).when(delegate).post(eq(options), anyConsumer(), anyConsumer());
    // Act: post via the Rx binding
    TestObserver<RestResponse> observer = rxApi.post(options).test();
    // Assert: failure bubbles through
    observer.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    observer.assertError(expectedFailure);
    verify(delegate).post(eq(options), anyConsumer(), anyConsumer());
}
Also used : RestResponse(com.amplifyframework.api.rest.RestResponse) RestOptions(com.amplifyframework.api.rest.RestOptions) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 9 with ApiException

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

the class RxApiBindingTest method mutateEmitsFailure.

/**
 * When the API behavior emits a failure for a mutation, so too should the Rx binding.
 * @throws InterruptedException If interrupted while test observer is awaiting terminal event
 */
@Test
public void mutateEmitsFailure() throws InterruptedException {
    // Arrange category behavior to fail
    ApiException expectedFailure = new ApiException("Expected", "Failure");
    GraphQLRequest<Model> deleteRequest = createMockMutationRequest(Model.class);
    doAnswer(invocation -> {
        final int positionOfFailureConsumer = 2;
        Consumer<ApiException> onFailure = invocation.getArgument(positionOfFailureConsumer);
        onFailure.accept(expectedFailure);
        return null;
    }).when(delegate).mutate(eq(deleteRequest), anyConsumer(), anyConsumer());
    // Act: access it via binding
    TestObserver<GraphQLResponse<Model>> observer = rxApi.mutate(deleteRequest).test();
    // Assert: failure is propagated
    observer.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    observer.assertError(expectedFailure);
    verify(delegate).mutate(eq(deleteRequest), anyConsumer(), anyConsumer());
}
Also used : RandomModel(com.amplifyframework.testutils.random.RandomModel) Model(com.amplifyframework.core.model.Model) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 10 with ApiException

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

the class RxApiBindingTest method subscribeStartsAndFails.

/**
 * When the subscribe API behavior starts and then immediately fails,
 * the Rx binding should emit that same failure.
 * @throws InterruptedException If interrupted while test observer is awaiting terminal event
 */
@Test
public void subscribeStartsAndFails() throws InterruptedException {
    // Arrange a category behavior which starts and then fails
    ApiException expectedFailure = new ApiException("Expected", "Failure");
    String token = RandomString.string();
    ConnectionStateEvent expectedConnectionStateEvent = new ConnectionStateEvent(ConnectionState.CONNECTED, token);
    final GraphQLRequest<Model> request = createMockSubscriptionRequest(Model.class);
    doAnswer(invocation -> {
        final int onStartPosition = 1;
        final int onFailurePosition = 3;
        Consumer<String> onStart = invocation.getArgument(onStartPosition);
        Consumer<ApiException> onFailure = invocation.getArgument(onFailurePosition);
        onStart.accept(token);
        onFailure.accept(expectedFailure);
        return null;
    }).when(delegate).subscribe(eq(request), anyConsumer(), anyConsumer(), anyConsumer(), anyAction());
    RxSubscriptionOperation<GraphQLResponse<Model>> rxOperation = rxApi.subscribe(request);
    // Act: subscribe via binding
    TestObserver<GraphQLResponse<Model>> dataObserver = rxOperation.observeSubscriptionData().test();
    TestObserver<ConnectionStateEvent> startObserver = rxOperation.observeConnectionState().test();
    startObserver.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    startObserver.assertValue(expectedConnectionStateEvent);
    startObserver.assertNoErrors();
    dataObserver.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    dataObserver.assertNoValues();
    dataObserver.assertError(expectedFailure);
}
Also used : RandomModel(com.amplifyframework.testutils.random.RandomModel) Model(com.amplifyframework.core.model.Model) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) RandomString(com.amplifyframework.testutils.random.RandomString) ConnectionStateEvent(com.amplifyframework.rx.RxOperations.RxSubscriptionOperation.ConnectionStateEvent) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Aggregations

ApiException (com.amplifyframework.api.ApiException)33 Test (org.junit.Test)12 GraphQLResponse (com.amplifyframework.api.graphql.GraphQLResponse)11 GraphQLRequest (com.amplifyframework.api.graphql.GraphQLRequest)9 AmplifyException (com.amplifyframework.AmplifyException)8 PaginatedResult (com.amplifyframework.api.graphql.PaginatedResult)7 JSONObject (org.json.JSONObject)7 Consumer (com.amplifyframework.core.Consumer)6 IOException (java.io.IOException)6 Request (okhttp3.Request)6 MockResponse (okhttp3.mockwebserver.MockResponse)6 JSONException (org.json.JSONException)6 ApiAuthException (com.amplifyframework.api.ApiException.ApiAuthException)5 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)5 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)5 NonNull (androidx.annotation.NonNull)4 RestOperationRequest (com.amplifyframework.api.rest.RestOperationRequest)4 RestResponse (com.amplifyframework.api.rest.RestResponse)4 Action (com.amplifyframework.core.Action)4 Cancelable (com.amplifyframework.core.async.Cancelable)4