Java Code Examples for software.amazon.awssdk.awscore.exception.AwsServiceException#Builder

The following examples show how to use software.amazon.awssdk.awscore.exception.AwsServiceException#Builder . 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: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void serviceCallWithStabilization() {
    AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(mock(LoggerProxy.class), MOCK,
                                                                          () -> Duration.ofSeconds(1).toMillis() // signal we
                                                                                                                 // have only
                                                                                                                 // 1s left.
    );
    AwsServiceException.Builder builder = mock(AwsServiceException.Builder.class);
    int[] attempt = { 2 };
    Model model = new Model();
    model.setRepoName("NewRepo");
    StdCallbackContext context = new StdCallbackContext();
    ServiceClient client = mock(ServiceClient.class);
    ProxyClient<ServiceClient> svcClient = proxy.newProxy(() -> client);
    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(15)).build())
            .makeServiceCall((r, c) -> c.injectCredentialsAndInvokeV2(r, c.client()::createRepository))
            .stabilize((request, response, client1, model1, context1) -> attempt[0]-- > 0)
            .retryErrorFilter((request, exception, client1, model1, context1) -> exception instanceof ThrottleException)
            .done(ign -> ProgressEvent.success(model, context));

    assertThat(result.getStatus()).isEqualTo(OperationStatus.SUCCESS);
}
 
Example 2
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void throwNotRetryableException() {
    AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(mock(LoggerProxy.class), MOCK,
                                                                          () -> Duration.ofSeconds(1).toMillis() // signal we
                                                                                                                 // have only
                                                                                                                 // 1s left.
    );
    AwsServiceException.Builder builder = mock(AwsServiceException.Builder.class);
    Model model = new Model();
    model.setRepoName("NewRepo");
    StdCallbackContext context = new StdCallbackContext();
    ServiceClient client = mock(ServiceClient.class);
    ProxyClient<ServiceClient> svcClient = proxy.newProxy(() -> client);
    ProgressEvent<Model,
        StdCallbackContext> result = proxy.initiate("client:createRepository", svcClient, model, context)
            .translateToServiceRequest(m -> new CreateRequest.Builder().repoName(m.getRepoName()).build())
            .makeServiceCall((r, g) -> {
                NonRetryableException e = NonRetryableException.builder().build();
                throw e;
            }).success();
    assertThat(result.getStatus()).isEqualTo(OperationStatus.FAILED);

}
 
Example 3
Source File: AmazonWebServicesClientProxyTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void throwOtherException() {
    AmazonWebServicesClientProxy proxy = new AmazonWebServicesClientProxy(mock(LoggerProxy.class), MOCK,
                                                                          () -> Duration.ofSeconds(1).toMillis() // signal we
                                                                                                                 // have only
                                                                                                                 // 1s left.
    );
    AwsServiceException.Builder builder = mock(AwsServiceException.Builder.class);
    Model model = new Model();
    model.setRepoName("NewRepo");
    StdCallbackContext context = new StdCallbackContext();
    ServiceClient client = mock(ServiceClient.class);
    ProxyClient<ServiceClient> svcClient = proxy.newProxy(() -> client);
    assertThrows(ResourceAlreadyExistsException.class,
        () -> proxy.initiate("client:createRepository", svcClient, model, context)
            .translateToServiceRequest(m -> new CreateRequest.Builder().repoName(m.getRepoName()).build())
            .makeServiceCall((r, g) -> {
                throw new ResourceAlreadyExistsException(new RuntimeException("Fail"));
            }).success());
}
 
Example 4
Source File: AwsJsonProtocolErrorUnmarshaller.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private AwsServiceException unmarshall(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) {
    JsonContent jsonContent = JsonContent.createJsonContent(response, jsonFactory);
    String errorCode = errorCodeParser.parseErrorCode(response, jsonContent);

    Optional<ExceptionMetadata> modeledExceptionMetadata = exceptions.stream()
                                                                     .filter(e -> e.errorCode().equals(errorCode))
                                                                     .findAny();

    SdkPojo sdkPojo = modeledExceptionMetadata.map(ExceptionMetadata::exceptionBuilderSupplier)
                                              .orElse(defaultExceptionSupplier)
                                              .get();

    AwsServiceException.Builder exception = ((AwsServiceException) jsonProtocolUnmarshaller
        .unmarshall(sdkPojo, response, jsonContent.getJsonNode())).toBuilder();
    String errorMessage = errorMessageParser.parseErrorMessage(response, jsonContent.getJsonNode());
    exception.awsErrorDetails(extractAwsErrorDetails(response, executionAttributes, jsonContent,
                                                     errorCode, errorMessage));
    exception.clockSkew(getClockSkew(executionAttributes));
    // Status code and request id are sdk level fields
    exception.message(errorMessage);
    exception.statusCode(statusCode(response, modeledExceptionMetadata));
    exception.requestId(getRequestIdFromHeaders(response.headers()));
    exception.extendedRequestId(getExtendedRequestIdFromHeaders(response.headers()));
    return exception.build();
}
 
Example 5
Source File: AwsXmlErrorUnmarshaller.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Unmarshalls the XML into the appropriate modeled exception based on the error code. If the error code
 * is not present or does not match any known exception we unmarshall into the base service exception.
 *
 * @param errorRoot Root of <Error/> element. Contains any modeled fields of the exception.
 * @param errorCode Error code identifying the modeled exception.
 * @return Unmarshalled exception builder.
 */
private AwsServiceException.Builder unmarshallFromErrorCode(SdkHttpFullResponse response,
                                                            XmlElement errorRoot,
                                                            String errorCode) {
    SdkPojo sdkPojo = exceptions.stream()
                                .filter(e -> e.errorCode().equals(errorCode))
                                .map(ExceptionMetadata::exceptionBuilderSupplier)
                                .findAny()
                                .orElse(defaultExceptionSupplier)
                                .get();

    AwsServiceException.Builder builder =
        ((AwsServiceException) errorUnmarshaller.unmarshall(sdkPojo, errorRoot, response)).toBuilder();
    builder.message(getMessage(errorRoot));
    return builder;
}
 
Example 6
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 7
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 8
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 9
Source File: BadRequestException.java    From cloudformation-cli-java-plugin with Apache License 2.0 4 votes vote down vote up
public BadRequestException(AwsServiceException.Builder builder) {
    super(builder);
}
 
Example 10
Source File: AccessDenied.java    From cloudformation-cli-java-plugin with Apache License 2.0 4 votes vote down vote up
public AccessDenied(AwsServiceException.Builder builder) {
    super(builder);
}
 
Example 11
Source File: NotFoundException.java    From cloudformation-cli-java-plugin with Apache License 2.0 4 votes vote down vote up
public NotFoundException(AwsServiceException.Builder builder) {
    super(builder);
    response = Mockito.mock(SdkHttpResponse.class);
    Mockito.when(response.statusCode()).thenReturn(404);
}
 
Example 12
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 13
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 14
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 15
Source File: AwsXmlErrorUnmarshaller.java    From aws-sdk-java-v2 with Apache License 2.0 2 votes vote down vote up
/**
 * @return Builder for the default service exception. Used when the error code doesn't match
 * any known modeled exception or when we can't determine the error code.
 */
private AwsServiceException.Builder defaultException() {
    return (AwsServiceException.Builder) defaultExceptionSupplier.get();
}