Search in sources :

Example 11 with ApiException

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

the class SynchronousApi method onCreate.

/**
 * Subscribe to create mutations, by forming a GraphQL subscription request.
 *
 * @param apiName One of the configured APIs
 * @param request A GraphQL subscription request
 * @param <T>     Type of object for which creation notifications are generated
 * @return An observable with which creations may be observed
 */
@NonNull
public <T> Observable<GraphQLResponse<T>> onCreate(@NonNull String apiName, @NonNull GraphQLRequest<T> request) {
    return Observable.create(emitter -> {
        CompositeDisposable disposable = new CompositeDisposable();
        emitter.setDisposable(disposable);
        Await.<String, ApiException>result(OPERATION_TIMEOUT_MS, (onSubscriptionStarted, onError) -> {
            Cancelable cancelable = asyncDelegate.subscribe(apiName, request, onSubscriptionStarted, emitter::onNext, onError, emitter::onComplete);
            if (cancelable != null) {
                disposable.add(Disposable.fromAction(cancelable::cancel));
            }
        });
    });
}
Also used : Cancelable(com.amplifyframework.core.async.Cancelable) CompositeDisposable(io.reactivex.rxjava3.disposables.CompositeDisposable) ApiException(com.amplifyframework.api.ApiException) NonNull(androidx.annotation.NonNull)

Example 12 with ApiException

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

the class AWSApiPluginTest method headerInterceptorsAreConfigured.

/**
 * Validates that the plugin adds custom headers into the outgoing OkHttp request.
 * @throws ApiException Thrown from the query() call.
 * @throws InterruptedException Possible thrown from takeRequest()
 */
@Test
public void headerInterceptorsAreConfigured() throws ApiException, InterruptedException {
    // Arrange some response. This isn't the point of the test,
    // but it keeps the mock web server from freezing up.
    webServer.enqueue(new MockResponse().setBody(Resources.readAsString("blog-owners-query-results.json")));
    // Fire off a request
    Await.<GraphQLResponse<PaginatedResult<BlogOwner>>, ApiException>result((onResult, onError) -> plugin.query(ModelQuery.list(BlogOwner.class), onResult, onError));
    RecordedRequest recordedRequest = webServer.takeRequest(5, TimeUnit.MILLISECONDS);
    assertNotNull(recordedRequest);
    assertEquals("specialValue", recordedRequest.getHeader("specialKey"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 13 with ApiException

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

the class AWSApiPluginTest method requestUsesIamForAuth.

/**
 * Ensure the auth mode used for the request is AWS_IAM. We verify this by
 * @throws AmplifyException Not expected.
 * @throws InterruptedException Not expected.
 */
@Test
public void requestUsesIamForAuth() throws AmplifyException, InterruptedException {
    webServer.enqueue(new MockResponse().setBody(Resources.readAsString("blog-owners-query-results.json")));
    AppSyncGraphQLRequest<PaginatedResult<BlogOwner>> appSyncGraphQLRequest = createQueryRequestWithAuthMode(BlogOwner.class, AuthorizationType.AWS_IAM);
    GraphQLResponse<PaginatedResult<BlogOwner>> actualResponse = Await.<GraphQLResponse<PaginatedResult<BlogOwner>>, ApiException>result((onResult, onError) -> plugin.query(appSyncGraphQLRequest, onResult, onError));
    RecordedRequest recordedRequest = webServer.takeRequest();
    assertNull(recordedRequest.getHeader("x-api-key"));
    assertNotNull(recordedRequest.getHeader("authorization"));
    assertTrue(recordedRequest.getHeader("authorization").startsWith("AWS4-HMAC-SHA256"));
    assertEquals(Arrays.asList("Curly", "Moe", "Larry"), Observable.fromIterable(actualResponse.getData()).map(BlogOwner::getName).toList().blockingGet());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 14 with ApiException

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

the class AWSApiPluginTest method requestUsesCognitoForAuth.

/**
 * If the auth mode is set for the individual request, ensure that the resulting request
 * to AppSync has the correct auth header.
 * @throws AmplifyException Not expected.
 * @throws InterruptedException Not expected.
 */
@Test
public void requestUsesCognitoForAuth() throws AmplifyException, InterruptedException {
    webServer.enqueue(new MockResponse().setBody(Resources.readAsString("blog-owners-query-results.json")));
    AppSyncGraphQLRequest<PaginatedResult<BlogOwner>> appSyncGraphQLRequest = createQueryRequestWithAuthMode(BlogOwner.class, AuthorizationType.AMAZON_COGNITO_USER_POOLS);
    GraphQLResponse<PaginatedResult<BlogOwner>> actualResponse = Await.<GraphQLResponse<PaginatedResult<BlogOwner>>, ApiException>result((onResult, onError) -> plugin.query(appSyncGraphQLRequest, onResult, onError));
    RecordedRequest recordedRequest = webServer.takeRequest();
    assertNull(recordedRequest.getHeader("x-api-key"));
    assertNotNull(recordedRequest.getHeader("authorization"));
    assertEquals("FAKE_TOKEN", recordedRequest.getHeader("authorization"));
    assertEquals(Arrays.asList("Curly", "Moe", "Larry"), Observable.fromIterable(actualResponse.getData()).map(BlogOwner::getName).toList().blockingGet());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) ApiException(com.amplifyframework.api.ApiException) Test(org.junit.Test)

Example 15 with ApiException

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

the class AWSApiPluginTest method setup.

/**
 * Sets up the test.
 * @throws ApiException On failure to configure plugin
 * @throws IOException On failure to start web server
 * @throws JSONException On failure to arrange configuration JSON
 */
@Before
public void setup() throws ApiException, IOException, JSONException {
    webServer = new MockWebServer();
    webServer.start(8080);
    baseUrl = webServer.url("/");
    JSONObject configuration = new JSONObject().put("graphQlApi", new JSONObject().put("endpointType", "GraphQL").put("endpoint", baseUrl.url()).put("region", "us-east-1").put("authorizationType", "API_KEY").put("apiKey", "FAKE-API-KEY"));
    ApiAuthProviders apiAuthProviders = ApiAuthProviders.builder().awsCredentialsProvider(new AWSCredentialsProvider() {

        @Override
        public AWSCredentials getCredentials() {
            return new BasicAWSCredentials("DUMMY_ID", "DUMMY_SECRET");
        }

        @Override
        public void refresh() {
        }
    }).cognitoUserPoolsAuthProvider(new CognitoUserPoolsAuthProvider() {

        @Override
        public String getLatestAuthToken() throws ApiException {
            return "FAKE_TOKEN";
        }

        @Override
        public String getUsername() {
            return "FAKE_USER";
        }
    }).build();
    this.plugin = AWSApiPlugin.builder().configureClient("graphQlApi", builder -> {
        builder.addInterceptor(chain -> {
            return chain.proceed(chain.request().newBuilder().addHeader("specialKey", "specialValue").build());
        });
        builder.connectTimeout(10, TimeUnit.SECONDS);
    }).apiAuthProviders(apiAuthProviders).build();
    this.plugin.configure(configuration, ApplicationProvider.getApplicationContext());
}
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) JSONObject(org.json.JSONObject) MockWebServer(okhttp3.mockwebserver.MockWebServer) AWSCredentials(com.amazonaws.auth.AWSCredentials) BasicAWSCredentials(com.amazonaws.auth.BasicAWSCredentials) CognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.CognitoUserPoolsAuthProvider) AWSCredentialsProvider(com.amazonaws.auth.AWSCredentialsProvider) BasicAWSCredentials(com.amazonaws.auth.BasicAWSCredentials) Before(org.junit.Before)

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