software.amazon.awssdk.core.exception.SdkClientException Java Examples
The following examples show how to use
software.amazon.awssdk.core.exception.SdkClientException.
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: AbstractAwsSigner.java From aws-sdk-java-v2 with Apache License 2.0 | 7 votes |
byte[] hash(InputStream input) throws SdkClientException { try { MessageDigest md = getMessageDigestInstance(); @SuppressWarnings("resource") DigestInputStream digestInputStream = new SdkDigestInputStream( input, md); byte[] buffer = new byte[1024]; while (digestInputStream.read(buffer) > -1) { ; } return digestInputStream.getMessageDigest().digest(); } catch (Exception e) { throw SdkClientException.builder() .message("Unable to compute hash while signing request: " + e.getMessage()) .cause(e) .build(); } }
Example #2
Source File: AmazonHttpClientTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void testRetryIoExceptionFromHandler() throws Exception { final IOException exception = new IOException("BOOM"); HttpResponseHandler<?> mockHandler = mock(HttpResponseHandler.class); when(mockHandler.needsConnectionLeftOpen()).thenReturn(false); when(mockHandler.handle(any(), any())).thenThrow(exception); ExecutionContext context = ClientExecutionAndRequestTimerTestUtils.executionContext(null); try { client.requestExecutionBuilder() .request(ValidSdkObjects.sdkHttpFullRequest().build()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(context) .execute(combinedSyncResponseHandler(mockHandler, null)); Assert.fail("No exception when request repeatedly fails!"); } catch (SdkClientException e) { Assert.assertSame(exception, e.getCause()); } // Verify that we called execute 4 times. verify(mockHandler, times(4)).handle(any(), any()); }
Example #3
Source File: StabilityTestRunner.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * Handle the exceptions of executing the futures. * * @param future the future to be executed * @param exceptionCounter the exception counter * @return the completable future */ private static CompletableFuture<?> handleException(CompletableFuture<?> future, ExceptionCounter exceptionCounter) { return future.exceptionally(t -> { Throwable cause = t.getCause(); log.error(() -> "An exception was thrown ", t); if (cause instanceof SdkServiceException) { exceptionCounter.addServiceException(); } else if (isIOException(cause)) { exceptionCounter.addIoException(); } else if (cause instanceof SdkClientException) { if (isIOException(cause.getCause())) { exceptionCounter.addIoException(); } else { exceptionCounter.addClientException(); } } else { exceptionCounter.addUnknownException(); } return null; }); }
Example #4
Source File: MarshallerSpec.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
private MethodSpec marshallMethod() { String variableName = shapeModel.getVariable().getVariableName(); MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder("marshall") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(requestClassName, variableName) .returns(httpRequestName); methodSpecBuilder.addStatement("$T.paramNotNull($L, $S)", ClassName.get(Validate.class), variableName, variableName); methodSpecBuilder.beginControlFlow("try"); methodSpecBuilder.addCode(protocolSpec.marshalCodeBlock(requestClassName)); methodSpecBuilder.endControlFlow(); methodSpecBuilder.beginControlFlow("catch (Exception e)"); methodSpecBuilder.addStatement("throw $T.builder().message(\"Unable to marshall request to JSON: \" + " + "e.getMessage()).cause(e).build()", ClassName .get(SdkClientException.class)); methodSpecBuilder.endControlFlow(); return methodSpecBuilder.build(); }
Example #5
Source File: AsyncApiCallTimeoutTrackingStage.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<OutputT> execute(SdkHttpFullRequest input, RequestExecutionContext context) throws Exception { CompletableFuture<OutputT> future = new CompletableFuture<>(); long apiCallTimeoutInMillis = resolveTimeoutInMillis(() -> context.requestConfig().apiCallTimeout(), clientConfig.option(SdkClientOption.API_CALL_TIMEOUT)); Supplier<SdkClientException> exceptionSupplier = () -> ApiCallTimeoutException.create(apiCallTimeoutInMillis); TimeoutTracker timeoutTracker = timeAsyncTaskIfNeeded(future, scheduledExecutor, exceptionSupplier, apiCallTimeoutInMillis); context.apiCallTimeoutTracker(timeoutTracker); CompletableFuture<OutputT> executeFuture = requestPipeline.execute(input, context); executeFuture.whenComplete((r, t) -> { if (t != null) { future.completeExceptionally(t); } else { future.complete(r); } }); return CompletableFutureUtils.forwardExceptionTo(future, executeFuture); }
Example #6
Source File: MessageAttributesIntegrationTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void sendMessage_InvalidMd5_ThrowsException() { try (SqsClient tamperingClient = SqsClient.builder() .credentialsProvider(getCredentialsProvider()) .overrideConfiguration(ClientOverrideConfiguration .builder() .addExecutionInterceptor( new TamperingInterceptor()) .build()) .build()) { tamperingClient.sendMessage( SendMessageRequest.builder() .queueUrl(queueUrl) .messageBody(MESSAGE_BODY) .messageAttributes(createRandomAttributeValues(10)) .build()); fail("Expected SdkClientException"); } catch (SdkClientException e) { assertThat(e.getMessage(), containsString("MD5 returned by SQS does not match")); } }
Example #7
Source File: ClasspathSdkHttpServiceProvider.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Override public Optional<T> loadService() { Iterator<T> httpServices = serviceLoader.loadServices(serviceClass); if (!httpServices.hasNext()) { return Optional.empty(); } T httpService = httpServices.next(); if (httpServices.hasNext()) { throw SdkClientException.builder().message( String.format( "Multiple HTTP implementations were found on the classpath. To avoid non-deterministic loading " + "implementations, please explicitly provide an HTTP client via the client builders, set the %s " + "system property with the FQCN of the HTTP service to use as the default, or remove all but one " + "HTTP implementation from the classpath", implSystemProperty.property())) .build(); } return Optional.of(httpService); }
Example #8
Source File: MessageMD5ChecksumInterceptor.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * Returns the hex-encoded MD5 hash String of the given message body. */ private static String calculateMessageBodyMd5(String messageBody) { log.debug(() -> "Message body: " + messageBody); byte[] expectedMd5; try { expectedMd5 = Md5Utils.computeMD5Hash(messageBody.getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw SdkClientException.builder() .message("Unable to calculate the MD5 hash of the message body. " + e.getMessage()) .cause(e) .build(); } String expectedMd5Hex = BinaryUtils.toHex(expectedMd5); log.debug(() -> "Expected MD5 of message body: " + expectedMd5Hex); return expectedMd5Hex; }
Example #9
Source File: ChecksumsEnabledValidator.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * Client side validation for {@link PutObjectRequest} * * @param response the response * @param executionAttributes the execution attributes */ public static void validatePutObjectChecksum(PutObjectResponse response, ExecutionAttributes executionAttributes) { SdkChecksum checksum = executionAttributes.getAttribute(CHECKSUM); if (response.eTag() != null) { String contentMd5 = BinaryUtils.toBase64(checksum.getChecksumBytes()); byte[] digest = BinaryUtils.fromBase64(contentMd5); byte[] ssHash = Base16Lower.decode(response.eTag().replace("\"", "")); if (!Arrays.equals(digest, ssHash)) { throw SdkClientException.create( String.format("Data read has a different checksum than expected. Was 0x%s, but expected 0x%s", BinaryUtils.toHex(digest), BinaryUtils.toHex(ssHash))); } } }
Example #10
Source File: EndpointTraitTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void hostExpression_withInputMemberLabel() throws URISyntaxException { try { client.endpointTraitTwo(EndpointTraitTwoRequest.builder() .stringMember("123456") .pathIdempotentToken("dummypath") .build()); Assert.fail("Expected an exception"); } catch (SdkClientException exception) { ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(mockHttpClient).prepareRequest(httpRequestCaptor.capture()); SdkHttpRequest request = httpRequestCaptor.getAllValues().get(0).httpRequest(); assertThat(request.host()).isEqualTo("123456-localhost.com"); assertThat(request.port()).isEqualTo(443); assertThat(request.encodedPath()).isEqualTo("/dummypath"); assertThat(request.getUri()).isEqualTo(new URI("http://123456-localhost.com:443/dummypath")); } }
Example #11
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 #12
Source File: EventStreamAsyncResponseTransformer.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * Handle the event stream message according to it's type. * * @param m Decoded message. */ private void handleMessage(Message m) { try { if (isEvent(m)) { if (m.getHeaders().get(":event-type").getString().equals("initial-response")) { eventStreamResponseHandler.responseReceived( initialResponseHandler.handle(adaptMessageToResponse(m, false), EMPTY_EXECUTION_ATTRIBUTES)); } else { // Add to queue to be delivered later by the executor eventsToDeliver.add(eventResponseHandler.handle(adaptMessageToResponse(m, false), EMPTY_EXECUTION_ATTRIBUTES)); } } else if (isError(m) || isException(m)) { SdkHttpFullResponse errorResponse = adaptMessageToResponse(m, true); Throwable exception = exceptionResponseHandler.handle( errorResponse, new ExecutionAttributes().putAttribute(SdkExecutionAttribute.SERVICE_NAME, serviceName)); runAndLogError(log, "Error thrown from exceptionOccurred, ignoring.", () -> exceptionOccurred(exception)); } } catch (Exception e) { throw SdkClientException.builder().cause(e).build(); } }
Example #13
Source File: StringToInstant.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Override public Instant convert(String value, SdkField<Instant> field) { if (value == null) { return null; } TimestampFormatTrait.Format format = resolveTimestampFormat(field); switch (format) { case ISO_8601: return DateUtils.parseIso8601Date(value); case UNIX_TIMESTAMP: return safeParseDate(DateUtils::parseUnixTimestampInstant).apply(value); case UNIX_TIMESTAMP_MILLIS: return safeParseDate(DateUtils::parseUnixTimestampMillisInstant).apply(value); case RFC_822: return DateUtils.parseRfc1123Date(value); default: throw SdkClientException.create("Unrecognized timestamp format - " + format); } }
Example #14
Source File: HttpCredentialsProviderTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
/** * Tests how the credentials provider behaves when the * server is not running. */ @Test public void testNoMetadataService() throws Exception { stubForErrorResponse(); HttpCredentialsProvider credentialsProvider = testCredentialsProvider(); // When there are no credentials, the provider should throw an exception if we can't connect assertThatExceptionOfType(SdkClientException.class).isThrownBy(credentialsProvider::resolveCredentials); // When there are valid credentials (but need to be refreshed) and the endpoint returns 404 status, // the provider should throw an exception. stubForSuccessResonseWithCustomExpirationDate(new Date(System.currentTimeMillis() + ONE_MINUTE * 4)); credentialsProvider.resolveCredentials(); // loads the credentials that will be expired soon stubForErrorResponse(); // Behaves as if server is unavailable. assertThatExceptionOfType(SdkClientException.class).isThrownBy(credentialsProvider::resolveCredentials); }
Example #15
Source File: PredictEndpointInterceptor.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); Object originalRequest = context.request(); if (originalRequest instanceof PredictRequest) { PredictRequest pr = (PredictRequest) originalRequest; if (pr.predictEndpoint() == null) { throw SdkClientException.builder().message("PredictRequest.PredictEndpoint is required!").build(); } try { URI endpoint = new URI(pr.predictEndpoint()); return request.toBuilder().uri(endpoint).build(); } catch (URISyntaxException e) { throw SdkClientException.builder() .message("Unable to parse PredictRequest.PredictEndpoint") .cause(e) .build(); } } return request; }
Example #16
Source File: IonParser.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Override public Number getNumberValue() { NumberType numberType = getNumberType(); if (numberType == null) { throw SdkClientException.builder() .message(String.format("Unable to get number value for non-numeric token %s", reader.getType())) .build(); } switch (numberType) { case BIG_DECIMAL: return reader.bigDecimalValue(); case BIG_INTEGER: return reader.bigIntegerValue(); case DOUBLE: return reader.doubleValue(); default: throw SdkClientException.builder() .message(String.format("Unable to get number value for number type %s", numberType)) .build(); } }
Example #17
Source File: SdkIonGenerator.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Override public StructuredJsonGenerator writeStartArray() { try { writer.stepIn(IonType.LIST); } catch (IOException e) { throw SdkClientException.builder().cause(e).build(); } return this; }
Example #18
Source File: SdkIonGenerator.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Override public StructuredJsonGenerator writeNull() { try { writer.writeNull(); } catch (IOException e) { throw SdkClientException.builder().cause(e).build(); } return this; }
Example #19
Source File: ProfileCredentialsProviderTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void missingProfileThrowsExceptionInGetCredentials() { ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder().profileFile(file).profileName("foo").build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); }
Example #20
Source File: HelpfulUnknownHostExceptionInterceptorTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void modifyException_returnsGenericGlobalRegionHelp_forServicesGlobalInSomePartitionOtherThanTheClientPartition() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.of("cn-north-99"), "iam")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "network")) .hasMessageContaining("aws-global") .hasMessageContaining("aws-cn-global"); }
Example #21
Source File: eventstreamoperationrequestmarshaller.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Override public SdkHttpFullRequest marshall(EventStreamOperationRequest eventStreamOperationRequest) { Validate.paramNotNull(eventStreamOperationRequest, "eventStreamOperationRequest"); try { ProtocolMarshaller<SdkHttpFullRequest> protocolMarshaller = protocolFactory .createProtocolMarshaller(SDK_OPERATION_BINDING); return protocolMarshaller.marshall(eventStreamOperationRequest); } catch (Exception e) { throw SdkClientException.builder().message("Unable to marshall request to JSON: " + e.getMessage()).cause(e).build(); } }
Example #22
Source File: InstanceProfileCredentialsProviderTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void resolveCredentials_endpointSettingEmpty_throws() { thrown.expect(SdkClientException.class); System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), ""); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); }
Example #23
Source File: StringToInstant.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
/** * Wraps date unmarshalling function to handle the {@link NumberFormatException}. * @param dateUnmarshaller Original date unmarshaller function. * @return New date unmarshaller function with exception handling. */ private Function<String, Instant> safeParseDate(Function<String, Instant> dateUnmarshaller) { return value -> { try { return dateUnmarshaller.apply(value); } catch (NumberFormatException e) { throw SdkClientException.builder() .message("Unable to parse date : " + value) .cause(e) .build(); } }; }
Example #24
Source File: EndpointTraitTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void clientWithDisabledHostPrefix_withInputMemberLabel_usesOriginalUri() { try { clientWithDisabledHostPrefix.endpointTraitTwo(EndpointTraitTwoRequest.builder() .stringMember("123456") .build()); Assert.fail("Expected an exception"); } catch (SdkClientException exception) { ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(mockHttpClient).prepareRequest(httpRequestCaptor.capture()); SdkHttpRequest request = httpRequestCaptor.getAllValues().get(0).httpRequest(); assertThat(request.host()).isEqualTo("localhost.com"); } }
Example #25
Source File: HelpfulUnknownHostExceptionInterceptorTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void modifyException_returnsGenericHelp_forGlobalRegions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.AWS_GLOBAL)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("network"); }
Example #26
Source File: AbstractAwsSigner.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
protected byte[] sign(String stringData, byte[] key, SigningAlgorithm algorithm) throws SdkClientException { try { byte[] data = stringData.getBytes(StandardCharsets.UTF_8); return sign(data, key, algorithm); } catch (Exception e) { throw SdkClientException.builder() .message("Unable to calculate a request signature: " + e.getMessage()) .cause(e) .build(); } }
Example #27
Source File: EndpointTraitTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Before public void setup() throws Exception { client = clientBuilder().build(); clientWithDisabledHostPrefix = clientBuilder().overrideConfiguration( ClientOverrideConfiguration.builder() .putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true) .build()).build(); when(mockHttpClient.prepareRequest(any())).thenReturn(abortableCallable); when(abortableCallable.call()).thenThrow(SdkClientException.create("Dummy exception")); }
Example #28
Source File: AwsRetryPolicyTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void retriesOnIOException() { assertTrue(shouldRetry(b -> b.exception(SdkClientException.builder() .message("IO") .cause(new IOException()) .build()))); }
Example #29
Source File: ThrowableUtils.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
/** * Wraps the given {@code Throwable} in {@link SdkException} if necessary. */ public static SdkException asSdkException(Throwable t) { if (t instanceof SdkException) { return (SdkException) t; } return SdkClientException.builder().cause(t).build(); }
Example #30
Source File: ResponseTransformerTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void downloadToExistingFileDoesNotRetry() throws IOException { stubForRetriesTimeoutReadingFromStreams(); assertThatThrownBy(() -> testClient().streamingOutputOperation(StreamingOutputOperationRequest.builder().build(), ResponseTransformer .toFile(new File("..")))) .isInstanceOf(SdkClientException.class); }