software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration Java Examples

The following examples show how to use software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration. 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: AmazonWebServicesClientProxy.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
public <RequestT extends AwsRequest, ResultT extends AwsResponse>
    CompletableFuture<ResultT>
    injectCredentialsAndInvokeV2Async(final RequestT request,
                                      final Function<RequestT, CompletableFuture<ResultT>> requestFunction) {

    AwsRequestOverrideConfiguration overrideConfiguration = AwsRequestOverrideConfiguration.builder()
        .credentialsProvider(v2CredentialsProvider).build();

    @SuppressWarnings("unchecked")
    RequestT wrappedRequest = (RequestT) request.toBuilder().overrideConfiguration(overrideConfiguration).build();

    try {
        CompletableFuture<ResultT> response = requestFunction.apply(wrappedRequest).thenApplyAsync(resultT -> {
            logRequestMetadataV2(request, resultT);
            return resultT;
        });
        return response;
    } catch (final Throwable e) {
        loggerProxy.log(String.format("Failed to execute remote function: {%s}", e.getMessage()));
        throw e;
    }
}
 
Example #2
Source File: DefaultPollyPresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void presign_includesRequestLevelQueryParams_included() {
    PollyPresigner presigner = DefaultPollyPresigner.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(credentialsProvider)
            .build();

    SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder()
            .overrideConfiguration(AwsRequestOverrideConfiguration.builder()
                    .putRawQueryParameter("QueryParam1", "Param1Value")
                    .build())
            .build();

    SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
            .synthesizeSpeechRequest(synthesizeSpeechRequest)
            .signatureDuration(Duration.ofHours(3))
            .build();

    PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest);

    assertThat(presignedSynthesizeSpeechRequest.httpRequest().rawQueryParameters().keySet()).contains("QueryParam1");
}
 
Example #3
Source File: DefaultPollyPresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void presign_includesRequestLevelHeaders_notBrowserCompatible() {
    PollyPresigner presigner = DefaultPollyPresigner.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(credentialsProvider)
            .build();

    SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder()
            .overrideConfiguration(AwsRequestOverrideConfiguration.builder()
                    .putHeader("Header1", "Header1Value")
                    .putHeader("Header2", "Header2Value")
                    .build())
            .build();

    SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
            .synthesizeSpeechRequest(synthesizeSpeechRequest)
            .signatureDuration(Duration.ofHours(3))
            .build();

    PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest);

    assertThat(presignedSynthesizeSpeechRequest.isBrowserExecutable()).isFalse();
}
 
Example #4
Source File: DefaultPollyPresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void presign_requestLevelHeaders_included() {
    PollyPresigner presigner = DefaultPollyPresigner.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(credentialsProvider)
            .build();

    SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder()
            .overrideConfiguration(AwsRequestOverrideConfiguration.builder()
                    .putHeader("Header1", "Header1Value")
                    .putHeader("Header2", "Header2Value")
                    .build())
            .build();

    SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
            .synthesizeSpeechRequest(synthesizeSpeechRequest)
            .signatureDuration(Duration.ofHours(3))
            .build();

    PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest);

    assertThat(presignedSynthesizeSpeechRequest.httpRequest().headers().keySet()).contains("Header1", "Header2");
}
 
Example #5
Source File: DefaultPollyPresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void presign_requestLevelCredentials_honored() {
    AwsCredentials requestCredentials = AwsBasicCredentials.create("akid2", "skid2");

    PollyPresigner presigner = DefaultPollyPresigner.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(credentialsProvider)
            .build();

    SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder()
            .overrideConfiguration(AwsRequestOverrideConfiguration.builder()
                    .credentialsProvider(StaticCredentialsProvider.create(requestCredentials)).build())
            .build();

    SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder()
            .synthesizeSpeechRequest(synthesizeSpeechRequest)
            .signatureDuration(Duration.ofHours(3))
            .build();

    PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest);

    assertThat(presignedSynthesizeSpeechRequest.url().getQuery()).contains("X-Amz-Credential=akid2");
}
 
Example #6
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void getObject_AdditionalHeadersAndQueryStringsCanBeAdded() {
    AwsRequestOverrideConfiguration override =
        AwsRequestOverrideConfiguration.builder()
                                       .putHeader("X-Amz-AdditionalHeader", "foo1")
                                       .putRawQueryParameter("additionalQueryParam", "foo2")
                                       .build();

    PresignedGetObjectRequest presigned =
        presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5))
                                         .getObjectRequest(go -> go.bucket("foo34343434")
                                                                   .key("bar")
                                                                   .overrideConfiguration(override)));

    assertThat(presigned.isBrowserExecutable()).isFalse();
    assertThat(presigned.signedHeaders()).containsOnlyKeys("host", "x-amz-additionalheader");
    assertThat(presigned.signedHeaders().get("x-amz-additionalheader")).containsExactly("foo1");
    assertThat(presigned.httpRequest().headers()).containsKeys("x-amz-additionalheader");
    assertThat(presigned.httpRequest().rawQueryParameters().get("additionalQueryParam").get(0)).isEqualTo("foo2");
}
 
Example #7
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void getObject_Sigv4PresignerHonorsSignatureDuration() {
    AwsRequestOverrideConfiguration override =
        AwsRequestOverrideConfiguration.builder()
                                       .signer(AwsS3V4Signer.create())
                                       .build();

    PresignedGetObjectRequest presigned =
        presigner.presignGetObject(r -> r.signatureDuration(Duration.ofSeconds(1234))
                                         .getObjectRequest(gor -> gor.bucket("a")
                                                                     .key("b")
                                                                     .overrideConfiguration(override)));

    assertThat(presigned.httpRequest().rawQueryParameters().get("X-Amz-Expires").get(0)).satisfies(expires -> {
        assertThat(expires).containsOnlyDigits();
        assertThat(Integer.parseInt(expires)).isCloseTo(1234, Offset.offset(2));
    });
}
 
Example #8
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void putObject_AdditionalHeadersAndQueryStringsCanBeAdded() {
    AwsRequestOverrideConfiguration override =
        AwsRequestOverrideConfiguration.builder()
                                       .putHeader("X-Amz-AdditionalHeader", "foo1")
                                       .putRawQueryParameter("additionalQueryParam", "foo2")
                                       .build();

    PresignedPutObjectRequest presigned =
        presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5))
                                         .putObjectRequest(go -> go.bucket("foo34343434")
                                                                   .key("bar")
                                                                   .overrideConfiguration(override)));

    assertThat(presigned.isBrowserExecutable()).isFalse();
    assertThat(presigned.signedHeaders()).containsOnlyKeys("host", "x-amz-additionalheader");
    assertThat(presigned.signedHeaders().get("x-amz-additionalheader")).containsExactly("foo1");
    assertThat(presigned.httpRequest().headers()).containsKeys("x-amz-additionalheader");
    assertThat(presigned.httpRequest().rawQueryParameters().get("additionalQueryParam").get(0)).isEqualTo("foo2");
}
 
Example #9
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void putObject_Sigv4PresignerHonorsSignatureDuration() {
    AwsRequestOverrideConfiguration override =
        AwsRequestOverrideConfiguration.builder()
                                       .signer(AwsS3V4Signer.create())
                                       .build();

    PresignedPutObjectRequest presigned =
        presigner.presignPutObject(r -> r.signatureDuration(Duration.ofSeconds(1234))
                                         .putObjectRequest(gor -> gor.bucket("a")
                                                                     .key("b")
                                                                     .overrideConfiguration(override)));

    assertThat(presigned.httpRequest().rawQueryParameters().get("X-Amz-Expires").get(0)).satisfies(expires -> {
        assertThat(expires).containsOnlyDigits();
        assertThat(Integer.parseInt(expires)).isCloseTo(1234, Offset.offset(2));
    });
}
 
Example #10
Source File: SqsMessageQueueReceiverEndpoint.java    From synapse with Apache License 2.0 6 votes vote down vote up
public SqsMessageQueueReceiverEndpoint(final @Nonnull String channelName,
                                       final @Nonnull MessageInterceptorRegistry interceptorRegistry,
                                       final @Nonnull SqsAsyncClient sqsAsyncClient,
                                       final @Nonnull ExecutorService executorService,
                                       final @Nullable ApplicationEventPublisher eventPublisher) {
    super(channelName, interceptorRegistry, eventPublisher);
    this.sqsAsyncClient = sqsAsyncClient;
    this.executorService = executorService;
    try {
        this.queueUrl = sqsAsyncClient.getQueueUrl(GetQueueUrlRequest
                .builder()
                .queueName(channelName)
                .overrideConfiguration(AwsRequestOverrideConfiguration.builder()
                        .apiCallAttemptTimeout(ofMillis(2000))
                        .build())
                .build())
                .get()
                .queueUrl();
    } catch (Exception e) {
        stopped.complete(null);
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #11
Source File: AmazonWebServicesClientProxy.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
public <RequestT extends AwsRequest, ResultT extends AwsResponse, IterableT extends SdkIterable<ResultT>>
    IterableT
    injectCredentialsAndInvokeIterableV2(final RequestT request, final Function<RequestT, IterableT> requestFunction) {

    AwsRequestOverrideConfiguration overrideConfiguration = AwsRequestOverrideConfiguration.builder()
        .credentialsProvider(v2CredentialsProvider).build();

    @SuppressWarnings("unchecked")
    RequestT wrappedRequest = (RequestT) request.toBuilder().overrideConfiguration(overrideConfiguration).build();

    try {
        IterableT response = requestFunction.apply(wrappedRequest);
        response.forEach(r -> logRequestMetadataV2(request, r));
        return response;
    } catch (final Throwable e) {
        loggerProxy.log(String.format("Failed to execute remote function: {%s}", e.getMessage()));
        throw e;
    }
}
 
Example #12
Source File: AmazonWebServicesClientProxy.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
public <RequestT extends AwsRequest, ResultT extends AwsResponse>
    ResultT
    injectCredentialsAndInvokeV2(final RequestT request, final Function<RequestT, ResultT> requestFunction) {

    AwsRequestOverrideConfiguration overrideConfiguration = AwsRequestOverrideConfiguration.builder()
        .credentialsProvider(v2CredentialsProvider).build();

    @SuppressWarnings("unchecked")
    RequestT wrappedRequest = (RequestT) request.toBuilder().overrideConfiguration(overrideConfiguration).build();

    try {
        ResultT response = requestFunction.apply(wrappedRequest);
        logRequestMetadataV2(request, response);
        return response;
    } catch (final Throwable e) {
        loggerProxy.log(String.format("Failed to execute remote function: {%s}", e.getMessage()));
        throw e;
    }
}
 
Example #13
Source File: AmazonWebServicesClientProxy.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
public <RequestT extends AwsRequest, ResultT extends AwsResponse>
    ResponseBytes<ResultT>
    injectCredentialsAndInvokeV2Bytes(final RequestT request,
                                      final Function<RequestT, ResponseBytes<ResultT>> requestFunction) {

    AwsRequestOverrideConfiguration overrideConfiguration = AwsRequestOverrideConfiguration.builder()
        .credentialsProvider(v2CredentialsProvider).build();

    @SuppressWarnings("unchecked")
    RequestT wrappedRequest = (RequestT) request.toBuilder().overrideConfiguration(overrideConfiguration).build();

    try {
        ResponseBytes<ResultT> response = requestFunction.apply(wrappedRequest);
        logRequestMetadataV2(request, response.response());
        return response;
    } catch (final Throwable e) {
        loggerProxy.log(String.format("Failed to execute remote function: {%s}", e.getMessage()));
        throw e;
    }
}
 
Example #14
Source File: AmazonWebServicesClientProxy.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
public <RequestT extends AwsRequest, ResultT extends AwsResponse>
    ResponseInputStream<ResultT>
    injectCredentialsAndInvokeV2InputStream(final RequestT request,
                                            final Function<RequestT, ResponseInputStream<ResultT>> requestFunction) {

    AwsRequestOverrideConfiguration overrideConfiguration = AwsRequestOverrideConfiguration.builder()
        .credentialsProvider(v2CredentialsProvider).build();

    @SuppressWarnings("unchecked")
    RequestT wrappedRequest = (RequestT) request.toBuilder().overrideConfiguration(overrideConfiguration).build();

    try {
        ResponseInputStream<ResultT> response = requestFunction.apply(wrappedRequest);
        logRequestMetadataV2(request, response.response());
        return response;
    } catch (final Throwable e) {
        loggerProxy.log(String.format("Failed to execute remote function: {%s}", e.getMessage()));
        throw e;
    }
}
 
Example #15
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testInjectCredentialsAndInvokeV2() {

    final LoggerProxy loggerProxy = mock(LoggerProxy.class);
    final Credentials credentials = new Credentials("accessKeyId", "secretAccessKey", "sessionToken");

    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(loggerProxy, credentials, () -> 1000L);

    final software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest wrappedRequest = mock(
        software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest.class);

    final software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest.Builder builder = mock(
        software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest.Builder.class);
    when(builder.overrideConfiguration(any(AwsRequestOverrideConfiguration.class))).thenReturn(builder);
    when(builder.build()).thenReturn(wrappedRequest);
    final software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest request = mock(
        software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest.class);
    when(request.toBuilder()).thenReturn(builder);

    final DescribeStackEventsResponse expectedResult = DescribeStackEventsResponse.builder()
        .stackEvents(Collections.emptyList()).build();

    final CloudFormationClient client = mock(CloudFormationClient.class);
    when(client
        .describeStackEvents(any(software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest.class)))
            .thenReturn(expectedResult);

    final DescribeStackEventsResponse result = proxy.injectCredentialsAndInvokeV2(request, client::describeStackEvents);

    // verify request is rebuilt for injection
    verify(request).toBuilder();

    // verify the wrapped request is sent over the initiate
    verify(client).describeStackEvents(wrappedRequest);

    // ensure the return type matches
    assertThat(result).isEqualTo(expectedResult);
}
 
Example #16
Source File: test-async-client-class.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private <T extends JsonRequest> T applyPaginatorUserAgent(T request) {
    Consumer<AwsRequestOverrideConfiguration.Builder> userAgentApplier = b -> b.addApiName(ApiName.builder()
            .version(VersionInfo.SDK_VERSION).name("PAGINATED").build());
    AwsRequestOverrideConfiguration overrideConfiguration = request.overrideConfiguration()
            .map(c -> c.toBuilder().applyMutation(userAgentApplier).build())
            .orElse((AwsRequestOverrideConfiguration.builder().applyMutation(userAgentApplier).build()));
    return (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build();
}
 
Example #17
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public <ResultT extends AwsResponse, IterableT extends SdkIterable<ResultT>> void testInjectCredentialsAndInvokeV2Iterable() {

    final LoggerProxy loggerProxy = mock(LoggerProxy.class);
    final Credentials credentials = new Credentials("accessKeyId", "secretAccessKey", "sessionToken");
    final ListObjectsV2Iterable response = mock(ListObjectsV2Iterable.class);

    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(loggerProxy, credentials, () -> 1000L);

    final software.amazon.awssdk.services.s3.model.ListObjectsV2Request wrappedRequest = mock(
        software.amazon.awssdk.services.s3.model.ListObjectsV2Request.class);

    final software.amazon.awssdk.services.s3.model.ListObjectsV2Request.Builder builder = mock(
        software.amazon.awssdk.services.s3.model.ListObjectsV2Request.Builder.class);
    when(builder.overrideConfiguration(any(AwsRequestOverrideConfiguration.class))).thenReturn(builder);
    when(builder.build()).thenReturn(wrappedRequest);
    final software.amazon.awssdk.services.s3.model.ListObjectsV2Request request = mock(
        software.amazon.awssdk.services.s3.model.ListObjectsV2Request.class);
    when(request.toBuilder()).thenReturn(builder);

    final S3Client client = mock(S3Client.class);

    when(client.listObjectsV2Paginator(any(software.amazon.awssdk.services.s3.model.ListObjectsV2Request.class)))
        .thenReturn(response);

    final ListObjectsV2Iterable result = proxy.injectCredentialsAndInvokeIterableV2(request, client::listObjectsV2Paginator);

    // verify request is rebuilt for injection
    verify(request).toBuilder();

    // verify the wrapped request is sent over the initiate
    verify(client).listObjectsV2Paginator(wrappedRequest);

    // ensure the return type matches
    assertThat(result).isEqualTo(response);
}
 
Example #18
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testInjectCredentialsAndInvokeV2InputStream() {

    final LoggerProxy loggerProxy = mock(LoggerProxy.class);
    final Credentials credentials = new Credentials("accessKeyId", "secretAccessKey", "sessionToken");
    final ResponseInputStream<?> responseInputStream = mock(ResponseInputStream.class);

    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(loggerProxy, credentials, () -> 1000L);

    final software.amazon.awssdk.services.s3.model.GetObjectRequest wrappedRequest = mock(
        software.amazon.awssdk.services.s3.model.GetObjectRequest.class);

    final software.amazon.awssdk.services.s3.model.GetObjectRequest.Builder builder = mock(
        software.amazon.awssdk.services.s3.model.GetObjectRequest.Builder.class);
    when(builder.overrideConfiguration(any(AwsRequestOverrideConfiguration.class))).thenReturn(builder);
    when(builder.build()).thenReturn(wrappedRequest);
    final software.amazon.awssdk.services.s3.model.GetObjectRequest request = mock(
        software.amazon.awssdk.services.s3.model.GetObjectRequest.class);
    when(request.toBuilder()).thenReturn(builder);

    final S3Client client = mock(S3Client.class);

    doReturn(responseInputStream).when(client)
        .getObject(any(software.amazon.awssdk.services.s3.model.GetObjectRequest.class));

    final ResponseInputStream<
        GetObjectResponse> result = proxy.injectCredentialsAndInvokeV2InputStream(request, client::getObject);

    // verify request is rebuilt for injection
    verify(request).toBuilder();

    // verify the wrapped request is sent over the initiate
    verify(client).getObject(wrappedRequest);

    // ensure the return type matches
    assertThat(result).isEqualTo(responseInputStream);
}
 
Example #19
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testInjectCredentialsAndInvokeV2InputStream_Exception() {

    final LoggerProxy loggerProxy = mock(LoggerProxy.class);
    final Credentials credentials = new Credentials("accessKeyId", "secretAccessKey", "sessionToken");

    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(loggerProxy, credentials, () -> 1000L);

    final software.amazon.awssdk.services.s3.model.GetObjectRequest wrappedRequest = mock(
        software.amazon.awssdk.services.s3.model.GetObjectRequest.class);

    final software.amazon.awssdk.services.s3.model.GetObjectRequest.Builder builder = mock(
        software.amazon.awssdk.services.s3.model.GetObjectRequest.Builder.class);
    when(builder.overrideConfiguration(any(AwsRequestOverrideConfiguration.class))).thenReturn(builder);
    when(builder.build()).thenReturn(wrappedRequest);
    final software.amazon.awssdk.services.s3.model.GetObjectRequest request = mock(
        software.amazon.awssdk.services.s3.model.GetObjectRequest.class);
    when(request.toBuilder()).thenReturn(builder);

    final S3Client client = mock(S3Client.class);

    doThrow(new TerminalException(new RuntimeException("Sorry"))).when(client)
        .getObject(any(software.amazon.awssdk.services.s3.model.GetObjectRequest.class));

    assertThrows(RuntimeException.class, () -> proxy.injectCredentialsAndInvokeV2InputStream(request, client::getObject),
        "Expected Runtime Exception.");

    // verify request is rebuilt for injection
    verify(request).toBuilder();

    // verify the wrapped request is sent over the initiate
    verify(client).getObject(wrappedRequest);
}
 
Example #20
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testInjectCredentialsAndInvokeV2Bytes() {

    final LoggerProxy loggerProxy = mock(LoggerProxy.class);
    final Credentials credentials = new Credentials("accessKeyId", "secretAccessKey", "sessionToken");
    final ResponseBytes<?> responseBytes = mock(ResponseBytes.class);

    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(loggerProxy, credentials, () -> 1000L);

    final software.amazon.awssdk.services.s3.model.GetObjectRequest wrappedRequest = mock(
        software.amazon.awssdk.services.s3.model.GetObjectRequest.class);

    final software.amazon.awssdk.services.s3.model.GetObjectRequest.Builder builder = mock(
        software.amazon.awssdk.services.s3.model.GetObjectRequest.Builder.class);
    when(builder.overrideConfiguration(any(AwsRequestOverrideConfiguration.class))).thenReturn(builder);
    when(builder.build()).thenReturn(wrappedRequest);
    final software.amazon.awssdk.services.s3.model.GetObjectRequest request = mock(
        software.amazon.awssdk.services.s3.model.GetObjectRequest.class);
    when(request.toBuilder()).thenReturn(builder);

    final S3Client client = mock(S3Client.class);

    doReturn(responseBytes).when(client)
        .getObjectAsBytes(any(software.amazon.awssdk.services.s3.model.GetObjectRequest.class));

    final ResponseBytes<
        GetObjectResponse> result = proxy.injectCredentialsAndInvokeV2Bytes(request, client::getObjectAsBytes);

    // verify request is rebuilt for injection
    verify(request).toBuilder();

    // verify the wrapped request is sent over the initiate
    verify(client).getObjectAsBytes(wrappedRequest);

    // ensure the return type matches
    assertThat(result).isEqualTo(responseBytes);
}
 
Example #21
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testInjectCredentialsAndInvokeV2Async_WithException() {

    final LoggerProxy loggerProxy = mock(LoggerProxy.class);
    final Credentials credentials = new Credentials("accessKeyId", "secretAccessKey", "sessionToken");

    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(loggerProxy, credentials, () -> 1000L);

    final software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest wrappedRequest = mock(
        software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest.class);

    final software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest.Builder builder = mock(
        software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest.Builder.class);
    when(builder.overrideConfiguration(any(AwsRequestOverrideConfiguration.class))).thenReturn(builder);
    when(builder.build()).thenReturn(wrappedRequest);
    final software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest request = mock(
        software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest.class);
    when(request.toBuilder()).thenReturn(builder);

    final CloudFormationAsyncClient client = mock(CloudFormationAsyncClient.class);

    when(client
        .describeStackEvents(any(software.amazon.awssdk.services.cloudformation.model.DescribeStackEventsRequest.class)))
            .thenThrow(new TerminalException(new RuntimeException("Sorry")));
    assertThrows(RuntimeException.class, () -> proxy.injectCredentialsAndInvokeV2Async(request, client::describeStackEvents),
        "Expected Runtime Exception.");

    // verify request is rebuilt for injection
    verify(request).toBuilder();

    // verify the wrapped request is sent over the initiate
    verify(client).describeStackEvents(wrappedRequest);

}
 
Example #22
Source File: KinesisRequestsBuilder.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T extends AwsRequest.Builder> T appendUserAgent(final T builder) {
    return (T) builder
            .overrideConfiguration(
                    AwsRequestOverrideConfiguration.builder()
            .addApiName(ApiName.builder().name(RetrievalConfig.KINESIS_CLIENT_LIB_USER_AGENT)
                    .version(RetrievalConfig.KINESIS_CLIENT_LIB_USER_AGENT_VERSION).build())
            .build());
}
 
Example #23
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void getObject_NonSigV4SignersRaisesException() {
    AwsRequestOverrideConfiguration override =
        AwsRequestOverrideConfiguration.builder()
                                       .signer(new NoOpSigner())
                                       .build();

    assertThatThrownBy(() -> presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5))
                                                              .getObjectRequest(go -> go.bucket("foo34343434")
                                                                                        .key("bar")
                                                                                        .overrideConfiguration(override))))
        .isInstanceOf(IllegalStateException.class)
        .hasMessageContaining("NoOpSigner");
}
 
Example #24
Source File: SqsMessageQueueReceiverEndpointIntegrationTest.java    From synapse with Apache License 2.0 5 votes vote down vote up
private ReceiveMessageRequest buildReceiveMessageRequest() throws InterruptedException, ExecutionException {
    return ReceiveMessageRequest.builder()
            .queueUrl(
                    asyncClient.getQueueUrl(GetQueueUrlRequest
                            .builder()
                            .queueName(SQS_INTEGRATION_TEST_CHANNEL)
                            .overrideConfiguration(AwsRequestOverrideConfiguration.builder()
                                    .build())
                            .build()).get().queueUrl())
            .messageAttributeNames(".*")
            .build();
}
 
Example #25
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void putObject_CredentialsCanBeOverriddenAtTheRequestLevel() {
    AwsCredentials clientCredentials = AwsBasicCredentials.create("a", "a");
    AwsCredentials requestCredentials = AwsBasicCredentials.create("b", "b");

    S3Presigner presigner = presignerBuilder().credentialsProvider(() -> clientCredentials).build();


    AwsRequestOverrideConfiguration overrideConfiguration =
        AwsRequestOverrideConfiguration.builder()
                                       .credentialsProvider(() -> requestCredentials)
                                       .build();

    PresignedPutObjectRequest presignedWithClientCredentials =
        presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5))
                                         .putObjectRequest(go -> go.bucket("foo34343434")
                                                                   .key("bar")));

    PresignedPutObjectRequest presignedWithRequestCredentials =
        presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5))
                                         .putObjectRequest(go -> go.bucket("foo34343434")
                                                                   .key("bar")
                                                                   .overrideConfiguration(overrideConfiguration)));

    System.out.println(presignedWithClientCredentials.url());

    assertThat(presignedWithClientCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0))
        .startsWith("a");
    assertThat(presignedWithRequestCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0))
        .startsWith("b");
}
 
Example #26
Source File: S3PresignerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void putObject_NonSigV4SignersRaisesException() {
    AwsRequestOverrideConfiguration override =
        AwsRequestOverrideConfiguration.builder()
                                       .signer(new NoOpSigner())
                                       .build();

    assertThatThrownBy(() -> presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5))
                                                              .putObjectRequest(go -> go.bucket("foo34343434")
                                                                                        .key("bar")
                                                                                        .overrideConfiguration(override))))
        .isInstanceOf(IllegalStateException.class)
        .hasMessageContaining("NoOpSigner");
}
 
Example #27
Source File: test-json-client-class.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private <T extends JsonRequest> T applyPaginatorUserAgent(T request) {
    Consumer<AwsRequestOverrideConfiguration.Builder> userAgentApplier = b -> b.addApiName(ApiName.builder()
                                                                                                  .version(VersionInfo.SDK_VERSION).name("PAGINATED").build());
    AwsRequestOverrideConfiguration overrideConfiguration = request.overrideConfiguration()
                                                                   .map(c -> c.toBuilder().applyMutation(userAgentApplier).build())
                                                                   .orElse((AwsRequestOverrideConfiguration.builder().applyMutation(userAgentApplier).build()));
    return (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build();
}
 
Example #28
Source File: ModelBuilderSpecs.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public TypeSpec builderInterface() {
    TypeSpec.Builder builder = TypeSpec.interfaceBuilder(builderInterfaceName())
            .addSuperinterfaces(builderSuperInterfaces())
            .addModifiers(Modifier.PUBLIC);

    shapeModel.getNonStreamingMembers()
              .forEach(m -> {
                  builder.addMethods(accessorsFactory.fluentSetterDeclarations(m, builderInterfaceName()));
                  builder.addMethods(accessorsFactory.convenienceSetterDeclarations(m, builderInterfaceName()));
              });

    if (isException()) {
        builder.addSuperinterface(parentExceptionBuilder().nestedClass("Builder"));
        builder.addMethods(ExceptionProperties.builderInterfaceMethods(builderInterfaceName()));
    }

    if (isRequest()) {
        builder.addMethod(MethodSpec.methodBuilder("overrideConfiguration")
                .returns(builderInterfaceName())
                .addAnnotation(Override.class)
                .addParameter(AwsRequestOverrideConfiguration.class, "overrideConfiguration")
                .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                .build());

        builder.addMethod(MethodSpec.methodBuilder("overrideConfiguration")
                .addAnnotation(Override.class)
                .returns(builderInterfaceName())
                .addParameter(ParameterizedTypeName.get(Consumer.class, AwsRequestOverrideConfiguration.Builder.class),
                        "builderConsumer")
                .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                .build());
    }

    return builder.build();
}
 
Example #29
Source File: ClientClassUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
static MethodSpec applyPaginatorUserAgentMethod(PoetExtensions poetExtensions, IntermediateModel model) {

        TypeVariableName typeVariableName =
            TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName()));

        ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName
            .get(ClassName.get(Consumer.class), ClassName.get(AwsRequestOverrideConfiguration.Builder.class));

        CodeBlock codeBlock = CodeBlock.builder()
                                       .addStatement("$T userAgentApplier = b -> b.addApiName($T.builder().version"
                                                     + "($T.SDK_VERSION).name($S).build())",
                                                     parameterizedTypeName, ApiName.class,
                                                     VersionInfo.class,
                                                     PAGINATOR_USER_AGENT)
                                       .addStatement("$T overrideConfiguration =\n"
                                                     + "            request.overrideConfiguration().map(c -> c.toBuilder()"
                                                     + ".applyMutation"
                                                     + "(userAgentApplier).build())\n"
                                                     + "            .orElse((AwsRequestOverrideConfiguration.builder()"
                                                     + ".applyMutation"
                                                     + "(userAgentApplier).build()))", AwsRequestOverrideConfiguration.class)
                                       .addStatement("return (T) request.toBuilder().overrideConfiguration"
                                                     + "(overrideConfiguration).build()")
                                       .build();

        return MethodSpec.methodBuilder("applyPaginatorUserAgent")
                         .addModifiers(Modifier.PRIVATE)
                         .addParameter(typeVariableName, "request")
                         .addTypeVariable(typeVariableName)
                         .addCode(codeBlock)
                         .returns(typeVariableName)
                         .build();
    }
 
Example #30
Source File: ClientClassUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
static MethodSpec applySignerOverrideMethod(PoetExtensions poetExtensions, IntermediateModel model) {
    String signerOverrideVariable = "signerOverride";

    TypeVariableName typeVariableName =
        TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName()));

    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName
        .get(ClassName.get(Consumer.class), ClassName.get(AwsRequestOverrideConfiguration.Builder.class));

    CodeBlock codeBlock = CodeBlock.builder()
                                   .beginControlFlow("if (request.overrideConfiguration().flatMap(c -> c.signer())"
                                                     + ".isPresent())")
                                   .addStatement("return request")
                                   .endControlFlow()
                                   .addStatement("$T $L = b -> b.signer(signer).build()",
                                                 parameterizedTypeName,
                                                 signerOverrideVariable)
                                   .addStatement("$1T overrideConfiguration =\n"
                                                 + "            request.overrideConfiguration().map(c -> c.toBuilder()"
                                                 + ".applyMutation($2L).build())\n"
                                                 + "            .orElse((AwsRequestOverrideConfiguration.builder()"
                                                 + ".applyMutation($2L).build()))",
                                                 AwsRequestOverrideConfiguration.class,
                                                 signerOverrideVariable)
                                   .addStatement("return (T) request.toBuilder().overrideConfiguration"
                                                 + "(overrideConfiguration).build()")
                                   .build();

    return MethodSpec.methodBuilder("applySignerOverride")
                     .addModifiers(Modifier.PRIVATE)
                     .addParameter(typeVariableName, "request")
                     .addParameter(Signer.class, "signer")
                     .addTypeVariable(typeVariableName)
                     .addCode(codeBlock)
                     .returns(typeVariableName)
                     .build();
}