software.amazon.awssdk.core.exception.RetryableException Java Examples

The following examples show how to use software.amazon.awssdk.core.exception.RetryableException. 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: AsyncClientHandlerTransformerVerificationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void prepareCallsEqualToExecuteAttempts() {
    mockSuccessfulResponse();
    AtomicLong prepareCalls = new AtomicLong(0);
    executeAndWaitError(new TestTransformer<SdkResponse, Void>() {
        @Override
        public CompletableFuture<Void> prepare() {
            prepareCalls.incrementAndGet();
            return super.prepare();
        }

        @Override
        public void onStream(SdkPublisher<ByteBuffer> stream) {
            stream.subscribe(new DrainingSubscriber<ByteBuffer>() {
                @Override
                public void onComplete() {
                    transformFuture().completeExceptionally(RetryableException.builder().message("retry me please: " + prepareCalls.get()).build());
                }
            });
        }
    });
    assertThat(prepareCalls.get()).isEqualTo(1 + RETRY_POLICY.numRetries());
}
 
Example #2
Source File: GetObjectFaultIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void handlerThrowsRetryableException_RetriedUpToLimit() throws Exception {
    RequestCountingResponseTransformer<GetObjectResponse, ?> handler = new RequestCountingResponseTransformer<>(
        (resp, in) -> {
            throw RetryableException.builder().build();
        });
    assertThatThrownBy(() -> s3.getObject(getObjectRequest(), handler))
        .isInstanceOf(SdkClientException.class);
    assertThat(handler.currentCallCount()).isEqualTo(4);
}
 
Example #3
Source File: ResponseTransformer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a response transformer that writes all response content to the specified file. If the file already exists
 * then a {@link java.nio.file.FileAlreadyExistsException} will be thrown.
 *
 * @param path        Path to file to write to.
 * @param <ResponseT> Type of unmarshalled response POJO.
 * @return ResponseTransformer instance.
 */
static <ResponseT> ResponseTransformer<ResponseT, ResponseT> toFile(Path path) {
    return (resp, in) -> {
        try {
            InterruptMonitor.checkInterrupted();
            Files.copy(in, path);
            return resp;
        } catch (IOException copyException) {
            String copyError = "Failed to read response into file: " + path;

            // If the write failed because of the state of the file, don't retry the request.
            if (copyException instanceof FileAlreadyExistsException || copyException instanceof DirectoryNotEmptyException) {
                throw new IOException(copyError, copyException);
            }

            // Try to clean up the file so that we can retry the request. If we can't delete it, don't retry the request.
            try {
                Files.deleteIfExists(path);
            } catch (IOException deletionException) {
                Logger.loggerFor(ResponseTransformer.class)
                      .error(() -> "Failed to delete destination file '" + path +
                                   "' after reading the service response " +
                                   "failed.", deletionException);

                throw new IOException(copyError + ". Additionally, the file could not be cleaned up (" +
                                      deletionException.getMessage() + "), so the request will not be retried.",
                                      copyException);
            }

            // Retry the request
            throw RetryableException.builder().message(copyError).cause(copyException).build();
        }
    };
}
 
Example #4
Source File: ResponseTransformer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a response transformer that loads all response content into memory, exposed as {@link ResponseBytes}. This allows
 * for conversion into a {@link String}, {@link ByteBuffer}, etc.
 *
 * @param <ResponseT> Type of unmarshalled response POJO.
 * @return The streaming response transformer that can be used on the client streaming method.
 */
static <ResponseT> ResponseTransformer<ResponseT, ResponseBytes<ResponseT>> toBytes() {
    return (response, inputStream) -> {
        try {
            InterruptMonitor.checkInterrupted();
            return ResponseBytes.fromByteArray(response, IoUtils.toByteArray(inputStream));
        } catch (IOException e) {
            throw RetryableException.builder().message("Failed to read response.").cause(e).build();
        }
    };
}
 
Example #5
Source File: SyncClientHandlerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void responseTransformerThrowsRetryableException_shouldPropogate() throws Exception {
    mockSuccessfulApiCall();
    when(responseTransformer.transform(any(SdkResponse.class), any(AbortableInputStream.class))).thenThrow(
        RetryableException.create("test"));

    assertThatThrownBy(() -> syncClientHandler.execute(clientExecutionParams(), responseTransformer))
        .isInstanceOf(RetryableException.class);
}
 
Example #6
Source File: S3AsyncByteReaderUsingSyncClient.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
<T> T invoke(Callable<T> operation) throws Exception {
  int retryCount = 0;
  while (true) {
    try {
      return operation.call();
    } catch (SdkBaseException | IOException | RetryableException e) {
      if (retryCount >= maxRetries) {
        throw e;
      }

      logger.warn("Retrying S3Async operation, exception was: {}", e.getLocalizedMessage());
      ++retryCount;
    }
  }
}
 
Example #7
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 #8
Source File: DefaultRetryConditionTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Test
public void retriesOnRetryableException() {
    assertTrue(shouldRetry(b -> b.exception(RetryableException.builder().message("this is retryable").build())));
}
 
Example #9
Source File: AwsRetryPolicyTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Test
public void retriesOnRetryableException() {
    assertTrue(shouldRetry(b -> b.exception(RetryableException.builder().build())));
}