software.amazon.awssdk.awscore.exception.AwsErrorDetails Java Examples

The following examples show how to use software.amazon.awssdk.awscore.exception.AwsErrorDetails. 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: AwsJsonExceptionTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void modeledException_HasExceptionMetadataSet() {
    stubFor(post(urlEqualTo(PATH)).willReturn(
        aResponse()
            .withStatus(404)
            .withHeader("x-amzn-RequestId", "1234")
            .withBody("{\"__type\": \"EmptyModeledException\", \"Message\": \"This is the service message\"}")));
    try {
        client.allTypes();
    } catch (EmptyModeledException e) {
        AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
        assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
        assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
        assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolJsonRpc");
        assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
        assertThat(e.requestId()).isEqualTo("1234");
        assertThat(e.extendedRequestId()).isNull();
        assertThat(e.statusCode()).isEqualTo(404);
    }
}
 
Example #2
Source File: SpectatorExecutionInterceptorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void awsThrottling() {
  SdkHttpRequest request = SdkHttpRequest.builder()
      .method(SdkHttpMethod.POST)
      .uri(URI.create("https://ec2.us-east-1.amazonaws.com"))
      .build();
  SdkHttpResponse response = SdkHttpResponse.builder()
      .statusCode(400)
      .build();
  Throwable error = AwsServiceException.builder()
      .awsErrorDetails(AwsErrorDetails.builder()
          .errorCode("Throttling")
          .errorMessage("too many requests")
          .build())
      .build();
  TestContext context = new TestContext(request, response, error);
  execute(context, createAttributes("EC2", "DescribeInstances"), millis(30));
  Assertions.assertEquals(1, registry.timers().count());

  Timer t = registry.timers().findFirst().orElse(null);
  Assertions.assertNotNull(t);
  Assertions.assertEquals(1, t.count());
  Assertions.assertEquals(millis(30), t.totalTime());
  Assertions.assertEquals("400", get(t.id(), "http.status"));
  Assertions.assertEquals("throttled", get(t.id(), "ipc.status"));
}
 
Example #3
Source File: SpectatorExecutionInterceptorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void awsFailure() {
  SdkHttpRequest request = SdkHttpRequest.builder()
      .method(SdkHttpMethod.POST)
      .uri(URI.create("https://ec2.us-east-1.amazonaws.com"))
      .build();
  SdkHttpResponse response = SdkHttpResponse.builder()
      .statusCode(403)
      .build();
  Throwable error = AwsServiceException.builder()
      .awsErrorDetails(AwsErrorDetails.builder()
          .errorCode("AccessDenied")
          .errorMessage("credentials have expired")
          .build())
      .build();
  TestContext context = new TestContext(request, response, error);
  execute(context, createAttributes("EC2", "DescribeInstances"), millis(30));
  Assertions.assertEquals(1, registry.timers().count());

  Timer t = registry.timers().findFirst().orElse(null);
  Assertions.assertNotNull(t);
  Assertions.assertEquals(1, t.count());
  Assertions.assertEquals(millis(30), t.totalTime());
  Assertions.assertEquals("403", get(t.id(), "http.status"));
  Assertions.assertEquals("AccessDenied", get(t.id(), "ipc.status.detail"));
}
 
Example #4
Source File: AwsRetryPolicyTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private Consumer<RetryPolicyContext.Builder> applyErrorCode(String errorCode, Duration clockSkew, Instant dateHeader) {
    SdkHttpFullResponse response = SdkHttpFullResponse.builder()
                                                      .putHeader("Date", DateUtils.formatRfc1123Date(dateHeader))
                                                      .build();

    AwsErrorDetails errorDetails = AwsErrorDetails.builder()
                                                  .errorCode(errorCode)
                                                  .sdkHttpResponse(response)
                                                  .build();

    AwsServiceException.Builder exception = AwsServiceException.builder()
                                                               .statusCode(404)
                                                               .awsErrorDetails(errorDetails)
                                                               .clockSkew(clockSkew);
    return b -> b.exception(exception.build());
}
 
Example #5
Source File: AwsJsonProtocolErrorUnmarshaller.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Build the {@link AwsErrorDetails} from the metadata in the response.
 *
 * @param response HTTP response.
 * @param executionAttributes Execution attributes.
 * @param jsonContent Parsed JSON content.
 * @param errorCode Parsed error code/type.
 * @param errorMessage Parsed error message.
 * @return AwsErrorDetails
 */
private AwsErrorDetails extractAwsErrorDetails(SdkHttpFullResponse response,
                                               ExecutionAttributes executionAttributes,
                                               JsonContent jsonContent,
                                               String errorCode,
                                               String errorMessage) {
    AwsErrorDetails.Builder errorDetails =
        AwsErrorDetails.builder()
                       .errorCode(errorCode)
                       .serviceName(executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME))
                       .sdkHttpResponse(response);

    if (jsonContent.getRawContent() != null) {
        errorDetails.rawResponse(SdkBytes.fromByteArray(jsonContent.getRawContent()));
    }

    errorDetails.errorMessage(errorMessage);
    return errorDetails.build();
}
 
Example #6
Source File: RestJsonExceptionTests.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void modeledException_HasExceptionMetadataIncludingExtendedRequestIdSet() {
    stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
        aResponse()
            .withStatus(404)
            .withHeader("x-amzn-RequestId", "1234")
            .withHeader("x-amz-id-2", "5678")
            .withBody("{\"__type\": \"EmptyModeledException\", \"Message\": \"This is the service message\"}")));
    try {
        client.allTypes();
    } catch (EmptyModeledException e) {
        AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
        assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
        assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
        assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolRestJson");
        assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
        assertThat(e.requestId()).isEqualTo("1234");
        assertThat(e.extendedRequestId()).isEqualTo("5678");
        assertThat(e.statusCode()).isEqualTo(404);
    }
}
 
Example #7
Source File: RestJsonExceptionTests.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void modeledException_HasExceptionMetadataSet() {
    stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
        aResponse()
            .withStatus(404)
            .withHeader("x-amzn-RequestId", "1234")
            .withBody("{\"__type\": \"EmptyModeledException\", \"Message\": \"This is the service message\"}")));
    try {
        client.allTypes();
    } catch (EmptyModeledException e) {
        AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
        assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
        assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
        assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolRestJson");
        assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
        assertThat(e.requestId()).isEqualTo("1234");
        assertThat(e.extendedRequestId()).isNull();
        assertThat(e.statusCode()).isEqualTo(404);
    }
}
 
Example #8
Source File: AwsJsonExceptionTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void modeledException_HasExceptionMetadataIncludingExtendedRequestIdSet() {
    stubFor(post(urlEqualTo(PATH)).willReturn(
        aResponse()
            .withStatus(404)
            .withHeader("x-amzn-RequestId", "1234")
            .withHeader("x-amz-id-2", "5678")
            .withBody("{\"__type\": \"EmptyModeledException\", \"Message\": \"This is the service message\"}")));
    try {
        client.allTypes();
    } catch (EmptyModeledException e) {
        AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
        assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
        assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
        assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolJsonRpc");
        assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
        assertThat(e.requestId()).isEqualTo("1234");
        assertThat(e.extendedRequestId()).isEqualTo("5678");
        assertThat(e.statusCode()).isEqualTo(404);
    }
}
 
Example #9
Source File: RestXmlExceptionTests.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void modeledException_HasExceptionMetadataSet() {
    String xml = "<ErrorResponse>"
                 + "   <Error>"
                 + "      <Code>EmptyModeledException</Code>"
                 + "      <Message>This is the service message</Message>"
                 + "   </Error>"
                 + "   <RequestId>1234</RequestId>"
                 + "</ErrorResponse>";
    stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
        aResponse()
            .withStatus(404)
            .withBody(xml)));
    try {
        client.allTypes();
    } catch (EmptyModeledException e) {
        AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
        assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
        assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
        assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolRestXml");
        assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
        assertThat(e.requestId()).isEqualTo("1234");
        assertThat(e.extendedRequestId()).isNull();
        assertThat(e.statusCode()).isEqualTo(404);
    }
}
 
Example #10
Source File: QueryExceptionTests.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void modeledException_HasExceptionMetadataSet() {
    String xml = "<ErrorResponse>"
                 + "   <Error>"
                 + "      <Code>EmptyModeledException</Code>"
                 + "      <Message>This is the service message</Message>"
                 + "   </Error>"
                 + "   <RequestId>1234</RequestId>"
                 + "</ErrorResponse>";
    stubFor(post(urlEqualTo(PATH)).willReturn(
        aResponse()
            .withStatus(404)
            .withBody(xml)));
    try {
        client.allTypes();
    } catch (EmptyModeledException e) {
        AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
        assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
        assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
        assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolQuery");
        assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
        assertThat(e.requestId()).isEqualTo("1234");
        assertThat(e.extendedRequestId()).isNull();
        assertThat(e.statusCode()).isEqualTo(404);
    }
}
 
Example #11
Source File: ExceptionProperties.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public static List<MethodSpec> builderImplMethods(ClassName className) {
    return Arrays.asList(
            builderImplMethods(className, "awsErrorDetails", AwsErrorDetails.class),
            builderImplMethods(className, "message", String.class),
            builderImplMethods(className, "requestId", String.class),
            builderImplMethods(className, "statusCode", int.class),
            builderImplMethods(className, "cause", Throwable.class));
}
 
Example #12
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void badRequest() {
    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(mock(LoggerProxy.class), MOCK,
                                                                                () -> Duration.ofMinutes(2).toMillis() // just
                                                                                                                       // keep
                                                                                                                       // going

    );
    final Model model = new Model();
    model.setRepoName("NewRepo");
    final StdCallbackContext context = new StdCallbackContext();
    final SdkHttpResponse sdkHttpResponse = mock(SdkHttpResponse.class);
    when(sdkHttpResponse.statusCode()).thenReturn(400);
    final ProgressEvent<Model,
        StdCallbackContext> result = proxy
            .initiate("client:createRespository", proxy.newProxy(() -> mock(ServiceClient.class)), model, context)
            .translateToServiceRequest(m -> new CreateRequest.Builder().repoName(m.getRepoName()).build())
            .makeServiceCall((r, c) -> {
                throw new BadRequestException(mock(AwsServiceException.Builder.class)) {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public AwsErrorDetails awsErrorDetails() {
                        return AwsErrorDetails.builder().errorCode("BadRequest").errorMessage("Bad Parameter in request")
                            .sdkHttpResponse(sdkHttpResponse).build();
                    }
                };
            }).done(o -> ProgressEvent.success(model, context));
    assertThat(result.getStatus()).isEqualTo(OperationStatus.FAILED);
    assertThat(result.getMessage()).contains("BadRequest");
}
 
Example #13
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void notFound() {
    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(mock(LoggerProxy.class), MOCK,
                                                                                () -> Duration.ofMinutes(2).toMillis() // just
                                                                                                                       // keep
                                                                                                                       // going
    );
    final Model model = new Model();
    model.setRepoName("NewRepo");
    StdCallbackContext context = new StdCallbackContext();
    final SdkHttpResponse sdkHttpResponse = mock(SdkHttpResponse.class);
    when(sdkHttpResponse.statusCode()).thenReturn(404);
    ProgressEvent<Model,
        StdCallbackContext> result = proxy
            .initiate("client:createRespository", proxy.newProxy(() -> mock(ServiceClient.class)), model, context)
            .translateToServiceRequest(m -> new CreateRequest.Builder().repoName(m.getRepoName()).build())
            .makeServiceCall((r, c) -> {
                throw new NotFoundException(mock(AwsServiceException.Builder.class)) {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public AwsErrorDetails awsErrorDetails() {
                        return AwsErrorDetails.builder().errorCode("NotFound").errorMessage("Repo not existing")
                            .sdkHttpResponse(sdkHttpResponse).build();
                    }
                };
            }).done(o -> ProgressEvent.success(model, context));
    assertThat(result.getStatus()).isEqualTo(OperationStatus.FAILED);
    assertThat(result.getMessage()).contains("NotFound");
}
 
Example #14
Source File: LocalS3Client.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public ResponseInputStream<GetObjectResponse> getObject(final GetObjectRequest getObjectRequest) throws S3Exception {
    final Map<String, BucketItem> bucketItemMap = bucketsWithContents.get(getObjectRequest.bucket());
    final BucketItem bucketItem = bucketItemMap.get(getObjectRequest.key());
    if (bucketItem != null) {
        try {
            return new ResponseInputStream<>(GetObjectResponse.builder().build(), toAbortableInputStream(bucketItem));
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
            throw SdkClientException.create("", e);
        }
    } else {
        throw NoSuchKeyException.builder().message("NoSuchKey").awsErrorDetails(AwsErrorDetails.builder().errorCode("NoSuchKey").build()).build();
    }
}
 
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 accessDenied() {
    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(mock(LoggerProxy.class), MOCK,
                                                                                () -> Duration.ofMinutes(2).toMillis() // just
                                                                                                                       // keep
                                                                                                                       // going
    );
    final Model model = new Model();
    model.setRepoName("NewRepo");
    final StdCallbackContext context = new StdCallbackContext();
    final SdkHttpResponse sdkHttpResponse = mock(SdkHttpResponse.class);
    when(sdkHttpResponse.statusCode()).thenReturn(401);
    ProgressEvent<Model,
        StdCallbackContext> result = proxy
            .initiate("client:createRespository", proxy.newProxy(() -> mock(ServiceClient.class)), model, context)
            .translateToServiceRequest(m -> new CreateRequest.Builder().repoName(m.getRepoName()).build())
            .makeServiceCall((r, c) -> {
                throw new AccessDenied(AwsServiceException.builder()) {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public AwsErrorDetails awsErrorDetails() {
                        return AwsErrorDetails.builder().errorCode("AccessDenied: 401").errorMessage("Token Invalid")
                            .sdkHttpResponse(sdkHttpResponse).build();
                    }

                };
            }).done(o -> ProgressEvent.success(model, context));
    assertThat(result.getStatus()).isEqualTo(OperationStatus.FAILED);
    assertThat(result.getMessage()).contains("AccessDenied");
}
 
Example #16
Source File: AwsRetryPolicyTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void retriesOnEC2ThrottledException() {
    AwsServiceException ex = AwsServiceException.builder()
                                                .awsErrorDetails(AwsErrorDetails.builder()
                                                                                .errorCode("EC2ThrottledException")
                                                                                .build())
                                                .build();

    assertTrue(shouldRetry(b -> b.exception(ex)));
}
 
Example #17
Source File: AwsXmlErrorUnmarshaller.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Unmarshal an AWS XML exception
 * @param documentRoot The parsed payload document
 * @param errorRoot The specific element of the parsed payload document that contains the error to be marshalled
 *                  or empty if it could not be located.
 * @param documentBytes The raw bytes of the original payload document if they are available
 * @param response The HTTP response object
 * @param executionAttributes {@link ExecutionAttributes} for the current execution
 * @return An {@link AwsServiceException} unmarshalled from the XML.
 */
public AwsServiceException unmarshall(XmlElement documentRoot,
                                      Optional<XmlElement> errorRoot,
                                      Optional<SdkBytes> documentBytes,
                                      SdkHttpFullResponse response,
                                      ExecutionAttributes executionAttributes) {
    String errorCode = getErrorCode(errorRoot);

    AwsServiceException.Builder builder = errorRoot
        .map(e -> invokeSafely(() -> unmarshallFromErrorCode(response, e, errorCode)))
        .orElseGet(this::defaultException);

    AwsErrorDetails awsErrorDetails =
        AwsErrorDetails.builder()
                       .errorCode(errorCode)
                       .errorMessage(builder.message())
                       .rawResponse(documentBytes.orElse(null))
                       .sdkHttpResponse(response)
                       .serviceName(executionAttributes.getAttribute(AwsExecutionAttribute.SERVICE_NAME))
                       .build();

    builder.requestId(getRequestId(response, documentRoot))
           .extendedRequestId(getExtendedRequestId(response))
           .statusCode(response.statusCode())
           .clockSkew(getClockSkew(executionAttributes))
           .awsErrorDetails(awsErrorDetails);

    return builder.build();
}
 
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 throttledExceedRuntimeBailout() {
    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(mock(LoggerProxy.class), MOCK,
                                                                                () -> Duration.ofSeconds(1).toMillis() // signal
                                                                                                                       // we
                                                                                                                       // have
                                                                                                                       // only
                                                                                                                       // 1s
                                                                                                                       // left.
    );
    final AwsServiceException.Builder builder = mock(AwsServiceException.Builder.class);
    final Model model = new Model();
    model.setRepoName("NewRepo");
    final StdCallbackContext context = new StdCallbackContext();
    final ServiceClient client = mock(ServiceClient.class);
    final ProxyClient<ServiceClient> svcClient = proxy.newProxy(() -> client);
    final SdkHttpResponse sdkHttpResponse = mock(SdkHttpResponse.class);
    when(sdkHttpResponse.statusCode()).thenReturn(429);

    final ProgressEvent<Model,
        StdCallbackContext> result = proxy.initiate("client:createRepository", svcClient, model, context)
            .translateToServiceRequest(m -> new CreateRequest.Builder().repoName(m.getRepoName()).build())
            .backoffDelay(Constant.of().delay(Duration.ofSeconds(5)).timeout(Duration.ofSeconds(10)).build())
            .makeServiceCall((r, c) -> {
                throw new ThrottleException(AwsServiceException.builder()) {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public AwsErrorDetails awsErrorDetails() {
                        return AwsErrorDetails.builder().errorCode("ThrottleException")
                            .errorMessage("Temporary Limit Exceeded").sdkHttpResponse(sdkHttpResponse).build();
                    }
                };
            }).done(ign -> ProgressEvent.success(model, context));
    assertThat(result.getStatus()).isEqualTo(OperationStatus.IN_PROGRESS);
    assertThat(result.getCallbackDelaySeconds()).isGreaterThan(0);
}
 
Example #19
Source File: ExceptionProperties.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public static List<MethodSpec> builderInterfaceMethods(ClassName className) {
    return Arrays.asList(
            builderMethod(className, "awsErrorDetails", AwsErrorDetails.class),
            builderMethod(className, "message", String.class),
            builderMethod(className, "requestId", String.class),
            builderMethod(className, "statusCode", int.class),
            builderMethod(className, "cause", Throwable.class));
}
 
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 serviceCallWithFilterException() {
    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(mock(LoggerProxy.class), MOCK,
                                                                                () -> Duration.ofSeconds(1).toMillis() // signal
                                                                                                                       // we
                                                                                                                       // have
                                                                                                                       // only
                                                                                                                       // 1
                                                                                                                       // second
    );
    final Model model = new Model();
    model.setRepoName("NewRepo");
    final StdCallbackContext context = new StdCallbackContext();
    final ServiceClient client = mock(ServiceClient.class);
    final ProxyClient<ServiceClient> svcClient = proxy.newProxy(() -> client);
    final SdkHttpResponse sdkHttpResponse = mock(SdkHttpResponse.class);
    when(sdkHttpResponse.statusCode()).thenReturn(503);
    when(client.createRepository(any(CreateRequest.class))).thenThrow(new ThrottleException(AwsServiceException.builder()) {
        private static final long serialVersionUID = 1L;

        @Override
        public AwsErrorDetails awsErrorDetails() {
            return AwsErrorDetails.builder().errorCode("ThrottleException").errorMessage("Temporary Limit Exceeded")
                .sdkHttpResponse(sdkHttpResponse).build();
        }
    });

    final ProgressEvent<Model,
        StdCallbackContext> result = proxy.initiate("client:createRepository", svcClient, model, context)
            .translateToServiceRequest(m -> new CreateRequest.Builder().repoName(m.getRepoName()).build())
            .backoffDelay(Constant.of().delay(Duration.ofSeconds(5)).timeout(Duration.ofSeconds(10)).build())
            .makeServiceCall((r, c) -> c.injectCredentialsAndInvokeV2(r, c.client()::createRepository))
            .retryErrorFilter((request, response, client1, model1, context1) -> response instanceof ThrottleException)
            .done(ign -> ProgressEvent.success(model, context));

    assertThat(result.getStatus()).isEqualTo(OperationStatus.IN_PROGRESS);

}
 
Example #21
Source File: RestXmlExceptionTests.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void modeledException_HasExceptionMetadataIncludingExtendedRequestIdSet() {
    String xml = "<ErrorResponse>"
                 + "   <Error>"
                 + "      <Code>EmptyModeledException</Code>"
                 + "      <Message>This is the service message</Message>"
                 + "   </Error>"
                 + "   <RequestId>1234</RequestId>"
                 + "</ErrorResponse>";
    stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
        aResponse()
            .withStatus(404)
            .withHeader("x-amz-id-2", "5678")
            .withBody(xml)));
    try {
        client.allTypes();
    } catch (EmptyModeledException e) {
        AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
        assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
        assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
        assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolRestXml");
        assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
        assertThat(e.requestId()).isEqualTo("1234");
        assertThat(e.extendedRequestId()).isEqualTo("5678");
        assertThat(e.statusCode()).isEqualTo(404);
    }
}
 
Example #22
Source File: ExceptionTranslationInterceptorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private S3Exception create404S3Exception() {
    return (S3Exception) S3Exception.builder()
                                    .awsErrorDetails(AwsErrorDetails.builder()
                                                                    .sdkHttpResponse(SdkHttpFullResponse.builder()
                                                                                                        .build())
                                                                    .build())
                                    .statusCode(404)
                                    .build();
}
 
Example #23
Source File: ExceptionTranslationInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private AwsErrorDetails fillErrorDetails(AwsErrorDetails original, String errorCode, String errorMessage) {
    return original.toBuilder().errorMessage(errorMessage).errorCode(errorCode).build();
}
 
Example #24
Source File: NotFoundException.java    From cloudformation-cli-java-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public AwsErrorDetails awsErrorDetails() {
    return AwsErrorDetails.builder().errorCode("NotFound").errorMessage("Repo not existing").sdkHttpResponse(response)
        .build();
}
 
Example #25
Source File: End2EndCallChainTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void happyCase() {
    final AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(mock(LoggerProxy.class), credentials,
                                                                                () -> Duration.ofMinutes(10).getSeconds());

    final Model model = Model.builder().repoName("repo").build();
    StdCallbackContext context = new StdCallbackContext();
    final ServiceClient serviceClient = mock(ServiceClient.class);
    when(serviceClient.createRepository(any(CreateRequest.class)))
        .thenReturn(new CreateResponse.Builder().repoName(model.getRepoName()).build());

    ProxyClient<ServiceClient> client = proxy.newProxy(() -> serviceClient);

    ProgressEvent<Model,
        StdCallbackContext> event = proxy.initiate("client:createRepository", client, model, context)
            .translateToServiceRequest((m) -> new CreateRequest.Builder().repoName(m.getRepoName()).build())
            .makeServiceCall((r, c) -> c.injectCredentialsAndInvokeV2(r, c.client()::createRepository))
            .done(r -> ProgressEvent.success(model, context));

    assertThat(event.getStatus()).isEqualTo(OperationStatus.SUCCESS);

    // replay, should get the same result.
    event = proxy.initiate("client:createRepository", client, model, context)
        .translateToServiceRequest((m) -> new CreateRequest.Builder().repoName(m.getRepoName()).build())
        .makeServiceCall((r, c) -> c.injectCredentialsAndInvokeV2(r, c.client()::createRepository))
        .done(r -> ProgressEvent.success(model, context));
    //
    // Verify that we only got called. During replay we should have been skipped.
    //
    verify(serviceClient).createRepository(any(CreateRequest.class));

    assertThat(event.getStatus()).isEqualTo(OperationStatus.SUCCESS);

    // Now a separate request
    final SdkHttpResponse sdkHttpResponse = mock(SdkHttpResponse.class);
    when(sdkHttpResponse.statusCode()).thenReturn(500);

    //
    // Now reset expectation to fail with already exists
    //
    final ExistsException exists = new ExistsException(mock(AwsServiceException.Builder.class)) {
        private static final long serialVersionUID = 1L;

        @Override
        public AwsErrorDetails awsErrorDetails() {
            return AwsErrorDetails.builder().errorCode("AlreadyExists").errorMessage("Repo already exists")
                .sdkHttpResponse(sdkHttpResponse).build();
        }
    };
    when(serviceClient.createRepository(any(CreateRequest.class))).thenThrow(exists);
    StdCallbackContext newContext = new StdCallbackContext();
    event = proxy.initiate("client:createRepository", client, model, newContext)
        .translateToServiceRequest((m) -> new CreateRequest.Builder().repoName(m.getRepoName()).build())
        .makeServiceCall((r, c) -> c.injectCredentialsAndInvokeV2(r, c.client()::createRepository))
        .done(r -> ProgressEvent.success(model, context));

    assertThat(event.getStatus()).isEqualTo(OperationStatus.FAILED);
    assertThat(event.getMessage()).contains("AlreadyExists");
}
 
Example #26
Source File: AmazonWebServicesClientProxy.java    From cloudformation-cli-java-plugin with Apache License 2.0 4 votes vote down vote up
public <RequestT, ClientT, ModelT, CallbackT extends StdCallbackContext>
    ProgressEvent<ModelT, CallbackT>
    defaultHandler(RequestT request, Exception e, ClientT client, ModelT model, CallbackT context) throws Exception {
    //
    // Client side exception, mapping this to InvalidRequest at the moment
    //
    if (e instanceof NonRetryableException) {
        return ProgressEvent.failed(model, context, HandlerErrorCode.InvalidRequest, e.getMessage());
    }

    if (e instanceof AwsServiceException) {
        AwsServiceException sdkException = (AwsServiceException) e;
        AwsErrorDetails details = sdkException.awsErrorDetails();
        String errMsg = "Exception=[" + sdkException.getClass() + "] " + "ErrorCode=[" + details.errorCode()
            + "],  ErrorMessage=[" + details.errorMessage() + "]";
        switch (details.sdkHttpResponse().statusCode()) {
            case HttpStatusCode.BAD_REQUEST:
                //
                // BadRequest, wrong values in the request
                //
                return ProgressEvent.failed(model, context, HandlerErrorCode.InvalidRequest, errMsg);

            case HttpStatusCode.UNAUTHORIZED:
            case HttpStatusCode.FORBIDDEN:
            case HTTP_STATUS_NETWORK_AUTHN_REQUIRED: // 511 Network Authentication Required, just in case
                //
                // Access Denied, AuthN/Z problems
                //
                return ProgressEvent.failed(model, context, HandlerErrorCode.AccessDenied, errMsg);

            case HttpStatusCode.NOT_FOUND:
            case HTTP_STATUS_GONE: // 410 Gone
                //
                // Resource that we are trying READ/UPDATE/DELETE is not found
                //
                return ProgressEvent.failed(model, context, HandlerErrorCode.NotFound, errMsg);

            case HttpStatusCode.SERVICE_UNAVAILABLE:
                //
                // Often retries help here as well. IMPORTANT to remember here that
                // there are retries with the SDK Client itself for these. Verify
                // what we add extra over the default ones
                //
            case HttpStatusCode.GATEWAY_TIMEOUT:
            case HttpStatusCode.THROTTLING: // Throttle, TOO many requests
                AmazonWebServicesClientProxy.this.loggerProxy.log("Retrying for error " + details.errorMessage());
                throw RetryableException.builder().cause(e).build();

            default:
                return ProgressEvent.failed(model, context, HandlerErrorCode.GeneralServiceException, errMsg);
        }
    }
    return ProgressEvent.failed(model, context, HandlerErrorCode.InternalFailure, e.getMessage());

}
 
Example #27
Source File: AwsRetryPolicyTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private Consumer<RetryPolicyContext.Builder> applyErrorCode(String errorCode) {
    AwsServiceException.Builder exception = AwsServiceException.builder().statusCode(404);
    exception.awsErrorDetails(AwsErrorDetails.builder().errorCode(errorCode).build());
    return b -> b.exception(exception.build());
}
 
Example #28
Source File: AwsRetryPolicyTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private Consumer<RetryPolicyContext.Builder> applyStatusCode(Integer statusCode) {
    AwsServiceException.Builder exception = AwsServiceException.builder().statusCode(statusCode);
    exception.awsErrorDetails(AwsErrorDetails.builder().errorCode("Foo").build());
    return b -> b.exception(exception.build())
                 .httpStatusCode(statusCode);
}
 
Example #29
Source File: RetryOnErrorCodeConditionTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private Consumer<RetryPolicyContext.Builder> applyErrorCode(String errorCode) {
    AwsServiceException.Builder exception = AwsServiceException.builder();
    exception.statusCode(404);
    exception.awsErrorDetails(AwsErrorDetails.builder().errorCode(errorCode).build());
    return b -> b.exception(exception.build());
}
 
Example #30
Source File: End2EndCallChainTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 4 votes vote down vote up
@Order(20)
@Test
public void createHandlerAlreadyExists() throws Exception {
    final HandlerRequest<Model, StdCallbackContext> request = prepareRequest();
    final Serializer serializer = new Serializer();
    final InputStream stream = prepareStream(serializer, request);
    final ByteArrayOutputStream output = new ByteArrayOutputStream(2048);
    final CredentialsProvider providerLoggingCredentialsProvider = prepareMockProvider();
    final Context cxt = mock(Context.class);
    // bail out immediately
    when(cxt.getRemainingTimeInMillis()).thenReturn((int) Duration.ofMinutes(1).toMillis());
    when(cxt.getLogger()).thenReturn(mock(LambdaLogger.class));

    final Model model = request.getRequestData().getResourceProperties();
    final ServiceClient client = mock(ServiceClient.class);
    final CreateRequest createRequest = new CreateRequest.Builder().repoName(model.getRepoName()).overrideConfiguration(
        AwsRequestOverrideConfiguration.builder().credentialsProvider(StaticCredentialsProvider.create(MockCreds)).build())
        .build();
    // Now a separate request
    final SdkHttpResponse sdkHttpResponse = mock(SdkHttpResponse.class);
    when(sdkHttpResponse.statusCode()).thenReturn(500);

    final ExistsException exists = new ExistsException(mock(AwsServiceException.Builder.class)) {
        private static final long serialVersionUID = 1L;

        @Override
        public AwsErrorDetails awsErrorDetails() {
            return AwsErrorDetails.builder().errorCode("AlreadyExists").errorMessage("Repo already exists")
                .sdkHttpResponse(sdkHttpResponse).build();
        }
    };
    when(client.createRepository(eq(createRequest))).thenThrow(exists);

    final SdkHttpClient httpClient = mock(SdkHttpClient.class);
    final ServiceHandlerWrapper wrapper = new ServiceHandlerWrapper(providerLoggingCredentialsProvider,
                                                                    mock(CloudWatchLogPublisher.class),
                                                                    mock(LogPublisher.class), mock(MetricsPublisher.class),
                                                                    new Validator(), serializer, client, httpClient);

    wrapper.handleRequest(stream, output, cxt);
    verify(client).createRepository(eq(createRequest));

    ProgressEvent<Model, StdCallbackContext> response = serializer.deserialize(output.toString(StandardCharsets.UTF_8.name()),
        new TypeReference<ProgressEvent<Model, StdCallbackContext>>() {
        });
    assertThat(response).isNotNull();
    assertThat(response.getStatus()).isEqualTo(OperationStatus.FAILED);
    assertThat(request.getRequestData()).isNotNull();
    Model responseModel = response.getResourceModel();
    assertThat(responseModel.getRepoName()).isEqualTo("repository");
    assertThat(response.getMessage()).contains("AlreadyExists");
}