Search in sources :

Example 16 with ApiException

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

the class AWSApiPluginTest method graphQlMutationGetsResponse.

/**
 * It should be possible to perform a successful call to
 * {@link AWSApiPlugin#mutate(GraphQLRequest, Consumer, Consumer)}.
 * When the server returns a valid response, then the mutate methods should
 * emit content via their value consumer.
 * @throws ApiException If call to mutate(...) itself emits such an exception
 * @throws JSONException On failure to arrange response JSON
 */
@Test
public void graphQlMutationGetsResponse() throws JSONException, ApiException {
    HubAccumulator networkStatusObserver = HubAccumulator.create(HubChannel.API, ApiChannelEventName.API_ENDPOINT_STATUS_CHANGED, 1).start();
    // Arrange a response from the "server"
    String expectedName = RandomString.string();
    webServer.enqueue(new MockResponse().setBody(new JSONObject().put("data", new JSONObject().put("createBlogOwner", new JSONObject().put("name", expectedName))).toString()));
    // Try to perform a mutation.
    BlogOwner tony = BlogOwner.builder().name(expectedName).build();
    GraphQLResponse<BlogOwner> actualResponse = Await.<GraphQLResponse<BlogOwner>, ApiException>result(((onResult, onError) -> plugin.mutate(ModelMutation.create(tony), onResult, onError)));
    // Assert that the expected response was received
    assertEquals(expectedName, actualResponse.getData().getName());
    // Verify that the expected hub event fired.
    HubEvent<?> event = networkStatusObserver.awaitFirst();
    assertNotNull(event);
    assertTrue(event.getData() instanceof ApiEndpointStatusChangeEvent);
    ApiEndpointStatusChangeEvent eventData = (ApiEndpointStatusChangeEvent) event.getData();
    assertEquals(ApiEndpointStatusChangeEvent.ApiEndpointStatus.REACHABLE, eventData.getCurrentStatus());
}
Also used : Arrays(java.util.Arrays) AmplifyException(com.amplifyframework.AmplifyException) ApplicationProvider(androidx.test.core.app.ApplicationProvider) ApiChannelEventName(com.amplifyframework.api.events.ApiChannelEventName) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) After(org.junit.After) Map(java.util.Map) MockWebServer(okhttp3.mockwebserver.MockWebServer) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) AWSCredentials(com.amazonaws.auth.AWSCredentials) ResponseBody(okhttp3.ResponseBody) HubEvent(com.amplifyframework.hub.HubEvent) Request(okhttp3.Request) HubChannel(com.amplifyframework.hub.HubChannel) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ModelPagination(com.amplifyframework.api.graphql.model.ModelPagination) RobolectricTestRunner(org.robolectric.RobolectricTestRunner) Type(java.lang.reflect.Type) Await(com.amplifyframework.testutils.Await) RandomString(com.amplifyframework.testutils.random.RandomString) ModelQuery(com.amplifyframework.api.graphql.model.ModelQuery) HttpUrl(okhttp3.HttpUrl) MockResponse(okhttp3.mockwebserver.MockResponse) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) RunWith(org.junit.runner.RunWith) Resources(com.amplifyframework.testutils.Resources) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) ApiException(com.amplifyframework.api.ApiException) Consumer(com.amplifyframework.core.Consumer) TypeMaker(com.amplifyframework.util.TypeMaker) Observable(io.reactivex.rxjava3.core.Observable) ApiEndpointStatusChangeEvent(com.amplifyframework.api.events.ApiEndpointStatusChangeEvent) AWSCredentialsProvider(com.amazonaws.auth.AWSCredentialsProvider) Response(okhttp3.Response) CognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.CognitoUserPoolsAuthProvider) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) Before(org.junit.Before) BasicAWSCredentials(com.amazonaws.auth.BasicAWSCredentials) Assert.assertNotNull(org.junit.Assert.assertNotNull) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) QueryType(com.amplifyframework.api.graphql.QueryType) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) Assert.assertNull(org.junit.Assert.assertNull) ModelMutation(com.amplifyframework.api.graphql.model.ModelMutation) Assert.assertEquals(org.junit.Assert.assertEquals) MockResponse(okhttp3.mockwebserver.MockResponse) JSONObject(org.json.JSONObject) ApiEndpointStatusChangeEvent(com.amplifyframework.api.events.ApiEndpointStatusChangeEvent) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) RandomString(com.amplifyframework.testutils.random.RandomString) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 17 with ApiException

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

the class AWSRestOperationTest method noErrorEmittedIfOperationIsCancelled.

/**
 * If the user calls {@link AWSRestOperation#cancel()}, then the operation
 * will not fire any callback. This behavior is consistent with iOS's REST operation.
 */
@Test
public void noErrorEmittedIfOperationIsCancelled() {
    long timeToWaitForResponse = 300L;
    RestOperationRequest request = new RestOperationRequest(HttpMethod.GET, baseUrl.uri().getPath(), emptyMap(), emptyMap());
    assertTimedOut(() -> Await.<RestResponse, ApiException>result(timeToWaitForResponse, (onResult, onError) -> {
        AWSRestOperation operation = new AWSRestOperation(request, baseUrl.url().toString(), client, onResult, onError);
        operation.start();
        operation.cancel();
    }));
}
Also used : Collections.emptyMap(java.util.Collections.emptyMap) Assert.assertThrows(org.junit.Assert.assertThrows) RunWith(org.junit.runner.RunWith) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) ApiException(com.amplifyframework.api.ApiException) RestOperationRequest(com.amplifyframework.api.rest.RestOperationRequest) RestResponse(com.amplifyframework.api.rest.RestResponse) RobolectricTestRunner(org.robolectric.RobolectricTestRunner) HttpMethod(com.amplifyframework.api.rest.HttpMethod) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) OkHttpClient(okhttp3.OkHttpClient) Await(com.amplifyframework.testutils.Await) After(org.junit.After) Map(java.util.Map) MockWebServer(okhttp3.mockwebserver.MockWebServer) HttpUrl(okhttp3.HttpUrl) MockResponse(okhttp3.mockwebserver.MockResponse) Assert.assertEquals(org.junit.Assert.assertEquals) Before(org.junit.Before) RestOperationRequest(com.amplifyframework.api.rest.RestOperationRequest) Test(org.junit.Test)

Example 18 with ApiException

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

the class ApiRequestDecoratorFactory method forAuthType.

/**
 * Given a authorization type, it returns the appropriate request decorator.
 * @param authorizationType the authorization type to be used for the request.
 * @return the appropriate request decorator for the given authorization type.
 * @throws ApiAuthException if unable to get a request decorator.
 */
public RequestDecorator forAuthType(@NonNull AuthorizationType authorizationType) throws ApiAuthException {
    switch(authorizationType) {
        case AMAZON_COGNITO_USER_POOLS:
            // Note that if there was no user-provided cognito provider passed in to initialize
            // the API plugin, we will try to default to using the DefaultCognitoUserPoolsAuthProvider.
            // If that fails, we then have no choice but to bubble up the error.
            CognitoUserPoolsAuthProvider cognitoUserPoolsAuthProvider = apiAuthProviders.getCognitoUserPoolsAuthProvider() != null ? apiAuthProviders.getCognitoUserPoolsAuthProvider() : new DefaultCognitoUserPoolsAuthProvider();
            // By calling getLatestAuthToken() here instead of inside the lambda block, makes the exception
            // handling a little bit cleaner. If getLatestAuthToken() is called from inside the lambda expression
            // below, we'd have to surround it with a try catch. By doing it this way, if there's a problem,
            // the ApiException will just be bubbled up. Same for OPENID_CONNECT.
            final String token;
            try {
                token = cognitoUserPoolsAuthProvider.getLatestAuthToken();
            } catch (ApiException exception) {
                throw new ApiAuthException("Failed to retrieve auth token from Cognito provider.", exception, "Check the application logs for details.");
            }
            return new TokenRequestDecorator(() -> token);
        case OPENID_CONNECT:
            if (apiAuthProviders.getOidcAuthProvider() == null) {
                throw new ApiAuthException("Attempting to use OPENID_CONNECT authorization " + "without an OIDC provider.", "Configure an OidcAuthProvider when initializing " + "the API plugin.");
            }
            final String oidcToken;
            try {
                oidcToken = apiAuthProviders.getOidcAuthProvider().getLatestAuthToken();
            } catch (ApiException exception) {
                throw new ApiAuthException("Failed to retrieve auth token from OIDC provider.", exception, "Check the application logs for details.");
            }
            return new TokenRequestDecorator(() -> oidcToken);
        case AWS_LAMBDA:
            if (apiAuthProviders.getFunctionAuthProvider() == null) {
                throw new ApiAuthException("Attempting to use AWS_LAMBDA authorization " + "without a provider implemented.", "Configure a FunctionAuthProvider when initializing the API plugin.");
            }
            final String functionToken;
            try {
                functionToken = apiAuthProviders.getFunctionAuthProvider().getLatestAuthToken();
            } catch (ApiException exception) {
                throw new ApiAuthException("Failed to retrieve auth token from function auth provider.", exception, "Check the application logs for details.");
            }
            return new TokenRequestDecorator(() -> functionToken);
        case API_KEY:
            if (apiAuthProviders.getApiKeyAuthProvider() != null) {
                return new ApiKeyRequestDecorator(apiAuthProviders.getApiKeyAuthProvider());
            } else if (apiKey != null) {
                return new ApiKeyRequestDecorator(() -> apiKey);
            } else {
                throw new ApiAuthException("Attempting to use API_KEY authorization without " + "an API key provider or an API key in the config file", "Verify that an API key is in the config file or an " + "ApiKeyAuthProvider is setup during the API " + "plugin initialization.");
            }
        case AWS_IAM:
            AWSCredentialsProvider credentialsProvider = apiAuthProviders.getAWSCredentialsProvider() != null ? apiAuthProviders.getAWSCredentialsProvider() : getDefaultCredentialsProvider();
            final AWS4Signer signer;
            final String serviceName;
            if (endpointType == EndpointType.GRAPHQL) {
                signer = new AppSyncV4Signer(region);
                serviceName = APP_SYNC_SERVICE_NAME;
            } else {
                signer = new ApiGatewayIamSigner(region);
                serviceName = API_GATEWAY_SERVICE_NAME;
            }
            return new IamRequestDecorator(signer, credentialsProvider, serviceName);
        case NONE:
        default:
            return NO_OP_REQUEST_DECORATOR;
    }
}
Also used : ApiAuthException(com.amplifyframework.api.ApiException.ApiAuthException) DefaultCognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.DefaultCognitoUserPoolsAuthProvider) AWS4Signer(com.amazonaws.auth.AWS4Signer) ApiGatewayIamSigner(com.amplifyframework.api.aws.sigv4.ApiGatewayIamSigner) DefaultCognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.DefaultCognitoUserPoolsAuthProvider) CognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.CognitoUserPoolsAuthProvider) AWSCredentialsProvider(com.amazonaws.auth.AWSCredentialsProvider) ApiException(com.amplifyframework.api.ApiException) AppSyncV4Signer(com.amplifyframework.api.aws.sigv4.AppSyncV4Signer)

Example 19 with ApiException

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

the class DefaultCognitoUserPoolsAuthProvider method fetchToken.

// Fetches token from the mobile client.
private synchronized void fetchToken() throws ApiException {
    final Semaphore semaphore = new Semaphore(0);
    lastTokenRetrievalFailureMessage = null;
    awsMobileClient.getTokens(new Callback<Tokens>() {

        @Override
        public void onResult(Tokens result) {
            token = result.getAccessToken().getTokenString();
            semaphore.release();
        }

        @Override
        public void onError(Exception error) {
            lastTokenRetrievalFailureMessage = error.getLocalizedMessage();
            semaphore.release();
        }
    });
    try {
        semaphore.acquire();
    } catch (InterruptedException exception) {
        throw new ApiException("Interrupted waiting for Cognito Userpools token.", exception, AmplifyException.TODO_RECOVERY_SUGGESTION);
    }
    if (lastTokenRetrievalFailureMessage != null) {
        throw new ApiAuthException(lastTokenRetrievalFailureMessage, AmplifyException.TODO_RECOVERY_SUGGESTION);
    }
}
Also used : ApiAuthException(com.amplifyframework.api.ApiException.ApiAuthException) Semaphore(java.util.concurrent.Semaphore) AmplifyException(com.amplifyframework.AmplifyException) ApiException(com.amplifyframework.api.ApiException) ApiAuthException(com.amplifyframework.api.ApiException.ApiAuthException) Tokens(com.amazonaws.mobile.client.results.Tokens) ApiException(com.amplifyframework.api.ApiException)

Example 20 with ApiException

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

the class AWSDataStorePluginTest method mockApiPluginWithExceptions.

/**
 * Almost the same as mockApiCategoryWithGraphQlApi, but it calls the onError callback instead.
 *
 * @return A mock version of the API Category.
 * @throws AmplifyException Throw if an error happens when adding the plugin.
 */
@SuppressWarnings("unchecked")
private static ApiCategory mockApiPluginWithExceptions() throws AmplifyException {
    ApiCategory mockApiCategory = spy(ApiCategory.class);
    ApiPlugin<?> mockApiPlugin = mock(ApiPlugin.class);
    when(mockApiPlugin.getPluginKey()).thenReturn(MOCK_API_PLUGIN_NAME);
    when(mockApiPlugin.getCategoryType()).thenReturn(CategoryType.API);
    doAnswer(invocation -> {
        int indexOfErrorConsumer = 2;
        Consumer<ApiException> onError = invocation.getArgument(indexOfErrorConsumer);
        onError.accept(new ApiException("Fake exception thrown from the API.query method", "Just retry"));
        return null;
    }).when(mockApiPlugin).query(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class));
    doAnswer(invocation -> {
        int indexOfErrorConsumer = 2;
        Consumer<ApiException> onError = invocation.getArgument(indexOfErrorConsumer);
        onError.accept(new ApiException("Fake exception thrown from the API.mutate method", "Just retry"));
        return null;
    }).when(mockApiPlugin).mutate(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class));
    doAnswer(invocation -> {
        int indexOfErrorConsumer = 3;
        Consumer<ApiException> onError = invocation.getArgument(indexOfErrorConsumer);
        ApiException apiException = new ApiException("Fake exception thrown from the API.subscribe method", "Just retry");
        onError.accept(apiException);
        return null;
    }).when(mockApiPlugin).subscribe(any(GraphQLRequest.class), any(Consumer.class), any(Consumer.class), any(Consumer.class), any(Action.class));
    mockApiCategory.addPlugin(mockApiPlugin);
    return mockApiCategory;
}
Also used : GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Action(com.amplifyframework.core.Action) Consumer(com.amplifyframework.core.Consumer) ApiCategory(com.amplifyframework.api.ApiCategory) ApiException(com.amplifyframework.api.ApiException)

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