software.amazon.awssdk.core.interceptor.ExecutionInterceptor Java Examples

The following examples show how to use software.amazon.awssdk.core.interceptor.ExecutionInterceptor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void sync_streamingOutput_success_allInterceptorMethodsCalled() throws IOException {
    // Given
    ExecutionInterceptor interceptor = mock(NoOpInterceptor.class, CALLS_REAL_METHODS);
    ProtocolRestJsonClient client = client(interceptor);
    StreamingOutputOperationRequest request = StreamingOutputOperationRequest.builder().build();
    stubFor(post(urlPathEqualTo(STREAMING_OUTPUT_PATH)).willReturn(aResponse().withStatus(200).withBody("\0")));

    // When
    client.streamingOutputOperation(request, (r, i) -> {
        assertThat(i.read()).isEqualTo(0);
        // TODO: We have to return "r" here. We should verify other response types are cool once we switch this off of
        // being the unmarshaller
        return r;
    });

    // Expect
    Context.AfterTransmission afterTransmissionArg = captureAfterTransmissionArg(interceptor);
    // TODO: When we don't always close the input stream, make sure we can read the service's '0' response.
    assertThat(afterTransmissionArg.responseBody() != null);
}
 
Example #2
Source File: EnhancedClientGetOverheadBenchmark.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Setup
public void setup(Blackhole bh) {
    dynamoDb = DynamoDbClient.builder()
            .credentialsProvider(StaticCredentialsProvider.create(
                    AwsBasicCredentials.create("akid", "skid")))
            .httpClient(new MockHttpClient(testItem.responseContent, "{}"))
            .overrideConfiguration(o -> o.addExecutionInterceptor(new ExecutionInterceptor() {
                @Override
                public void afterUnmarshalling(Context.AfterUnmarshalling context,
                                               ExecutionAttributes executionAttributes) {
                    bh.consume(context);
                    bh.consume(executionAttributes);
                }
            }))
            .build();

    DynamoDbEnhancedClient ddbEnh = DynamoDbEnhancedClient.builder()
            .dynamoDbClient(dynamoDb)
            .build();

    table = ddbEnh.table(testItem.name(), testItem.tableSchema);
}
 
Example #3
Source File: EnhancedClientPutOverheadBenchmark.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Setup
public void setup(Blackhole bh) {
    ddb = DynamoDbClient.builder()
            .credentialsProvider(StaticCredentialsProvider.create(
                    AwsBasicCredentials.create("akid", "skid")))
            .httpClient(new MockHttpClient("{}", "{}"))
            .overrideConfiguration(c -> c.addExecutionInterceptor(new ExecutionInterceptor() {
                @Override
                public void afterUnmarshalling(Context.AfterUnmarshalling context,
                                               ExecutionAttributes executionAttributes) {
                    bh.consume(context);
                    bh.consume(executionAttributes);
                }
            }))
            .build();

    DynamoDbEnhancedClient ddbEnh = DynamoDbEnhancedClient.builder()
            .dynamoDbClient(ddb)
            .build();

    enhTable = ddbEnh.table(testItem.name(), testItem.tableSchema);
}
 
Example #4
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private Context.AfterTransmission captureAfterTransmissionArgAsync(ExecutionInterceptor interceptor) {
    ArgumentCaptor<Context.AfterTransmission> afterTransmissionArg = ArgumentCaptor.forClass(Context.AfterTransmission.class);

    InOrder inOrder = Mockito.inOrder(interceptor);
    inOrder.verify(interceptor).beforeExecution(any(), any());
    inOrder.verify(interceptor).modifyRequest(any(), any());
    inOrder.verify(interceptor).beforeMarshalling(any(), any());
    inOrder.verify(interceptor).afterMarshalling(any(), any());
    inOrder.verify(interceptor).modifyAsyncHttpContent(any(), any());
    inOrder.verify(interceptor).modifyHttpContent(any(), any());
    inOrder.verify(interceptor).modifyHttpRequest(any(), any());
    inOrder.verify(interceptor).beforeTransmission(any(), any());
    inOrder.verify(interceptor).afterTransmission(afterTransmissionArg.capture(), any());
    inOrder.verify(interceptor).modifyHttpResponse(any(), any());
    inOrder.verify(interceptor).modifyHttpResponseContent(any(), any());
    inOrder.verify(interceptor).beforeUnmarshalling(any(), any());
    inOrder.verify(interceptor).afterUnmarshalling(any(), any());
    inOrder.verify(interceptor).modifyResponse(any(), any());
    inOrder.verify(interceptor).modifyAsyncHttpResponseContent(any(), any());
    inOrder.verify(interceptor).afterExecution(any(), any());
    verifyNoMoreInteractions(interceptor);
    return afterTransmissionArg.getValue();
}
 
Example #5
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private Context.AfterTransmission captureAfterTransmissionArg(ExecutionInterceptor interceptor) {
    ArgumentCaptor<Context.AfterTransmission> afterTransmissionArg = ArgumentCaptor.forClass(Context.AfterTransmission.class);

    InOrder inOrder = Mockito.inOrder(interceptor);
    inOrder.verify(interceptor).beforeExecution(any(), any());
    inOrder.verify(interceptor).modifyRequest(any(), any());
    inOrder.verify(interceptor).beforeMarshalling(any(), any());
    inOrder.verify(interceptor).afterMarshalling(any(), any());
    inOrder.verify(interceptor).modifyAsyncHttpContent(any(), any());
    inOrder.verify(interceptor).modifyHttpContent(any(), any());
    inOrder.verify(interceptor).modifyHttpRequest(any(), any());
    inOrder.verify(interceptor).beforeTransmission(any(), any());
    inOrder.verify(interceptor).afterTransmission(afterTransmissionArg.capture(), any());
    inOrder.verify(interceptor).modifyHttpResponse(any(), any());
    inOrder.verify(interceptor).modifyHttpResponseContent(any(), any());
    inOrder.verify(interceptor).beforeUnmarshalling(any(), any());
    inOrder.verify(interceptor).afterUnmarshalling(any(), any());
    inOrder.verify(interceptor).modifyResponse(any(), any());
    inOrder.verify(interceptor).afterExecution(any(), any());
    verifyNoMoreInteractions(interceptor);
    return afterTransmissionArg.getValue();
}
 
Example #6
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private Context.BeforeTransmission captureBeforeTransmissionArg(ExecutionInterceptor interceptor, boolean isAsync) {
    ArgumentCaptor<Context.BeforeTransmission> beforeTransmissionArg = ArgumentCaptor.forClass(Context.BeforeTransmission.class);

    InOrder inOrder = Mockito.inOrder(interceptor);
    inOrder.verify(interceptor).beforeExecution(any(), any());
    inOrder.verify(interceptor).modifyRequest(any(), any());
    inOrder.verify(interceptor).beforeMarshalling(any(), any());
    inOrder.verify(interceptor).afterMarshalling(any(), any());
    inOrder.verify(interceptor).modifyAsyncHttpContent(any(), any());
    inOrder.verify(interceptor).modifyHttpContent(any(), any());
    inOrder.verify(interceptor).modifyHttpRequest(any(), any());
    inOrder.verify(interceptor).beforeTransmission(beforeTransmissionArg.capture(), any());
    inOrder.verify(interceptor).afterTransmission(any(), any());
    inOrder.verify(interceptor).modifyHttpResponse(any(), any());
    inOrder.verify(interceptor).modifyHttpResponseContent(any(), any());
    inOrder.verify(interceptor).beforeUnmarshalling(any(), any());
    if (isAsync) {
        inOrder.verify(interceptor).modifyAsyncHttpResponseContent(any(), any());
    }
    inOrder.verify(interceptor).afterUnmarshalling(any(), any());
    inOrder.verify(interceptor).modifyResponse(any(), any());
    inOrder.verify(interceptor).afterExecution(any(), any());
    verifyNoMoreInteractions(interceptor);
    return beforeTransmissionArg.getValue();
}
 
Example #7
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void async_interceptorException_failureInterceptorMethodsCalled() {
    // Given
    ExecutionInterceptor interceptor = mock(MessageUpdatingInterceptor.class, CALLS_REAL_METHODS);
    RuntimeException exception = new RuntimeException("Uh oh!");
    doThrow(exception).when(interceptor).afterExecution(any(), any());

    ProtocolRestJsonAsyncClient client = asyncClient(interceptor);
    MembersInHeadersRequest request = MembersInHeadersRequest.builder().build();
    stubFor(post(urlPathEqualTo(MEMBERS_IN_HEADERS_PATH)).willReturn(aResponse().withStatus(200).withBody("")));

    // When
    assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> client.membersInHeaders(request).get())
                                                       .withCause(SdkClientException.builder()
                                                                                    .cause(exception)
                                                                                    .build());

    // Expect
    expectAllMethodsCalled(interceptor, request, exception, true);
}
 
Example #8
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void sync_interceptorException_failureInterceptorMethodsCalled() {
    // Given
    ExecutionInterceptor interceptor = mock(MessageUpdatingInterceptor.class, CALLS_REAL_METHODS);
    RuntimeException exception = new RuntimeException("Uh oh!");
    doThrow(exception).when(interceptor).afterExecution(any(), any());

    ProtocolRestJsonClient client = client(interceptor);
    MembersInHeadersRequest request = MembersInHeadersRequest.builder().build();
    stubFor(post(urlPathEqualTo(MEMBERS_IN_HEADERS_PATH)).willReturn(aResponse().withStatus(200).withBody("")));

    // When
    assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> client.membersInHeaders(request));

    // Expect
    expectAllMethodsCalled(interceptor, request, exception, false);
}
 
Example #9
Source File: ClientOverrideConfigurationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGuaranteeImmutability() {
    List<String> headerValues = new ArrayList<>();
    headerValues.add("bar");
    Map<String, List<String>> headers = new HashMap<>();
    headers.put("foo", headerValues);

    List<ExecutionInterceptor> executionInterceptors = new ArrayList<>();
    SlowExecutionInterceptor slowExecutionInterceptor = new SlowExecutionInterceptor();
    executionInterceptors.add(slowExecutionInterceptor);

    ClientOverrideConfiguration.Builder configurationBuilder =
        ClientOverrideConfiguration.builder().executionInterceptors(executionInterceptors)
                                   .headers(headers);

    headerValues.add("test");
    headers.put("new header", Collections.singletonList("new value"));
    executionInterceptors.clear();

    assertThat(configurationBuilder.headers().size()).isEqualTo(1);
    assertThat(configurationBuilder.headers().get("foo")).containsExactly("bar");
    assertThat(configurationBuilder.executionInterceptors()).containsExactly(slowExecutionInterceptor);
}
 
Example #10
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void async_streamingOutput_success_allInterceptorMethodsCalled()
        throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // Given
    ExecutionInterceptor interceptor = mock(NoOpInterceptor.class, CALLS_REAL_METHODS);
    ProtocolRestJsonAsyncClient client = asyncClient(interceptor);
    StreamingOutputOperationRequest request = StreamingOutputOperationRequest.builder().build();
    stubFor(post(urlPathEqualTo(STREAMING_OUTPUT_PATH)).willReturn(aResponse().withStatus(200).withBody("\0")));

    // When
    client.streamingOutputOperation(request, new NoOpAsyncResponseTransformer()).get(10, TimeUnit.SECONDS);

    // Expect
    Context.AfterTransmission afterTransmissionArg = captureAfterTransmissionArgAsync(interceptor);
    assertThat(afterTransmissionArg.responseBody()).isNotNull();
}
 
Example #11
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void async_streamingInput_success_allInterceptorMethodsCalled()
        throws ExecutionException, InterruptedException, TimeoutException, IOException {
    // Given
    ExecutionInterceptor interceptor = mock(NoOpInterceptor.class, CALLS_REAL_METHODS);
    ProtocolRestJsonAsyncClient client = asyncClient(interceptor);
    StreamingInputOperationRequest request = StreamingInputOperationRequest.builder().build();
    stubFor(post(urlPathEqualTo(STREAMING_INPUT_PATH)).willReturn(aResponse().withStatus(200).withBody("")));

    // When
    client.streamingInputOperation(request, new NoOpAsyncRequestBody()).get(10, TimeUnit.SECONDS);

    // Expect
    Context.BeforeTransmission beforeTransmissionArg = captureBeforeTransmissionArg(interceptor, true);

    // TODO: The content should actually be empty to match responses. We can fix this by updating the StructuredJsonGenerator
    // to use null for NO-OP marshalling of payloads. This will break streaming POST operations for JSON because of a hack in
    // the MoveParametersToBodyStage, but we can move the logic from there into the query marshallers (why the hack exists)
    // and then everything should be good for JSON.
    assertThat(beforeTransmissionArg.requestBody().get().contentStreamProvider().newStream().read()).isEqualTo(-1);
    assertThat(beforeTransmissionArg.httpRequest().firstMatchingHeader(Header.CONTENT_LENGTH).get())
        .contains(Long.toString(0L));
}
 
Example #12
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void sync_streamingInput_success_allInterceptorMethodsCalled() throws IOException {
    // Given
    ExecutionInterceptor interceptor = mock(NoOpInterceptor.class, CALLS_REAL_METHODS);
    ProtocolRestJsonClient client = client(interceptor);
    StreamingInputOperationRequest request = StreamingInputOperationRequest.builder().build();
    stubFor(post(urlPathEqualTo(STREAMING_INPUT_PATH)).willReturn(aResponse().withStatus(200).withBody("")));

    // When
    client.streamingInputOperation(request, RequestBody.fromBytes(new byte[] {0}));

    // Expect
    Context.BeforeTransmission beforeTransmissionArg = captureBeforeTransmissionArg(interceptor, false);
    assertThat(beforeTransmissionArg.requestBody().get().contentStreamProvider().newStream().read()).isEqualTo(0);
    assertThat(beforeTransmissionArg.httpRequest().firstMatchingHeader(Header.CONTENT_LENGTH).get())
        .contains(Long.toString(1L));
}
 
Example #13
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void async_success_allInterceptorMethodsCalled()
        throws ExecutionException, InterruptedException, TimeoutException {
    // Given
    ExecutionInterceptor interceptor = mock(MessageUpdatingInterceptor.class, CALLS_REAL_METHODS);
    ProtocolRestJsonAsyncClient client = asyncClient(interceptor);
    MembersInHeadersRequest request = MembersInHeadersRequest.builder().build();
    stubFor(post(urlPathEqualTo(MEMBERS_IN_HEADERS_PATH)).willReturn(aResponse().withStatus(200).withBody("")));

    // When
    MembersInHeadersResponse result = client.membersInHeaders(request).get(10, TimeUnit.SECONDS);

    // Expect
    expectAllMethodsCalled(interceptor, request, null, true);
    validateRequestResponse(result);
}
 
Example #14
Source File: HttpClientApiCallAttemptTimeoutTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private ExecutionContext withInterceptors(ExecutionInterceptor... requestHandlers) {

        ExecutionInterceptorChain interceptors =
            new ExecutionInterceptorChain(Arrays.asList(requestHandlers));

        InterceptorContext incerceptorContext =
            InterceptorContext.builder()
                              .request(NoopTestRequest.builder().build())
                              .httpRequest(generateRequest())
                              .build();
        return ExecutionContext.builder()
                               .signer(new NoOpSigner())
                               .interceptorChain(interceptors)
                               .executionAttributes(new ExecutionAttributes())
                               .interceptorContext(incerceptorContext)
                               .build();
    }
 
Example #15
Source File: HttpClientApiCallTimeoutTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private ExecutionContext withInterceptors(ExecutionInterceptor... requestHandlers) {

        ExecutionInterceptorChain interceptors =
            new ExecutionInterceptorChain(Arrays.asList(requestHandlers));

        InterceptorContext incerceptorContext =
            InterceptorContext.builder()
                              .request(NoopTestRequest.builder().build())
                              .httpRequest(generateRequest())
                              .build();
        return ExecutionContext.builder()
                               .signer(new NoOpSigner())
                               .interceptorChain(interceptors)
                               .executionAttributes(new ExecutionAttributes())
                               .interceptorContext(incerceptorContext)
                               .build();
    }
 
Example #16
Source File: AsyncHttpClientApiCallTimeoutTests.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private ExecutionContext withInterceptors(ExecutionInterceptor... requestHandlers) {

        ExecutionInterceptorChain interceptors =
            new ExecutionInterceptorChain(Arrays.asList(requestHandlers));

        InterceptorContext incerceptorContext =
            InterceptorContext.builder()
                              .request(NoopTestRequest.builder().build())
                              .httpRequest(generateRequest())
                              .build();
        return ExecutionContext.builder()
                               .signer(new NoOpSigner())
                               .interceptorChain(interceptors)
                               .executionAttributes(new ExecutionAttributes())
                               .interceptorContext(incerceptorContext)
                               .build();
    }
 
Example #17
Source File: MirrorImporterConfiguration.java    From hedera-mirror-node with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnProperty(prefix = "hedera.mirror.importer.downloader", name = "cloudProvider", havingValue = "GCP")
public S3AsyncClient gcpCloudStorageClient() {
    log.info("Configured to download from GCP with bucket name '{}'", downloaderProperties.getBucketName());
    // Any valid region for aws client. Ignored by GCP.
    S3AsyncClientBuilder clientBuilder = asyncClientBuilder("us-east-1")
            .endpointOverride(URI.create(downloaderProperties.getCloudProvider().getEndpoint()));
    String projectId = downloaderProperties.getGcpProjectId();
    if (StringUtils.isNotBlank(projectId)) {
        clientBuilder.overrideConfiguration(builder -> builder.addExecutionInterceptor(new ExecutionInterceptor() {
            @Override
            public SdkHttpRequest modifyHttpRequest(
                    Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
                return context.httpRequest().toBuilder()
                        .appendRawQueryParameter("userProject", projectId).build();
            }
        }));
    }
    return clientBuilder.build();
}
 
Example #18
Source File: AmazonClientRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private ExecutionInterceptor createInterceptor(Class<?> interceptorClass) {
    try {
        return (ExecutionInterceptor) Class.forName(interceptorClass.getName()).newInstance();
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOG.error("Unable to create interceptor", e);
        return null;
    }
}
 
Example #19
Source File: HttpClientApiCallAttemptTimeoutTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulResponse_SlowBeforeTransmissionExecutionInterceptor_ThrowsApiCallTimeoutException() {
    stubFor(get(anyUrl())
                .willReturn(aResponse().withStatus(200).withBody("{}")));
    ExecutionInterceptor interceptor =
        new SlowExecutionInterceptor().beforeTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT);

    assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor))
                                             .execute(noOpSyncResponseHandler()))
        .isInstanceOf(ApiCallAttemptTimeoutException.class);
}
 
Example #20
Source File: ExceptionReportingUtilsTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public RequestExecutionContext context(ExecutionInterceptor... executionInterceptors) {
    List<ExecutionInterceptor> interceptors = Arrays.asList(executionInterceptors);
    ExecutionInterceptorChain executionInterceptorChain = new ExecutionInterceptorChain(interceptors);
    return RequestExecutionContext.builder()
                                  .executionContext(ExecutionContext.builder()
                                                                    .signer(new NoOpSigner())
                                                                    .executionAttributes(new ExecutionAttributes())
                                                                    .interceptorContext(InterceptorContext.builder()
                                                                                                          .request(ValidSdkObjects.sdkRequest())
                                                                                                          .build())
                                                                    .interceptorChain(executionInterceptorChain)
                                                                    .build())
                                  .originalRequest(ValidSdkObjects.sdkRequest())
                                  .build();
}
 
Example #21
Source File: HttpClientApiCallAttemptTimeoutTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulResponse_SlowAfterResponseExecutionInterceptor_ThrowsApiCallTimeoutException() {
    stubFor(get(anyUrl())
                .willReturn(aResponse().withStatus(200).withBody("{}")));
    ExecutionInterceptor interceptor =
        new SlowExecutionInterceptor().afterTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT);
    assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor))
                                             .execute(noOpSyncResponseHandler()))
        .isInstanceOf(ApiCallAttemptTimeoutException.class);
}
 
Example #22
Source File: HttpClientApiCallTimeoutTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulResponse_SlowBeforeTransmissionExecutionInterceptor_ThrowsApiCallTimeoutException() {
    stubFor(get(anyUrl())
                .willReturn(aResponse().withStatus(200).withBody("{}")));
    ExecutionInterceptor interceptor =
        new SlowExecutionInterceptor().beforeTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT);

    assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor))
                                             .execute(noOpSyncResponseHandler()))
        .isInstanceOf(ApiCallTimeoutException.class);
}
 
Example #23
Source File: HttpClientApiCallTimeoutTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulResponse_SlowAfterResponseExecutionInterceptor_ThrowsApiCallTimeoutException() {
    stubFor(get(anyUrl())
                .willReturn(aResponse().withStatus(200).withBody("{}")));
    ExecutionInterceptor interceptor =
        new SlowExecutionInterceptor().afterTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT);
    assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor))
                                             .execute(noOpSyncResponseHandler()))
        .isInstanceOf(ApiCallTimeoutException.class);
}
 
Example #24
Source File: AsyncHttpClientApiCallTimeoutTests.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void successfulResponse_SlowBeforeRequestRequestHandler_ThrowsApiCallTimeoutException() {
    stubFor(get(anyUrl())
                .willReturn(aResponse().withStatus(200).withBody("{}")));
    ExecutionInterceptor interceptor =
        new SlowExecutionInterceptor().beforeTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT);

    CompletableFuture future = requestBuilder().executionContext(withInterceptors(interceptor))
                                               .execute(noOpResponseHandler());
    assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallTimeoutException.class);
}
 
Example #25
Source File: test-query-client-builder-class.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
protected final SdkClientConfiguration finalizeServiceConfiguration(SdkClientConfiguration config) {
    ClasspathInterceptorChainFactory interceptorFactory = new ClasspathInterceptorChainFactory();
    List<ExecutionInterceptor> interceptors = interceptorFactory
        .getInterceptors("software/amazon/awssdk/services/query/execution.interceptors");
    interceptors = CollectionUtils.mergeLists(interceptors, config.option(SdkClientOption.EXECUTION_INTERCEPTORS));
    List<ExecutionInterceptor> protocolInterceptors = Collections.singletonList(new QueryParametersToBodyInterceptor());
    interceptors = CollectionUtils.mergeLists(interceptors, protocolInterceptors);
    return config.toBuilder().option(SdkClientOption.EXECUTION_INTERCEPTORS, interceptors).build();
}
 
Example #26
Source File: test-client-builder-class.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
protected final SdkClientConfiguration finalizeServiceConfiguration(SdkClientConfiguration config) {
    ClasspathInterceptorChainFactory interceptorFactory = new ClasspathInterceptorChainFactory();
    List<ExecutionInterceptor> interceptors = interceptorFactory
        .getInterceptors("software/amazon/awssdk/services/json/execution.interceptors");
    interceptors = CollectionUtils.mergeLists(interceptors, config.option(SdkClientOption.EXECUTION_INTERCEPTORS));
    ServiceConfiguration.Builder c = ((ServiceConfiguration) config.option(SdkClientOption.SERVICE_CONFIGURATION))
        .toBuilder();
    c.profileFile(c.profileFile() != null ? c.profileFile() : config.option(SdkClientOption.PROFILE_FILE)).profileName(
        c.profileName() != null ? c.profileName() : config.option(SdkClientOption.PROFILE_NAME));
    return config.toBuilder().option(SdkClientOption.EXECUTION_INTERCEPTORS, interceptors)
                 .option(SdkClientOption.RETRY_POLICY, MyServiceRetryPolicy.resolveRetryPolicy(config))
                 .option(SdkClientOption.SERVICE_CONFIGURATION, c.build()).build();
}
 
Example #27
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private void expectServiceCallErrorMethodsCalled(ExecutionInterceptor interceptor, boolean isAsync) {
    ArgumentCaptor<ExecutionAttributes> attributes = ArgumentCaptor.forClass(ExecutionAttributes.class);
    ArgumentCaptor<Context.BeforeUnmarshalling> beforeUnmarshallingArg = ArgumentCaptor.forClass(Context.BeforeUnmarshalling.class);
    ArgumentCaptor<Context.FailedExecution> failedExecutionArg = ArgumentCaptor.forClass(Context.FailedExecution.class);

    InOrder inOrder = Mockito.inOrder(interceptor);
    inOrder.verify(interceptor).beforeExecution(any(), attributes.capture());
    inOrder.verify(interceptor).modifyRequest(any(), attributes.capture());
    inOrder.verify(interceptor).beforeMarshalling(any(), attributes.capture());
    inOrder.verify(interceptor).afterMarshalling(any(), attributes.capture());
    inOrder.verify(interceptor).modifyAsyncHttpContent(any(), attributes.capture());
    inOrder.verify(interceptor).modifyHttpContent(any(), attributes.capture());
    inOrder.verify(interceptor).modifyHttpRequest(any(), attributes.capture());
    inOrder.verify(interceptor).beforeTransmission(any(), attributes.capture());
    inOrder.verify(interceptor).afterTransmission(any(), attributes.capture());
    inOrder.verify(interceptor).modifyHttpResponse(any(), attributes.capture());
    inOrder.verify(interceptor).modifyHttpResponseContent(any(), attributes.capture());
    inOrder.verify(interceptor).beforeUnmarshalling(beforeUnmarshallingArg.capture(), attributes.capture());
    if (isAsync) {
        inOrder.verify(interceptor).modifyAsyncHttpResponseContent(any(), attributes.capture());
    }
    inOrder.verify(interceptor).modifyException(failedExecutionArg.capture(), attributes.capture());
    inOrder.verify(interceptor).onExecutionFailure(failedExecutionArg.capture(), attributes.capture());
    verifyNoMoreInteractions(interceptor);

    // Verify same execution attributes were used for all method calls
    assertThat(attributes.getAllValues()).containsOnly(attributes.getAllValues().get(0));

    // Verify HTTP response
    assertThat(beforeUnmarshallingArg.getValue().httpResponse().statusCode()).isEqualTo(404);

    // Verify failed execution parameters
    assertThat(failedExecutionArg.getValue().exception()).isInstanceOf(SdkServiceException.class);
    verifyFailedExecutionMethodCalled(failedExecutionArg, false);
}
 
Example #28
Source File: Route53InterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private SdkResponse modifyResponse(ExecutionInterceptor interceptor, SdkResponse responseObject) {
    return interceptor.modifyResponse(InterceptorContext.builder()
                                                        .request(CreateHostedZoneRequest.builder().build())
                                                        .response(responseObject)
                                                        .build(),
                                      new ExecutionAttributes());
}
 
Example #29
Source File: EndpointDiscoveryTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10_000)
public void canBeEnabledViaProfileOnOverrideConfiguration() throws InterruptedException {
    ExecutionInterceptor interceptor = Mockito.spy(AbstractExecutionInterceptor.class);

    String profileFileContent =
        "[default]\n" +
        "aws_endpoint_discovery_enabled = true";

    ProfileFile profileFile = ProfileFile.builder()
                                         .type(ProfileFile.Type.CONFIGURATION)
                                         .content(new StringInputStream(profileFileContent))
                                         .build();

    DynamoDbClient dynamoDb = DynamoDbClient.builder()
                                            .region(Region.US_WEST_2)
                                            .credentialsProvider(AnonymousCredentialsProvider.create())
                                            .overrideConfiguration(c -> c.defaultProfileFile(profileFile)
                                                                         .defaultProfileName("default")
                                                                         .addExecutionInterceptor(interceptor)
                                                                         .retryPolicy(r -> r.numRetries(0)))
                                            .build();

    assertThatThrownBy(dynamoDb::listTables).isInstanceOf(SdkException.class);

    ArgumentCaptor<Context.BeforeTransmission> context;

    do {
        Thread.sleep(1);
        context = ArgumentCaptor.forClass(Context.BeforeTransmission.class);
        Mockito.verify(interceptor, atLeastOnce()).beforeTransmission(context.capture(), any());
    } while (context.getAllValues().size() < 2);

    assertThat(context.getAllValues()
                      .stream()
                      .anyMatch(v -> v.httpRequest()
                                      .firstMatchingHeader("X-Amz-Target")
                                      .map(h -> h.equals("DynamoDB_20120810.DescribeEndpoints"))
                                      .orElse(false)))
        .isTrue();
}
 
Example #30
Source File: DefaultS3Presigner.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Copied from {@code DefaultS3BaseClientBuilder} and {@link SdkDefaultClientBuilder}.
 */
private List<ExecutionInterceptor> initializeInterceptors() {
    ClasspathInterceptorChainFactory interceptorFactory = new ClasspathInterceptorChainFactory();
    List<ExecutionInterceptor> s3Interceptors =
        interceptorFactory.getInterceptors("software/amazon/awssdk/services/s3/execution.interceptors");
    return mergeLists(interceptorFactory.getGlobalInterceptors(), s3Interceptors);
}