Search in sources :

Example 26 with ApiException

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

the class SynchronousApi method onCreate.

/**
 * Subscribe to model creations.
 *
 * @param apiName One of the configured API endpoints
 * @param clazz   Class of model for which you want notifications when they're created
 * @param <T>     The type of model for which creation notifications will be dispatched
 * @return An Observable that can be used to observe the subscription data
 */
@SuppressWarnings("CodeBlock2Expr")
@NonNull
public <T extends Model> Observable<GraphQLResponse<T>> onCreate(@NonNull String apiName, @NonNull Class<T> clazz) {
    return Observable.create(emitter -> {
        Await.<String, ApiException>result(OPERATION_TIMEOUT_MS, (onSubscriptionStarted, onError) -> {
            Cancelable cancelable = asyncDelegate.subscribe(apiName, ModelSubscription.onCreate(clazz), onSubscriptionStarted, emitter::onNext, onError, emitter::onComplete);
            emitter.setDisposable(AmplifyDisposables.fromCancelable(cancelable));
        });
    });
}
Also used : Cancelable(com.amplifyframework.core.async.Cancelable) ApiException(com.amplifyframework.api.ApiException) NonNull(androidx.annotation.NonNull)

Example 27 with ApiException

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

the class SubscriptionEndpointTest method subscribeToEventComments.

/**
 * Subscribe to comments on an event.
 * @param eventId ID of event for which comments are being made
 * @return Subscription ID received from subscription_ack message payload
 * @throws ApiException If outcome of subscription request is anything other than an ACK w/ new ID
 */
private String subscribeToEventComments(String eventId) throws ApiException {
    // Arrange a request to start a subscription.
    String document = Assets.readAsString("subscribe-event-comments.graphql");
    GsonVariablesSerializer serializer = new GsonVariablesSerializer();
    Map<String, Object> variables = Collections.singletonMap("eventId", eventId);
    GraphQLRequest<String> request = new SimpleGraphQLRequest<>(document, variables, String.class, serializer);
    return Await.<String, ApiException>result((onResult, onError) -> executor.execute(() -> subscriptionEndpoint.requestSubscription(request, onResult, item -> {
        final String message;
        if (item.hasErrors()) {
            message = "Subscription error: " + item.getErrors().toString();
        } else {
            message = "Unexpected subscription data: " + item.getData();
        }
        ApiException apiException = new ApiException(message, "Not expected.");
        onError.accept(apiException);
    }, error -> onError.accept(new ApiException("Subscription failed.", error, "Not expected.")), () -> onError.accept(new ApiException("Subscription completed too soon.", "Not expected.")))));
}
Also used : SimpleGraphQLRequest(com.amplifyframework.api.graphql.SimpleGraphQLRequest) JSONObject(org.json.JSONObject) RandomString(com.amplifyframework.testutils.random.RandomString) ApiException(com.amplifyframework.api.ApiException)

Example 28 with ApiException

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

the class AWSRestOperationTest method responseEmittedWhenOperationSucceeds.

/**
 * Tests the happy path, wherein the server returns a response, the
 * operation hasn't been canceled, and we get a {@link RestResponse}
 * at the end of it.
 * @throws ApiException
 *         A possible outcome of the operation. This is not
 *         expected, and would constitute a test failure.
 */
@Test
public void responseEmittedWhenOperationSucceeds() throws ApiException {
    RestOperationRequest request = new RestOperationRequest(HttpMethod.GET, baseUrl.uri().getPath(), emptyMap(), emptyMap());
    RestResponse response = Await.<RestResponse, ApiException>result((onResult, onError) -> {
        AWSRestOperation operation = new AWSRestOperation(request, baseUrl.url().toString(), client, onResult, onError);
        operation.start();
    });
    assertTrue(response.getCode().isSuccessful());
    Map<String, String> expected = new HashMap<>();
    expected.put("foo", "bar,baz");
    expected.put("qux", "quux");
    expected.put("content-length", "21");
    assertEquals(expected, response.getHeaders());
}
Also used : HashMap(java.util.HashMap) RestResponse(com.amplifyframework.api.rest.RestResponse) RestOperationRequest(com.amplifyframework.api.rest.RestOperationRequest) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 29 with ApiException

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

the class MultiAuthAppSyncGraphQLOperation method dispatchRequest.

private void dispatchRequest() {
    if (authTypes.hasNext()) {
        AuthorizationType authType = authTypes.next();
        Request okHttpRequest = new Request.Builder().url(endpoint).addHeader("accept", CONTENT_TYPE).addHeader("content-type", CONTENT_TYPE).post(RequestBody.create(getRequest().getContent(), MediaType.parse(CONTENT_TYPE))).build();
        Request decoratedOkHttpRequest;
        try {
            RequestDecorator requestDecorator = apiRequestDecoratorFactory.forAuthType(authType);
            decoratedOkHttpRequest = requestDecorator.decorate(okHttpRequest);
        } catch (ApiException apiException) {
            LOG.warn("Failed to make a successful request with " + authType, apiException);
            // Only queue up a retry if it's an auth-related exception.
            if (apiException instanceof ApiAuthException && authTypes.hasNext()) {
                executorService.submit(this::dispatchRequest);
            } else {
                onFailure.accept(apiException);
            }
            return;
        }
        LOG.debug("Request: " + getRequest().getContent());
        ongoingCall = client.newCall(decoratedOkHttpRequest);
        ongoingCall.enqueue(new OkHttpCallback());
    } else {
        onFailure.accept(new ApiAuthException("Unable to successfully complete request with any of the compatible auth types.", "Check your application logs for detail."));
    }
}
Also used : ApiAuthException(com.amplifyframework.api.ApiException.ApiAuthException) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Request(okhttp3.Request) RequestDecorator(com.amplifyframework.api.aws.auth.RequestDecorator) ApiException(com.amplifyframework.api.ApiException)

Example 30 with ApiException

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

the class SubscriptionEndpoint method buildConnectionRequestUrl.

/*
     * Discover WebSocket endpoint from the AppSync endpoint.
     * AppSync endpoint : https://xxxxxxxxxxxx.appsync-api.ap-southeast-2.amazonaws.com/graphql
     * Discovered WebSocket endpoint : wss:// xxxxxxxxxxxx.appsync-realtime-api.ap-southeast-2.amazonaws.com/graphql
     */
private String buildConnectionRequestUrl(AuthorizationType authType) throws ApiException {
    // Construct the authorization header for connection request
    final byte[] rawHeader = authorizer.createHeadersForConnection(authType).toString().getBytes();
    URL appSyncEndpoint = null;
    try {
        appSyncEndpoint = new URL(apiConfiguration.getEndpoint());
    } catch (MalformedURLException malformedUrlException) {
    // throwing in a second ...
    }
    if (appSyncEndpoint == null) {
        throw new ApiException("Malformed API Url: " + apiConfiguration.getEndpoint(), "Verify that GraphQL endpoint is properly formatted.");
    }
    DomainType domainType = DomainType.from(apiConfiguration.getEndpoint());
    String authority = appSyncEndpoint.getHost();
    if (domainType == DomainType.STANDARD) {
        authority = authority.replace("appsync-api", "appsync-realtime-api");
    }
    String path = appSyncEndpoint.getPath();
    if (domainType == DomainType.CUSTOM) {
        path = path + "/realtime";
    }
    return new Uri.Builder().scheme("wss").authority(authority).appendPath(path).appendQueryParameter("header", Base64.encodeToString(rawHeader, Base64.DEFAULT)).appendQueryParameter("payload", "e30=").build().toString();
}
Also used : MalformedURLException(java.net.MalformedURLException) Uri(android.net.Uri) URL(java.net.URL) 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