Java Code Examples for software.amazon.awssdk.core.interceptor.Context#ModifyHttpRequest

The following examples show how to use software.amazon.awssdk.core.interceptor.Context#ModifyHttpRequest . 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: EndpointAddressInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private Context.ModifyHttpRequest context(SdkRequest request, SdkHttpRequest sdkHttpRequest) {
    return new Context.ModifyHttpRequest() {
        @Override
        public SdkHttpRequest httpRequest() {
            return sdkHttpRequest;
        }

        @Override
        public Optional<RequestBody> requestBody() {
            return null;
        }

        @Override
        public Optional<AsyncRequestBody> asyncRequestBody() {
            return null;
        }

        @Override
        public SdkRequest request() {
            return request;
        }
    };
}
 
Example 2
Source File: EndpointAddressInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void verifyEndpoint(String protocol, String expectedEndpoint,
                            S3Configuration.Builder builder) {
    String bucket = "test-bucket";
    String key = "test-key";
    URI customUri = URI.create(String.format("%s://s3-test.com/%s/%s", protocol, bucket, key));
    URI expectedUri = URI.create(String.format("%s/%s/%s", expectedEndpoint, bucket, key));
    Context.ModifyHttpRequest ctx = context(PutObjectRequest.builder().build(), sdkHttpRequest(customUri));
    ExecutionAttributes executionAttributes = new ExecutionAttributes();
    S3Configuration s3Configuration = builder.build();

    executionAttributes.putAttribute(SERVICE_CONFIG, s3Configuration);
    executionAttributes.putAttribute(AWS_REGION, Region.US_EAST_1);

    SdkHttpRequest sdkHttpFullRequest = interceptor.modifyHttpRequest(ctx, executionAttributes);

    assertThat(sdkHttpFullRequest.getUri()).isEqualTo(expectedUri);
}
 
Example 3
Source File: InterceptorTestUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public static Context.ModifyHttpRequest modifyHttpRequestContext(SdkRequest request, SdkHttpRequest sdkHttpRequest) {
    Optional<RequestBody> requestBody = Optional.of(RequestBody.fromString("helloworld"));
    Optional<AsyncRequestBody> asyncRequestBody = Optional.of(AsyncRequestBody.fromString("helloworld"));

    return new Context.ModifyHttpRequest() {
        @Override
        public SdkHttpRequest httpRequest() {
            return sdkHttpRequest;
        }

        @Override
        public Optional<RequestBody> requestBody() {
            return requestBody;
        }

        @Override
        public Optional<AsyncRequestBody> asyncRequestBody() {
            return asyncRequestBody;
        }

        @Override
        public SdkRequest request() {
            return request;
        }
    };
}
 
Example 4
Source File: EndpointAddressInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void verifyVirtualStyleConvertDnsEndpoint(String protocol) {
    String bucketName = "test-bucket";
    String key = "test-key";
    URI customUri = URI.create(String.format("%s://s3-test.com/%s/%s", protocol, bucketName, key));
    URI expectedUri = URI.create(String.format("%s://%s.s3.dualstack.us-east-1.amazonaws.com/%s", protocol,
                                               bucketName, key));

    Context.ModifyHttpRequest ctx = context(ListObjectsV2Request.builder().bucket(bucketName).build(),
                                            sdkHttpRequest(customUri));
    ExecutionAttributes executionAttributes = new ExecutionAttributes();
    S3Configuration s3Configuration = S3Configuration.builder().dualstackEnabled(true).build();

    executionAttributes.putAttribute(SERVICE_CONFIG, s3Configuration);
    executionAttributes.putAttribute(AWS_REGION, Region.US_EAST_1);

    SdkHttpRequest sdkHttpFullRequest = interceptor.modifyHttpRequest(ctx, executionAttributes);

    assertThat(sdkHttpFullRequest.getUri()).isEqualTo(expectedUri);
}
 
Example 5
Source File: EndpointAddressInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
                                        ExecutionAttributes executionAttributes) {
    SdkHttpRequest request = context.httpRequest();

    if (!request.headers().containsKey(X_AMZ_ACCOUNT_ID)) {
        throw SdkClientException.create("Account ID must be specified for all requests");
    }

    String accountId = request.headers().get(X_AMZ_ACCOUNT_ID).get(0);

    S3ControlConfiguration config = (S3ControlConfiguration) executionAttributes.getAttribute(
        AwsSignerExecutionAttribute.SERVICE_CONFIG);

    String host = resolveHost(request, accountId, config);

    return request.toBuilder()
                  .host(host)
                  .build();
}
 
Example 6
Source File: TracingExecutionInterceptor.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
/**
 * Before an individual http request is finalized. This is only called once per operation, meaning
 * we can only have one span per operation.
 */
@Override public SdkHttpRequest modifyHttpRequest(
    Context.ModifyHttpRequest context,
    ExecutionAttributes executionAttributes
) {
  HttpClientRequest request = new HttpClientRequest(context.httpRequest());

  Span span = handler.handleSend(request);
  executionAttributes.putAttribute(SPAN, span);

  String serviceName = executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME);
  String operation = getAwsOperationNameFromRequestClass(context.request());
  // TODO: This overwrites user configuration. We don't do this in other layered tools such
  // as WebMVC. Instead, we add tags (such as we do here) and neither overwrite the name, nor
  // remoteServiceName. Users can always remap in an span handler using tags!
  span.name(operation)
      .remoteServiceName(serviceName)
      .tag("aws.service_name", serviceName)
      .tag("aws.operation", operation);

  return request.build();
}
 
Example 7
Source File: AsyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modifyAsyncHttpContent_putObjectRequest_checksumDisabled_shouldNotModify() {
    ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled();
    Context.ModifyHttpRequest modifyHttpRequest =
        InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build());

    Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest,
                                                                                     executionAttributes);
    assertThat(asyncRequestBody).isEqualTo(modifyHttpRequest.asyncRequestBody());
}
 
Example 8
Source File: EnableTrailingChecksumInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modifyHttpRequest_nonGetObjectRequest_shouldNotModifyHttpRequest() {
    Context.ModifyHttpRequest modifyHttpRequestContext =
        modifyHttpRequestContext(PutObjectRequest.builder().build());

    SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext, new ExecutionAttributes());
    assertThat(sdkHttpRequest).isEqualToComparingFieldByField(modifyHttpRequestContext.httpRequest());
}
 
Example 9
Source File: CreateMultipartUploadRequestInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void nonCreateMultipartRequest_shouldNotModifyHttpContent() {
    Context.ModifyHttpRequest modifyHttpRequest =
        InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build());
    Optional<RequestBody> requestBody =
        interceptor.modifyHttpContent(modifyHttpRequest,
                                      new ExecutionAttributes());
    assertThat(modifyHttpRequest.requestBody().get()).isEqualTo(requestBody.get());
}
 
Example 10
Source File: EnableTrailingChecksumInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Append trailing checksum header for {@link GetObjectRequest} if trailing checksum is enabled from config.
 */
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
                                        ExecutionAttributes executionAttributes) {

    if (getObjectChecksumEnabledPerRequest(context.request(), executionAttributes)) {
        return context.httpRequest().toBuilder().putHeader(ENABLE_CHECKSUM_REQUEST_HEADER,
                                                           ENABLE_MD5_CHECKSUM_HEADER_VALUE)
                      .build();
    }

    return context.httpRequest();
}
 
Example 11
Source File: AsyncChecksumValidationInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
                                                         ExecutionAttributes executionAttributes) {
    boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest());

    if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) {
        SdkChecksum checksum = new Md5Checksum();
        executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true);
        executionAttributes.putAttribute(CHECKSUM, checksum);
        return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum));
    }

    return context.asyncRequestBody();
}
 
Example 12
Source File: EnableTrailingChecksumInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modifyHttpRequest_getObjectTrailingChecksumEnabled_shouldAddTrailingChecksumHeader() {
    Context.ModifyHttpRequest modifyHttpRequestContext =
        modifyHttpRequestContext(GetObjectRequest.builder().build());

    SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext, new ExecutionAttributes());

    assertThat(sdkHttpRequest.headers().get(ENABLE_CHECKSUM_REQUEST_HEADER)).containsOnly(ENABLE_MD5_CHECKSUM_HEADER_VALUE);
}
 
Example 13
Source File: SyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modifyHttpContent_putObjectRequest_checksumDisabled_shouldNotModify() {
    ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled();
    Context.ModifyHttpRequest modifyHttpRequest =
        InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build());

    Optional<RequestBody> requestBody = interceptor.modifyHttpContent(modifyHttpRequest,
                                                                      executionAttributes);
    assertThat(requestBody).isEqualTo(modifyHttpRequest.requestBody());
}
 
Example 14
Source File: PutObjectInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
                                        ExecutionAttributes executionAttributes) {
    if (context.request() instanceof PutObjectRequest) {
        return context.httpRequest().toBuilder().putHeader("Expect", "100-continue").build();
    }
    return context.httpRequest();
}
 
Example 15
Source File: AcceptJsonInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
    return context.httpRequest()
                  .toBuilder()
                  .putHeader("Accept", "application/json")
                  .build();
}
 
Example 16
Source File: SwitchToPostInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
    if (context.request() instanceof SearchRequest) {
        byte[] params = SdkHttpUtils.encodeAndFlattenFormData(context.httpRequest().rawQueryParameters()).orElse("")
                                    .getBytes(StandardCharsets.UTF_8);
        return Optional.of(RequestBody.fromContentProvider(() -> new ByteArrayInputStream(params),
                                                           params.length,
                                                           "application/x-www-form-urlencoded; charset=" +
                                                           lowerCase(StandardCharsets.UTF_8.toString())));
    }

    return context.requestBody();
}
 
Example 17
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
                                            ExecutionAttributes executionAttributes) {
    SdkHttpRequest httpRequest = context.httpRequest();
    return httpRequest.copy(b -> b.putHeader("x-amz-integer", "2"));
}
 
Example 18
Source File: RdsPresignInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public final SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
                                                  ExecutionAttributes executionAttributes) {
    SdkHttpRequest request = context.httpRequest();
    SdkRequest originalRequest = context.request();
    if (!requestClassToPreSign.isInstance(originalRequest)) {
        return request;
    }

    if (request.rawQueryParameters().containsKey(PARAM_PRESIGNED_URL)) {
        return request;
    }

    PresignableRequest presignableRequest = adaptRequest(requestClassToPreSign.cast(originalRequest));

    String sourceRegion = presignableRequest.getSourceRegion();
    if (sourceRegion == null) {
        return request;
    }

    String destinationRegion = executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION).id();

    URI endpoint = createEndpoint(sourceRegion, SERVICE_NAME);
    SdkHttpFullRequest.Builder marshalledRequest = presignableRequest.marshall().toBuilder().uri(endpoint);

    SdkHttpFullRequest requestToPresign =
            marshalledRequest.method(SdkHttpMethod.GET)
                             .putRawQueryParameter(PARAM_DESTINATION_REGION, destinationRegion)
                             .removeQueryParameter(PARAM_SOURCE_REGION)
                             .build();

    requestToPresign = presignRequest(requestToPresign, executionAttributes, sourceRegion);

    String presignedUrl = requestToPresign.getUri().toString();

    return request.toBuilder()
                  .putRawQueryParameter(PARAM_PRESIGNED_URL, presignedUrl)
                  // Remove the unmodeled params to stop them getting onto the wire
                  .removeQueryParameter(PARAM_SOURCE_REGION)
                  .build();
}
 
Example 19
Source File: InterceptorTestUtils.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
public static Context.ModifyHttpRequest modifyHttpRequestContext(SdkRequest request) {
    return modifyHttpRequestContext(request, sdkHttpFullRequest());
}
 
Example 20
Source File: GeneratePreSignUrlInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
    SdkHttpRequest request = context.httpRequest();
    SdkRequest originalRequest = context.request();

    if (originalRequest instanceof CopySnapshotRequest) {

        CopySnapshotRequest originalCopySnapshotRequest = (CopySnapshotRequest) originalRequest;

        // Return if presigned url is already specified by the user.
        if (originalCopySnapshotRequest.presignedUrl() != null) {
            return request;
        }

        String serviceName = "ec2";

        // The source regions where the snapshot currently resides.
        String sourceRegion = originalCopySnapshotRequest.sourceRegion();
        String sourceSnapshotId = originalCopySnapshotRequest
                .sourceSnapshotId();

        /*
         * The region where the snapshot has to be copied from the source.
         * The original copy snap shot request will have the end point set
         * as the destination region in the client before calling this
         * request.
         */
        String destinationRegion = originalCopySnapshotRequest.destinationRegion();

        if (destinationRegion == null) {
            destinationRegion =
                    AwsHostNameUtils.parseSigningRegion(request.host(), serviceName)
                                    .orElseThrow(() -> new IllegalArgumentException("Could not determine region for " +
                                                                                    request.host()))
                                    .id();
        }

        URI endPointSource = createEndpoint(sourceRegion, serviceName);

        SdkHttpFullRequest requestForPresigning = generateRequestForPresigning(
                sourceSnapshotId, sourceRegion, destinationRegion)
                .toBuilder()
                .uri(endPointSource)
                .method(SdkHttpMethod.GET)
                .build();

        Aws4Signer signer = Aws4Signer.create();
        Aws4PresignerParams signingParams = getPresignerParams(executionAttributes, sourceRegion, serviceName);

        SdkHttpFullRequest presignedRequest = signer.presign(requestForPresigning, signingParams);

        return request.toBuilder()
                      .putRawQueryParameter("DestinationRegion", destinationRegion)
                      .putRawQueryParameter("PresignedUrl", presignedRequest.getUri().toString())
                      .build();
    }

    return request;
}