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

The following examples show how to use software.amazon.awssdk.core.interceptor.Context. 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: SyncChecksumValidationInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context,
                                                       ExecutionAttributes executionAttributes) {
    if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse())
        && context.responseBody().isPresent()) {

        SdkChecksum checksum = new Md5Checksum();

        long contentLength = context.httpResponse()
                                    .firstMatchingHeader(CONTENT_LENGTH_HEADER)
                                    .map(Long::parseLong)
                                    .orElse(0L);

        if (contentLength > 0) {
            return Optional.of(new ChecksumValidatingInputStream(context.responseBody().get(), checksum, contentLength));
        }
    }

    return context.responseBody();
}
 
Example #2
Source File: SyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void afterUnmarshalling_putObjectRequest_with_SSE_shouldNotValidateChecksum() {
    SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();

    PutObjectResponse response = PutObjectResponse.builder()
                                                  .eTag(INVALID_CHECKSUM)
                                                  .build();

    PutObjectRequest putObjectRequest = PutObjectRequest.builder().build();

    SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder()
                                                      .putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString())
                                                      .putHeader("x-amz-server-side-encryption-aws-kms-key-id", ENABLE_MD5_CHECKSUM_HEADER_VALUE)
                                                      .uri(URI.create("http://localhost:8080"))
                                                      .method(SdkHttpMethod.PUT)
                                                      .build();

    Context.AfterUnmarshalling afterUnmarshallingContext =
        InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse);

    interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum());
}
 
Example #3
Source File: TracingInterceptor.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) {
    AWSXRayRecorder recorder = getRecorder();
    Entity origin = recorder.getTraceEntity();

    Subsegment subsegment = recorder.beginSubsegment(executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME));
    if (subsegment == null) {
        return;
    }
    subsegment.setNamespace(Namespace.AWS.toString());
    subsegment.putAws(EntityDataKeys.AWS.OPERATION_KEY,
                      executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME));
    Region region = executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION);
    if (region != null) {
        subsegment.putAws(EntityDataKeys.AWS.REGION_KEY, region.id());
    }
    subsegment.putAllAws(extractRequestParameters(context, executionAttributes));
    if (accountId != null) {
        subsegment.putAws(EntityDataKeys.AWS.ACCOUNT_ID_SUBSEGMENT_KEY, accountId);
    }

    recorder.setTraceEntity(origin);
    // store the subsegment in the AWS SDK's executionAttributes so it can be accessed across threads
    executionAttributes.putAttribute(entityKey, subsegment);
}
 
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: TracingInterceptor.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
    SdkHttpRequest httpRequest = context.httpRequest();

    Subsegment subsegment = executionAttributes.getAttribute(entityKey);
    if (subsegment == null) {
        return httpRequest;
    }

    boolean isSampled = subsegment.getParentSegment().isSampled();
    TraceHeader header = new TraceHeader(
            subsegment.getParentSegment().getTraceId(),
            isSampled ? subsegment.getId() : null,
            isSampled ? TraceHeader.SampleDecision.SAMPLED : TraceHeader.SampleDecision.NOT_SAMPLED
    );

    return httpRequest.toBuilder().appendHeader(TraceHeader.HEADER_KEY, header.toString()).build();
}
 
Example #6
Source File: EndpointAddressInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void verifyAccesspointArn(String protocol, String accessPointArn, String expectedEndpoint,
                                  Region expectedSigningRegion,
                                  S3Configuration.Builder builder, Region region) {
    String key = "test-key";

    URI customUri = URI.create(String.format("%s://s3-test.com/%s/%s", protocol, urlEncode(accessPointArn), key));
    URI expectedUri = URI.create(String.format("%s/%s", expectedEndpoint, key));
    PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                                                        .bucket(accessPointArn)
                                                        .key(key)
                                                        .build();
    Context.ModifyHttpRequest ctx = context(putObjectRequest, sdkHttpRequest(customUri));
    ExecutionAttributes executionAttributes = new ExecutionAttributes();
    S3Configuration s3Configuration = builder.build();

    executionAttributes.putAttribute(SERVICE_CONFIG, s3Configuration);
    executionAttributes.putAttribute(AWS_REGION, region);
    executionAttributes.putAttribute(SIGNING_REGION, region);

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

    assertThat(executionAttributes.getAttribute(SIGNING_REGION))
        .isEqualTo(expectedSigningRegion);
    assertThat(sdkHttpFullRequest.getUri()).isEqualTo(expectedUri);
}
 
Example #7
Source File: CreateBucketInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void modifyRequest_UpdatesLocationConstraint_When_NullCreateBucketConfiguration() {
    CreateBucketRequest request = CreateBucketRequest.builder()
                                                     .bucket("test-bucket")
                                                     .build();

    Context.ModifyRequest context = () -> request;

    ExecutionAttributes attributes = new ExecutionAttributes()
            .putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_EAST_2);

    SdkRequest modifiedRequest = new CreateBucketInterceptor().modifyRequest(context, attributes);
    String locationConstraint = ((CreateBucketRequest) modifiedRequest).createBucketConfiguration().locationConstraintAsString();

    assertThat(locationConstraint).isEqualToIgnoringCase("us-east-2");
}
 
Example #8
Source File: QueryParametersToBodyInterceptor.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 httpRequest = context.httpRequest();

    if (!(httpRequest instanceof SdkHttpFullRequest)) {
        return httpRequest;
    }

    SdkHttpFullRequest httpFullRequest = (SdkHttpFullRequest) httpRequest;
    if (shouldPutParamsInBody(httpFullRequest)) {
        return changeQueryParametersToFormData(httpFullRequest);
    }
    return httpFullRequest;
}
 
Example #9
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 #10
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 #11
Source File: HelpfulUnknownHostExceptionInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) {
    if (!hasCause(context.exception(), UnknownHostException.class)) {
        return context.exception();
    }

    StringBuilder error = new StringBuilder();
    error.append("Received an UnknownHostException when attempting to interact with a service. See cause for the "
                 + "exact endpoint that is failing to resolve. ");

    Optional<String> globalRegionErrorDetails = getGlobalRegionErrorDetails(executionAttributes);

    if (globalRegionErrorDetails.isPresent()) {
        error.append(globalRegionErrorDetails.get());
    } else {
        error.append("If this is happening on an endpoint that previously worked, there may be a network connectivity "
                     + "issue or your DNS cache could be storing endpoints for too long.");
    }

    return SdkClientException.builder().message(error.toString()).cause(context.exception()).build();
}
 
Example #12
Source File: AcceptJsonInterceptor.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) {
    // Some APIG operations marshall to the 'Accept' header to specify the
    // format of the document returned by the service, such as GetExport
    // https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-export-api.html.
    // See the same fix in V1:
    // https://github.com/aws/aws-sdk-java/blob/cd2275c07df8656033bfa9baa665354bfb17a6bf/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/internal/AcceptJsonRequestHandler.java#L29
    SdkHttpRequest httpRequest = context.httpRequest();
    if (!httpRequest.headers().containsKey("Accept")) {
        return httpRequest
                .toBuilder()
                .putHeader("Accept", "application/json")
                .build();
    }
    return httpRequest;
}
 
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 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 #14
Source File: AsyncChecksumValidationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() {
    SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();

    PutObjectResponse response = PutObjectResponse.builder()
                                                  .eTag(VALID_CHECKSUM)
                                                  .build();

    PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                                                        .build();

    SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder()
                                                      .uri(URI.create("http://localhost:8080"))
                                                      .method(SdkHttpMethod.PUT)
                                                      .build();

    Context.AfterUnmarshalling afterUnmarshallingContext =
        InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse);

    interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum());
}
 
Example #15
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 #16
Source File: MessageMD5ChecksumInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) {
    SdkResponse response = context.response();
    SdkRequest originalRequest = context.request();
    if (response != null) {
        if (originalRequest instanceof SendMessageRequest) {
            SendMessageRequest sendMessageRequest = (SendMessageRequest) originalRequest;
            SendMessageResponse sendMessageResult = (SendMessageResponse) response;
            sendMessageOperationMd5Check(sendMessageRequest, sendMessageResult);

        } else if (originalRequest instanceof ReceiveMessageRequest) {
            ReceiveMessageResponse receiveMessageResult = (ReceiveMessageResponse) response;
            receiveMessageResultMd5Check(receiveMessageResult);

        } else if (originalRequest instanceof SendMessageBatchRequest) {
            SendMessageBatchRequest sendMessageBatchRequest = (SendMessageBatchRequest) originalRequest;
            SendMessageBatchResponse sendMessageBatchResult = (SendMessageBatchResponse) response;
            sendMessageBatchOperationMd5Check(sendMessageBatchRequest, sendMessageBatchResult);
        }
    }
}
 
Example #17
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 #18
Source File: CreateMultipartUploadRequestInterceptor.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) {
    if (context.request() instanceof CreateMultipartUploadRequest) {
        SdkHttpRequest.Builder builder = context.httpRequest()
                                                .toBuilder()
                                                .putHeader(CONTENT_LENGTH, String.valueOf(0));

        if (!context.httpRequest().firstMatchingHeader(CONTENT_TYPE).isPresent()) {
            builder.putHeader(CONTENT_TYPE, "binary/octet-stream");
        }

        return builder.build();
    }

    return context.httpRequest();
}
 
Example #19
Source File: DecodeUrlEncodedResponseInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public SdkResponse modifyResponse(Context.ModifyResponse context,
                                  ExecutionAttributes executionAttributes) {
    SdkResponse response = context.response();
    if (shouldHandle(response)) {
        if (response instanceof ListObjectsResponse) {
            return modifyListObjectsResponse((ListObjectsResponse) response);
        }

        if (response instanceof ListObjectsV2Response) {
            return modifyListObjectsV2Response((ListObjectsV2Response) response);
        }

        if (response instanceof ListObjectVersionsResponse) {
            return modifyListObjectVersionsResponse((ListObjectVersionsResponse) response);
        }

        if (response instanceof ListMultipartUploadsResponse) {
            return modifyListMultipartUploadsResponse((ListMultipartUploadsResponse) response);
        }
    }
    return response;
}
 
Example #20
Source File: GetBucketPolicyInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context,
                                                       ExecutionAttributes executionAttributes) {
    if (INTERCEPTOR_CONTEXT_PREDICATE.test(context)) {

        String policy = context.responseBody()
                               .map(r -> invokeSafely(() -> IoUtils.toUtf8String(r)))
                               .orElse(null);

        if (policy != null) {
            String xml = XML_ENVELOPE_PREFIX + policy + XML_ENVELOPE_SUFFIX;
            return Optional.of(AbortableInputStream.create(new StringInputStream(xml)));
        }
    }

    return context.responseBody();
}
 
Example #21
Source File: SpectatorExecutionInterceptor.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes attrs) {
  logRetryAttempt(attrs);

  String serviceName = attrs.getAttribute(SdkExecutionAttribute.SERVICE_NAME);
  String opName = attrs.getAttribute(SdkExecutionAttribute.OPERATION_NAME);
  String endpoint = serviceName + "." + opName;

  SdkHttpRequest request = context.httpRequest();

  IpcLogEntry logEntry = logger.createClientEntry()
      .withOwner("aws-sdk-java-v2")
      .withProtocol(IpcProtocol.http_1)
      .withHttpMethod(request.method().name())
      .withUri(request.getUri())
      .withEndpoint(endpoint)
      .withAttempt(extractAttempt(request))
      .withAttemptFinal(false); // Don't know if it is the final attempt

  request.headers().forEach((k, vs) -> vs.forEach(v -> logEntry.addRequestHeader(k, v)));

  attrs.putAttribute(LOG_ENTRY, logEntry.markStart());
}
 
Example #22
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 #23
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void verifyFailedExecutionMethodCalled(ArgumentCaptor<Context.FailedExecution> failedExecutionArg,
                                               boolean expectResponse) {
    MembersInHeadersRequest failedRequest = (MembersInHeadersRequest) failedExecutionArg.getValue().request();

    assertThat(failedRequest.stringMember()).isEqualTo("1");
    assertThat(failedExecutionArg.getValue().httpRequest()).hasValueSatisfying(httpRequest -> {
        assertThat(httpRequest.firstMatchingHeader("x-amz-string")).hasValue("1");
        assertThat(httpRequest.firstMatchingHeader("x-amz-integer")).hasValue("2");
    });
    assertThat(failedExecutionArg.getValue().httpResponse()).hasValueSatisfying(httpResponse -> {
        assertThat(httpResponse.firstMatchingHeader("x-amz-integer")).hasValue("3");
    });

    if (expectResponse) {
        assertThat(failedExecutionArg.getValue().response().map(MembersInHeadersResponse.class::cast)).hasValueSatisfying(response -> {
            assertThat(response.integerMember()).isEqualTo(3);
            assertThat(response.stringMember()).isEqualTo("4");
        });
    } else {
        assertThat(failedExecutionArg.getValue().response()).isNotPresent();
    }
}
 
Example #24
Source File: EnableChunkedEncodingInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) {
    SdkRequest sdkRequest = context.request();

    if (sdkRequest instanceof PutObjectRequest || sdkRequest instanceof UploadPartRequest) {
        S3Configuration serviceConfiguration =
                (S3Configuration) executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG);

        boolean enableChunkedEncoding;
        if (serviceConfiguration != null) {
            enableChunkedEncoding = serviceConfiguration.chunkedEncodingEnabled();
        } else {
            enableChunkedEncoding = true;
        }

        executionAttributes.putAttributeIfAbsent(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, enableChunkedEncoding);
    }

    return sdkRequest;
}
 
Example #25
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) {
    ConfiguredS3SdkHttpRequest configuredRequest =
        S3EndpointUtils.applyEndpointConfiguration(
                context.httpRequest(),
                context.request(),
                executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION),
                (S3Configuration) executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG),
                Boolean.TRUE.equals(executionAttributes.getAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN)));

    configuredRequest.signingRegionModification().ifPresent(
        region -> executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, region));

    return configuredRequest.sdkHttpRequest();
}
 
Example #26
Source File: ExecutionInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) {
    MembersInHeadersResponse response = (MembersInHeadersResponse) context.response();
    return response.toBuilder()
            .stringMember("4")
            .build();
}
 
Example #27
Source File: AddContentMd5HeaderInterceptor.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) {
    String contentMd5 = executionAttributes.getAttribute(CONTENT_MD5_ATTRIBUTE);

    if (contentMd5 != null) {
        return context.httpRequest().toBuilder().putHeader(CONTENT_MD5, contentMd5).build();
    }

    return context.httpRequest();
}
 
Example #28
Source File: SpectatorExecutionInterceptorTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
Context.FailedExecution failureContext() {
  return new Context.FailedExecution() {
    @Override
    public Throwable exception() {
      return error;
    }

    @Override
    public SdkRequest request() {
      return null;
    }

    @Override
    public Optional<SdkHttpRequest> httpRequest() {
      return Optional.ofNullable(request);
    }

    @Override
    public Optional<SdkHttpResponse> httpResponse() {
      return Optional.ofNullable(response);
    }

    @Override
    public Optional<SdkResponse> response() {
      return Optional.empty();
    }
  };
}
 
Example #29
Source File: ExceptionTranslationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void headBucket404_shouldTranslateException() {
    S3Exception s3Exception = create404S3Exception();
    Context.FailedExecution failedExecution = getFailedExecution(s3Exception,
                                                                 HeadBucketRequest.builder().build());

    assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes()))
        .isExactlyInstanceOf(NoSuchBucketException.class);
}
 
Example #30
Source File: EnableTrailingChecksumInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modifyHttpRequest_getObjectTrailingChecksumDisabled_shouldNotModifyHttpRequest() {
    Context.ModifyHttpRequest modifyHttpRequestContext =
        modifyHttpRequestContext(GetObjectRequest.builder().build());

    SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext,
                                                                  new ExecutionAttributes().putAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG,
                                                                                                         S3Configuration.builder().checksumValidationEnabled(false).build()));

    assertThat(sdkHttpRequest).isEqualToComparingFieldByField(modifyHttpRequestContext.httpRequest());
}