software.amazon.awssdk.awscore.exception.AwsServiceException Java Examples
The following examples show how to use
software.amazon.awssdk.awscore.exception.AwsServiceException.
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: BaseMockApiCall.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
public void failedAsyncApiCall() { logger.info("stubing failed async api call for {} protocol", protocol); mockAyncHttpClient.stubNextResponse(errorResponse(protocol)); try { asyncRunnable().run(); } catch (CompletionException e) { if (e.getCause() instanceof AwsServiceException) { logger.info("expected service exception {}", e.getMessage()); } else { throw new RuntimeException("Unexpected exception is thrown"); } } mockAyncHttpClient.reset(); }
Example #2
Source File: test-json-client-class.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * <p> * Performs a post operation to the query service and has no output * </p> * * @param aPostOperationRequest * @return Result of the APostOperation operation returned by the service. * @throws InvalidInputException * The request was rejected because an invalid or out-of-range value was supplied for an input parameter. * @throws SdkException * Base class for all exceptions that can be thrown by the SDK (both service and client). Can be used for * catch all scenarios. * @throws SdkClientException * If any client side error occurs such as an IO related failure, failure to get credentials, etc. * @throws JsonException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample JsonClient.APostOperation * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/json-service-2010-05-08/APostOperation" target="_top">AWS * API Documentation</a> */ @Override public APostOperationResponse aPostOperation(APostOperationRequest aPostOperationRequest) throws InvalidInputException, AwsServiceException, SdkClientException, JsonException { String hostPrefix = "{StringMember}-foo."; Validate.paramNotBlank(aPostOperationRequest.stringMember(), "StringMember"); String resolvedHostExpression = String.format("%s-foo.", aPostOperationRequest.stringMember()); JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler<APostOperationResponse> responseHandler = protocolFactory.createResponseHandler(operationMetadata, APostOperationResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); return clientHandler.execute(new ClientExecutionParams<APostOperationRequest, APostOperationResponse>() .withOperationName("APostOperation") .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .hostPrefixExpression(resolvedHostExpression).withInput(aPostOperationRequest) .withMarshaller(new APostOperationRequestMarshaller(protocolFactory))); }
Example #3
Source File: test-json-client-class.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * Some paginated operation without result_key in paginators.json file * * @param paginatedOperationWithoutResultKeyRequest * @return Result of the PaginatedOperationWithoutResultKey operation returned by the service. * @throws SdkException * Base class for all exceptions that can be thrown by the SDK (both service and client). Can be used for * catch all scenarios. * @throws SdkClientException * If any client side error occurs such as an IO related failure, failure to get credentials, etc. * @throws JsonException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample JsonClient.PaginatedOperationWithoutResultKey * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/json-service-2010-05-08/PaginatedOperationWithoutResultKey" * target="_top">AWS API Documentation</a> */ @Override public PaginatedOperationWithoutResultKeyResponse paginatedOperationWithoutResultKey( PaginatedOperationWithoutResultKeyRequest paginatedOperationWithoutResultKeyRequest) throws AwsServiceException, SdkClientException, JsonException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler<PaginatedOperationWithoutResultKeyResponse> responseHandler = protocolFactory.createResponseHandler( operationMetadata, PaginatedOperationWithoutResultKeyResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); return clientHandler .execute(new ClientExecutionParams<PaginatedOperationWithoutResultKeyRequest, PaginatedOperationWithoutResultKeyResponse>() .withOperationName("PaginatedOperationWithoutResultKey") .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .withInput(paginatedOperationWithoutResultKeyRequest) .withMarshaller(new PaginatedOperationWithoutResultKeyRequestMarshaller(protocolFactory))); }
Example #4
Source File: SpectatorExecutionInterceptorTest.java From spectator with Apache License 2.0 | 6 votes |
@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 #5
Source File: AwsScanner.java From clouditor with Apache License 2.0 | 6 votes |
<O extends AwsResponse, R extends AwsRequest, S extends ToCopyableBuilder> void enrich( AssetProperties properties, String key, Function<R, O> listFunction, Function<O, S> valueFunction, R builder) { try { var response = listFunction.apply(builder); properties.put( key, MAPPER.convertValue(valueFunction.apply(response).toBuilder(), AssetProperties.class)); } catch (AwsServiceException ex) { // ignore if error is 404, since this just means that the value is empty if (ex.statusCode() != 404) { LOGGER.info( "Got exception from {} while retrieving info for {}: {}", this.getClass(), key, ex.getMessage()); } } }
Example #6
Source File: test-json-client-class.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * <p> * Performs a post operation to the query service and has modelled output * </p> * * @param aPostOperationWithOutputRequest * @return Result of the APostOperationWithOutput operation returned by the service. * @throws InvalidInputException * The request was rejected because an invalid or out-of-range value was supplied for an input parameter. * @throws SdkException * Base class for all exceptions that can be thrown by the SDK (both service and client). Can be used for * catch all scenarios. * @throws SdkClientException * If any client side error occurs such as an IO related failure, failure to get credentials, etc. * @throws JsonException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample JsonClient.APostOperationWithOutput * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/json-service-2010-05-08/APostOperationWithOutput" * target="_top">AWS API Documentation</a> */ @Override public APostOperationWithOutputResponse aPostOperationWithOutput( APostOperationWithOutputRequest aPostOperationWithOutputRequest) throws InvalidInputException, AwsServiceException, SdkClientException, JsonException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler<APostOperationWithOutputResponse> responseHandler = protocolFactory.createResponseHandler( operationMetadata, APostOperationWithOutputResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); return clientHandler .execute(new ClientExecutionParams<APostOperationWithOutputRequest, APostOperationWithOutputResponse>() .withOperationName("APostOperationWithOutput") .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .withInput(aPostOperationWithOutputRequest) .withMarshaller(new APostOperationWithOutputRequestMarshaller(protocolFactory))); }
Example #7
Source File: AmazonWebServicesClientProxyTest.java From cloudformation-cli-java-plugin with Apache License 2.0 | 6 votes |
@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 #8
Source File: SpectatorExecutionInterceptorTest.java From spectator with Apache License 2.0 | 6 votes |
@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 #9
Source File: AmazonWebServicesClientProxyTest.java From cloudformation-cli-java-plugin with Apache License 2.0 | 6 votes |
@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 #10
Source File: test-async-client-class.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * Some paginated operation without result_key in paginators.json file * * @param paginatedOperationWithoutResultKeyRequest * @return A Java Future containing the result of the PaginatedOperationWithoutResultKey operation returned by the * service.<br/> * The CompletableFuture returned by this method can be completed exceptionally with the following * exceptions. * <ul> * <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client). * Can be used for catch all scenarios.</li> * <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get * credentials, etc.</li> * <li>JsonException Base class for all service exceptions. Unknown exceptions will be thrown as an instance * of this type.</li> * </ul> * @sample JsonAsyncClient.PaginatedOperationWithoutResultKey * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/json-service-2010-05-08/PaginatedOperationWithoutResultKey" * target="_top">AWS API Documentation</a> */ @Override public CompletableFuture<PaginatedOperationWithoutResultKeyResponse> paginatedOperationWithoutResultKey( PaginatedOperationWithoutResultKeyRequest paginatedOperationWithoutResultKeyRequest) { try { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler<PaginatedOperationWithoutResultKeyResponse> responseHandler = protocolFactory .createResponseHandler(operationMetadata, PaginatedOperationWithoutResultKeyResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); CompletableFuture<PaginatedOperationWithoutResultKeyResponse> executeFuture = clientHandler .execute(new ClientExecutionParams<PaginatedOperationWithoutResultKeyRequest, PaginatedOperationWithoutResultKeyResponse>() .withOperationName("PaginatedOperationWithoutResultKey") .withMarshaller(new PaginatedOperationWithoutResultKeyRequestMarshaller(protocolFactory)) .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .withInput(paginatedOperationWithoutResultKeyRequest)); return executeFuture; } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } }
Example #11
Source File: test-async-client-class.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * Some paginated operation with result_key in paginators.json file * * @param paginatedOperationWithResultKeyRequest * @return A Java Future containing the result of the PaginatedOperationWithResultKey operation returned by the * service.<br/> * The CompletableFuture returned by this method can be completed exceptionally with the following * exceptions. * <ul> * <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client). * Can be used for catch all scenarios.</li> * <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get * credentials, etc.</li> * <li>JsonException Base class for all service exceptions. Unknown exceptions will be thrown as an instance * of this type.</li> * </ul> * @sample JsonAsyncClient.PaginatedOperationWithResultKey * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/json-service-2010-05-08/PaginatedOperationWithResultKey" * target="_top">AWS API Documentation</a> */ @Override public CompletableFuture<PaginatedOperationWithResultKeyResponse> paginatedOperationWithResultKey( PaginatedOperationWithResultKeyRequest paginatedOperationWithResultKeyRequest) { try { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler<PaginatedOperationWithResultKeyResponse> responseHandler = protocolFactory.createResponseHandler( operationMetadata, PaginatedOperationWithResultKeyResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); CompletableFuture<PaginatedOperationWithResultKeyResponse> executeFuture = clientHandler .execute(new ClientExecutionParams<PaginatedOperationWithResultKeyRequest, PaginatedOperationWithResultKeyResponse>() .withOperationName("PaginatedOperationWithResultKey") .withMarshaller(new PaginatedOperationWithResultKeyRequestMarshaller(protocolFactory)) .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .withInput(paginatedOperationWithResultKeyRequest)); return executeFuture; } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } }
Example #12
Source File: test-async-client-class.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * <p> * Performs a post operation to the query service and has modelled output * </p> * * @param aPostOperationWithOutputRequest * @return A Java Future containing the result of the APostOperationWithOutput operation returned by the service.<br/> * The CompletableFuture returned by this method can be completed exceptionally with the following * exceptions. * <ul> * <li>InvalidInputException The request was rejected because an invalid or out-of-range value was supplied * for an input parameter.</li> * <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client). * Can be used for catch all scenarios.</li> * <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get * credentials, etc.</li> * <li>JsonException Base class for all service exceptions. Unknown exceptions will be thrown as an instance * of this type.</li> * </ul> * @sample JsonAsyncClient.APostOperationWithOutput * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/json-service-2010-05-08/APostOperationWithOutput" * target="_top">AWS API Documentation</a> */ @Override public CompletableFuture<APostOperationWithOutputResponse> aPostOperationWithOutput( APostOperationWithOutputRequest aPostOperationWithOutputRequest) { try { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler<APostOperationWithOutputResponse> responseHandler = protocolFactory.createResponseHandler( operationMetadata, APostOperationWithOutputResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); CompletableFuture<APostOperationWithOutputResponse> executeFuture = clientHandler .execute(new ClientExecutionParams<APostOperationWithOutputRequest, APostOperationWithOutputResponse>() .withOperationName("APostOperationWithOutput") .withMarshaller(new APostOperationWithOutputRequestMarshaller(protocolFactory)) .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .withInput(aPostOperationWithOutputRequest)); return executeFuture; } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } }
Example #13
Source File: AwsJsonProtocolErrorUnmarshaller.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
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 #14
Source File: AmazonWebServicesClientProxyTest.java From cloudformation-cli-java-plugin with Apache License 2.0 | 6 votes |
@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 #15
Source File: test-endpoint-discovery-sync.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * Invokes the DescribeEndpoints operation. * * @param describeEndpointsRequest * @return Result of the DescribeEndpoints operation returned by the service. * @throws SdkException * Base class for all exceptions that can be thrown by the SDK (both service and client). Can be used for * catch all scenarios. * @throws SdkClientException * If any client side error occurs such as an IO related failure, failure to get credentials, etc. * @throws EndpointDiscoveryTestException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample EndpointDiscoveryTestClient.DescribeEndpoints */ @Override public DescribeEndpointsResponse describeEndpoints(DescribeEndpointsRequest describeEndpointsRequest) throws AwsServiceException, SdkClientException, EndpointDiscoveryTestException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler<DescribeEndpointsResponse> responseHandler = protocolFactory.createResponseHandler(operationMetadata, DescribeEndpointsResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); return clientHandler.execute(new ClientExecutionParams<DescribeEndpointsRequest, DescribeEndpointsResponse>() .withOperationName("DescribeEndpoints").withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler).withInput(describeEndpointsRequest) .withMarshaller(new DescribeEndpointsRequestMarshaller(protocolFactory))); }
Example #16
Source File: FirehoseAppender.java From kinesis-logback-appender with Apache License 2.0 | 5 votes |
@Override protected void validateStreamName(FirehoseAsyncClient client, String streamName) { DescribeDeliveryStreamResponse describeResponse; try { describeResponse = getClient() .describeDeliveryStream(b -> b.deliveryStreamName(streamName).build()) .get(); DeliveryStreamStatus streamStatus = describeResponse.deliveryStreamDescription().deliveryStreamStatus(); if(!DeliveryStreamStatus.ACTIVE.equals(streamStatus)) { setInitializationFailed(true); addError("Stream " + streamName + " is not ready (in active status) for appender: " + name); } } catch(InterruptedException ie) { setInitializationFailed(true); addError("Interrupted while attempting to describe " + streamName, ie); } catch(ExecutionException ee) { setInitializationFailed(true); addError("Error executing the operation", ee); } catch(ResourceNotFoundException rnfe) { setInitializationFailed(true); addError("Stream " + streamName + " doesn't exist for appender: " + name, rnfe); } catch(AwsServiceException ase) { setInitializationFailed(true); addError("Error connecting to AWS to verify stream " + streamName + " for appender: " + name, ase); } }
Example #17
Source File: test-async-client-class.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
/** * Some operation with a streaming output * * @param streamingOutputOperationRequest * @param asyncResponseTransformer * The response transformer for processing the streaming response in a non-blocking manner. See * {@link AsyncResponseTransformer} for details on how this callback should be implemented and for links to * precanned implementations for common scenarios like downloading to a file. The service documentation for * the response content is as follows 'This be a stream'. * @return A future to the transformed result of the AsyncResponseTransformer.<br/> * The CompletableFuture returned by this method can be completed exceptionally with the following * exceptions. * <ul> * <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client). * Can be used for catch all scenarios.</li> * <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get * credentials, etc.</li> * <li>JsonException Base class for all service exceptions. Unknown exceptions will be thrown as an instance * of this type.</li> * </ul> * @sample JsonAsyncClient.StreamingOutputOperation * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/json-service-2010-05-08/StreamingOutputOperation" * target="_top">AWS API Documentation</a> */ @Override public <ReturnT> CompletableFuture<ReturnT> streamingOutputOperation( StreamingOutputOperationRequest streamingOutputOperationRequest, AsyncResponseTransformer<StreamingOutputOperationResponse, ReturnT> asyncResponseTransformer) { try { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(true) .isPayloadJson(false).build(); HttpResponseHandler<StreamingOutputOperationResponse> responseHandler = protocolFactory.createResponseHandler( operationMetadata, StreamingOutputOperationResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); CompletableFuture<ReturnT> executeFuture = clientHandler.execute( new ClientExecutionParams<StreamingOutputOperationRequest, StreamingOutputOperationResponse>() .withOperationName("StreamingOutputOperation") .withMarshaller(new StreamingOutputOperationRequestMarshaller(protocolFactory)) .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .withInput(streamingOutputOperationRequest), asyncResponseTransformer); executeFuture.whenComplete((r, e) -> { if (e != null) { runAndLogError(log, "Exception thrown in exceptionOccurred callback, ignoring", () -> asyncResponseTransformer.exceptionOccurred(e)); } }); return executeFuture; } catch (Throwable t) { runAndLogError(log, "Exception thrown in exceptionOccurred callback, ignoring", () -> asyncResponseTransformer.exceptionOccurred(t)); return CompletableFutureUtils.failedFuture(t); } }
Example #18
Source File: JsonProtocolSpec.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Override public Optional<MethodSpec> createErrorResponseHandler() { ClassName httpResponseHandler = ClassName.get(HttpResponseHandler.class); ClassName sdkBaseException = ClassName.get(AwsServiceException.class); TypeName responseHandlerOfException = ParameterizedTypeName.get(httpResponseHandler, sdkBaseException); return Optional.of(MethodSpec.methodBuilder("createErrorResponseHandler") .addParameter(BaseAwsJsonProtocolFactory.class, "protocolFactory") .addParameter(JsonOperationMetadata.class, "operationMetadata") .returns(responseHandlerOfException) .addModifiers(Modifier.PRIVATE) .addStatement("return protocolFactory.createErrorResponseHandler(operationMetadata)") .build()); }
Example #19
Source File: test-endpoint-discovery-sync.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
/** * Invokes the TestDiscoveryOptional operation. * * @param testDiscoveryOptionalRequest * @return Result of the TestDiscoveryOptional operation returned by the service. * @throws SdkException * Base class for all exceptions that can be thrown by the SDK (both service and client). Can be used for * catch all scenarios. * @throws SdkClientException * If any client side error occurs such as an IO related failure, failure to get credentials, etc. * @throws EndpointDiscoveryTestException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample EndpointDiscoveryTestClient.TestDiscoveryOptional */ @Override public TestDiscoveryOptionalResponse testDiscoveryOptional(TestDiscoveryOptionalRequest testDiscoveryOptionalRequest) throws AwsServiceException, SdkClientException, EndpointDiscoveryTestException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler<TestDiscoveryOptionalResponse> responseHandler = protocolFactory.createResponseHandler( operationMetadata, TestDiscoveryOptionalResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); URI cachedEndpoint = null; if (clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED)) { String key = clientConfiguration.option(AwsClientOption.CREDENTIALS_PROVIDER).resolveCredentials().accessKeyId(); EndpointDiscoveryRequest endpointDiscoveryRequest = EndpointDiscoveryRequest.builder().required(false) .defaultEndpoint(clientConfiguration.option(SdkClientOption.ENDPOINT)).build(); cachedEndpoint = endpointDiscoveryCache.get(key, endpointDiscoveryRequest); } return clientHandler.execute(new ClientExecutionParams<TestDiscoveryOptionalRequest, TestDiscoveryOptionalResponse>() .withOperationName("TestDiscoveryOptional").withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler).discoveredEndpoint(cachedEndpoint) .withInput(testDiscoveryOptionalRequest) .withMarshaller(new TestDiscoveryOptionalRequestMarshaller(protocolFactory))); }
Example #20
Source File: test-endpoint-discovery-sync.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
/** * Invokes the TestDiscoveryRequired operation. * * @param testDiscoveryRequiredRequest * @return Result of the TestDiscoveryRequired operation returned by the service. * @throws SdkException * Base class for all exceptions that can be thrown by the SDK (both service and client). Can be used for * catch all scenarios. * @throws SdkClientException * If any client side error occurs such as an IO related failure, failure to get credentials, etc. * @throws EndpointDiscoveryTestException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample EndpointDiscoveryTestClient.TestDiscoveryRequired */ @Override public TestDiscoveryRequiredResponse testDiscoveryRequired(TestDiscoveryRequiredRequest testDiscoveryRequiredRequest) throws AwsServiceException, SdkClientException, EndpointDiscoveryTestException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler<TestDiscoveryRequiredResponse> responseHandler = protocolFactory.createResponseHandler( operationMetadata, TestDiscoveryRequiredResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); URI cachedEndpoint = null; if (clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED)) { String key = clientConfiguration.option(AwsClientOption.CREDENTIALS_PROVIDER).resolveCredentials().accessKeyId(); EndpointDiscoveryRequest endpointDiscoveryRequest = EndpointDiscoveryRequest.builder().required(true) .defaultEndpoint(clientConfiguration.option(SdkClientOption.ENDPOINT)).build(); cachedEndpoint = endpointDiscoveryCache.get(key, endpointDiscoveryRequest); } return clientHandler.execute(new ClientExecutionParams<TestDiscoveryRequiredRequest, TestDiscoveryRequiredResponse>() .withOperationName("TestDiscoveryRequired").withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler).discoveredEndpoint(cachedEndpoint) .withInput(testDiscoveryRequiredRequest) .withMarshaller(new TestDiscoveryRequiredRequestMarshaller(protocolFactory))); }
Example #21
Source File: AwsStructuredIonFactoryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
private AwsServiceException handleError(SdkHttpFullResponse error) throws Exception { return AwsIonProtocolFactory.builder() .registerModeledException( ExceptionMetadata.builder() .exceptionBuilderSupplier(InvalidParameterException::builder) .errorCode(ERROR_TYPE) .build()) .customErrorCodeFieldName(NO_CUSTOM_ERROR_CODE_FIELD_NAME) .build() .createErrorResponseHandler(JsonOperationMetadata.builder() .hasStreamingSuccessResponse(false) .isPayloadJson(true) .build()) .handle(error, new ExecutionAttributes()); }
Example #22
Source File: test-async-client-class.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
/** * <p> * Performs a post operation to the query service and has no output * </p> * * @param aPostOperationRequest * @return A Java Future containing the result of the APostOperation operation returned by the service.<br/> * The CompletableFuture returned by this method can be completed exceptionally with the following * exceptions. * <ul> * <li>InvalidInputException The request was rejected because an invalid or out-of-range value was supplied * for an input parameter.</li> * <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client). * Can be used for catch all scenarios.</li> * <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get * credentials, etc.</li> * <li>JsonException Base class for all service exceptions. Unknown exceptions will be thrown as an instance * of this type.</li> * </ul> * @sample JsonAsyncClient.APostOperation * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/json-service-2010-05-08/APostOperation" target="_top">AWS * API Documentation</a> */ @Override public CompletableFuture<APostOperationResponse> aPostOperation(APostOperationRequest aPostOperationRequest) { try { String hostPrefix = "{StringMember}-foo."; Validate.paramNotBlank(aPostOperationRequest.stringMember(), "StringMember"); String resolvedHostExpression = String.format("%s-foo.", aPostOperationRequest.stringMember()); JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler<APostOperationResponse> responseHandler = protocolFactory.createResponseHandler( operationMetadata, APostOperationResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); CompletableFuture<APostOperationResponse> executeFuture = clientHandler .execute(new ClientExecutionParams<APostOperationRequest, APostOperationResponse>() .withOperationName("APostOperation") .withMarshaller(new APostOperationRequestMarshaller(protocolFactory)) .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .hostPrefixExpression(resolvedHostExpression).withInput(aPostOperationRequest)); return executeFuture; } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } }
Example #23
Source File: JsonProtocolSpec.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Override public Optional<CodeBlock> errorResponseHandler(OperationModel opModel) { String protocolFactory = protocolFactoryLiteral(model, opModel); return Optional.of( CodeBlock.builder() .add("\n\n$T<$T> errorResponseHandler = createErrorResponseHandler($L, operationMetadata);", HttpResponseHandler.class, AwsServiceException.class, protocolFactory) .build()); }
Example #24
Source File: AwsStructuredIonFactoryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void handlesErrorsUsingAnnotation() throws Exception { IonStruct payload = createPayload(); payload.addTypeAnnotation(ERROR_PREFIX + ERROR_TYPE); SdkHttpFullResponse error = createResponse(payload); AwsServiceException exception = handleError(error); assertThat(exception).isInstanceOf(InvalidParameterException.class); assertEquals(ERROR_MESSAGE, exception.awsErrorDetails().errorMessage()); }
Example #25
Source File: SyncClientInterface.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
private static List<ClassName> getExceptionClasses(IntermediateModel model, OperationModel opModel) { List<ClassName> exceptions = opModel.getExceptions().stream() .map(e -> ClassName.get(model.getMetadata().getFullModelPackageName(), e.getExceptionName())) .collect(toCollection(ArrayList::new)); Collections.addAll(exceptions, ClassName.get(AwsServiceException.class), ClassName.get(SdkClientException.class), ClassName.get(model.getMetadata().getFullModelPackageName(), model.getSdkModeledExceptionBaseClassName())); return exceptions; }
Example #26
Source File: test-query-async-client-class.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
/** * Some operation with a streaming output * * @param streamingOutputOperationRequest * @param asyncResponseTransformer * The response transformer for processing the streaming response in a non-blocking manner. See * {@link AsyncResponseTransformer} for details on how this callback should be implemented and for links to * precanned implementations for common scenarios like downloading to a file. The service documentation for * the response content is as follows 'This be a stream'. * @return A future to the transformed result of the AsyncResponseTransformer.<br/> * The CompletableFuture returned by this method can be completed exceptionally with the following * exceptions. * <ul> * <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client). * Can be used for catch all scenarios.</li> * <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get * credentials, etc.</li> * <li>QueryException Base class for all service exceptions. Unknown exceptions will be thrown as an * instance of this type.</li> * </ul> * @sample QueryAsyncClient.StreamingOutputOperation * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/query-service-2010-05-08/StreamingOutputOperation" * target="_top">AWS API Documentation</a> */ @Override public <ReturnT> CompletableFuture<ReturnT> streamingOutputOperation( StreamingOutputOperationRequest streamingOutputOperationRequest, AsyncResponseTransformer<StreamingOutputOperationResponse, ReturnT> asyncResponseTransformer) { try { HttpResponseHandler<StreamingOutputOperationResponse> responseHandler = protocolFactory .createResponseHandler(StreamingOutputOperationResponse::builder); HttpResponseHandler<AwsServiceException> errorResponseHandler = protocolFactory.createErrorResponseHandler(); CompletableFuture<ReturnT> executeFuture = clientHandler.execute( new ClientExecutionParams<StreamingOutputOperationRequest, StreamingOutputOperationResponse>() .withOperationName("StreamingOutputOperation") .withMarshaller(new StreamingOutputOperationRequestMarshaller(protocolFactory)) .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .withInput(streamingOutputOperationRequest), asyncResponseTransformer); executeFuture.whenComplete((r, e) -> { if (e != null) { runAndLogError(log, "Exception thrown in exceptionOccurred callback, ignoring", () -> asyncResponseTransformer.exceptionOccurred(e)); } }); return executeFuture; } catch (Throwable t) { runAndLogError(log, "Exception thrown in exceptionOccurred callback, ignoring", () -> asyncResponseTransformer.exceptionOccurred(t)); return CompletableFutureUtils.failedFuture(t); } }
Example #27
Source File: BaseAwsJsonProtocolFactory.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
/** * Creates a response handler for handling a error response (non 2xx response). */ public final HttpResponseHandler<AwsServiceException> createErrorResponseHandler( JsonOperationMetadata errorResponseMetadata) { return AwsJsonProtocolErrorUnmarshaller .builder() .jsonProtocolUnmarshaller(protocolUnmarshaller) .exceptions(modeledExceptions) .errorCodeParser(getSdkFactory().getErrorCodeParser(customErrorCodeFieldName)) .errorMessageParser(AwsJsonErrorMessageParser.DEFAULT_ERROR_MESSAGE_PARSER) .jsonFactory(getSdkFactory().getJsonFactory()) .defaultExceptionSupplier(defaultServiceExceptionSupplier) .build(); }
Example #28
Source File: BaseExceptionClass.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
public TypeSpec builderInterface() { TypeSpec.Builder builder = TypeSpec.interfaceBuilder(baseExceptionClassName.nestedClass("Builder")) .addSuperinterface(ClassName.get(AwsServiceException.class).nestedClass("Builder")) .addModifiers(Modifier.PUBLIC) .addMethods(ExceptionProperties.builderInterfaceMethods(className().nestedClass("Builder"))); return builder.build(); }
Example #29
Source File: BaseExceptionClass.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Override public TypeSpec poetSpec() { return PoetUtils.createClassBuilder(baseExceptionClassName) .superclass(AwsServiceException.class) .addMethod(constructor()) .addMethod(builderMethod()) .addMethod(toBuilderMethod()) .addMethod(serializableBuilderClass()) .addModifiers(Modifier.PUBLIC) .addType(builderInterface()) .addType(builderImplClass()) .build(); }
Example #30
Source File: AwsXmlErrorUnmarshaller.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
/** * 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(); }