private MultiPartUpload initiateMultiPartUpload() throws IOException { final ObjectMetadata om = createDefaultMetadata(); final InitiateMultipartUploadRequest initiateMPURequest = new InitiateMultipartUploadRequest(bucket, key, om); initiateMPURequest.setCannedACL(cannedACL); try { return new MultiPartUpload( client.initiateMultipartUpload(initiateMPURequest).getUploadId()); } catch (AmazonServiceException ase) { throw new IOException("Unable to initiate MultiPartUpload (server side)" + ": " + ase, ase); } catch (AmazonClientException ace) { throw new IOException("Unable to initiate MultiPartUpload (client side)" + ": " + ace, ace); } }
/** * Send email. * * @param eMsg the e msg * @return true, if successful */ public boolean sendEmail(EmailMessage eMsg) { SendEmailRequest request = new SendEmailRequest().withSource(eMsg.getFromAddress()); Destination dest = new Destination().withToAddresses(eMsg.getToAddresses()); dest.setCcAddresses(eMsg.getToCcAddresses()); request.setDestination(dest); Content subjContent = new Content().withData(eMsg.getSubject()); Message msg = new Message().withSubject(subjContent); Content textContent = new Content().withData(eMsg.getTxtMessage()); Body body = new Body().withText(textContent); if (eMsg.getHtmlMessage() != null) { Content htmlContent = new Content().withData(eMsg.getHtmlMessage()); body.setHtml(htmlContent); } msg.setBody(body); request.setMessage(msg); try { emailClient.sendEmail(request); logger.debug(msg); } catch (AmazonClientException e) { logger.error(e.getMessage()); return false; } return true; }
@Test(timeout = 60 * 1000) public void leasing_a_new_connection_fails_with_connection_pool_timeout() throws Exception { String localhostEndpoint = "http://localhost:" + server.getPort(); AmazonHttpClient httpClient = new AmazonHttpClient( new ClientConfiguration() .withMaxConnections(1) .withConnectionTimeout(100) .withMaxErrorRetry(0)); Request<?> request = new EmptyHttpRequest(localhostEndpoint, HttpMethodName.GET); // Block the first connection in the pool with this request. httpClient.requestExecutionBuilder().request(request).execute(new EmptyAWSResponseHandler()); try { // A new connection will be leased here which would fail in // ConnectionPoolTimeoutException. httpClient.requestExecutionBuilder().request(request).execute(); Assert.fail("Connection pool timeout exception is expected!"); } catch (AmazonClientException e) { Assert.assertTrue(e.getCause() instanceof ConnectionPoolTimeoutException); } }
@Override public InputStream readBlob(String blobName) throws IOException { int retry = 0; while (retry <= blobStore.numberOfRetries()) { try { S3Object s3Object = SocketAccess.doPrivileged(() -> blobStore.client().getObject(blobStore.bucket(), buildKey(blobName))); return s3Object.getObjectContent(); } catch (AmazonClientException e) { if (blobStore.shouldRetry(e) && (retry < blobStore.numberOfRetries())) { retry++; } else { if (e instanceof AmazonS3Exception) { if (404 == ((AmazonS3Exception) e).getStatusCode()) { throw new NoSuchFileException("Blob object [" + blobName + "] not found: " + e.getMessage()); } } throw e; } } } throw new BlobStoreException("retries exhausted while attempting to access blob object [name:" + blobName + ", bucket:" + blobStore.bucket() + "]"); }
@Override public CopyObjectResult copyObject(CopyObjectRequest copyObjectRequest) throws AmazonClientException, AmazonServiceException { String sourceBlobName = copyObjectRequest.getSourceKey(); String targetBlobName = copyObjectRequest.getDestinationKey(); if (!blobs.containsKey(sourceBlobName)) { throw new AmazonS3Exception("Source blob [" + sourceBlobName + "] does not exist."); } if (blobs.containsKey(targetBlobName)) { throw new AmazonS3Exception("Target blob [" + targetBlobName + "] already exists."); } blobs.put(targetBlobName, blobs.get(sourceBlobName)); return new CopyObjectResult(); // nothing is done with it }
@Override public Bucket createBucket(CreateBucketRequest createBucketRequest) throws AmazonClientException, AmazonServiceException { if ("nonExistingBucket".equals(createBucketRequest.getBucketName())) { nonExistingBucketCreated = true; } Bucket bucket = new Bucket(); bucket.setName(createBucketRequest.getBucketName()); bucket.setCreationDate(new Date()); bucket.setOwner(new Owner("c2efc7302b9011ba9a78a92ac5fd1cd47b61790499ab5ddf5a37c31f0638a8fc ", "Christian Mueller")); return bucket; }
@Test public void shouldRetry_MaxErrorNotExceeded_DelegatesToLegacyRetryCondition() { final RetryPolicyContext context = RetryPolicyContexts.LEGACY; adapter.shouldRetry(context); verify(retryCondition).shouldRetry( eq((AmazonWebServiceRequest) context.originalRequest()), eq((AmazonClientException) context.exception()), eq(context.retriesAttempted())); }
@Override public boolean shouldRetry(RetryPolicyContext context) { if (context.retriesAttempted() >= getMaxErrorRetry()) { return false; } return legacyRetryPolicy.getRetryCondition().shouldRetry( (AmazonWebServiceRequest) context.originalRequest(), (AmazonClientException) context.exception(), context.retriesAttempted()); }
/** * You can make any number of invalidation requests, but you can have only three invalidation requests * in progress at one time. Each request can contain up to 1,000 objects to invalidate. If you * exceed these limits, you get an error message. * <p> * It usually takes 10 to 15 minutes to complete your invalidation request, depending on * the size of your request. */ @Override public void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt) throws BackgroundException { try { final Distribution d = this.read(container, method, prompt); final List<String> keys = new ArrayList<String>(); for(Path file : files) { if(containerService.isContainer(file)) { // To invalidate all of the objects in a distribution keys.add(String.format("%s*", String.valueOf(Path.DELIMITER))); } else { if(file.isDirectory()) { // The *, which replaces 0 or more characters, must be the last character in the invalidation path keys.add(String.format("/%s*", containerService.getKey(file))); } else { keys.add(String.format("/%s", containerService.getKey(file))); } } } if(keys.isEmpty()) { log.warn("No keys selected for invalidation"); } else { final AmazonCloudFront client = client(container); client.createInvalidation(new CreateInvalidationRequest(d.getId(), new InvalidationBatch(new Paths().withItems(keys).withQuantity(keys.size()), new AlphanumericRandomStringService().random()) )); } } catch(AmazonClientException e) { throw new AmazonServiceExceptionMappingService().map("Cannot write CDN configuration", e); } }
/** * Tests loading a profile that assumes a role, but the source profile does not exist. */ @Test public void testRoleProfileWithNoSourceName() throws URISyntaxException { checkDeferredException(ProfileResourceLoader.roleProfileWithNoSourceName(), AmazonClientException.class, "test", "Should throw an exception as there is a role profile with a missing source role"); }
/** * If no region is explicitly given and no region can be found from the {@link * AwsRegionProvider} implementation then the builder should fail to build clients. We mock the * provider to yield consistent results for the tests. */ @Test(expected = AmazonClientException.class) public void noRegionProvidedExplicitlyOrImplicitly_ThrowsException() { AwsRegionProvider mockRegionProvider = mock(AwsRegionProvider.class); when(mockRegionProvider.getRegion()).thenReturn(null); new ConcreteAsyncBuilder(mockRegionProvider).build(); }
@Override public BackgroundException map(final AmazonClientException e) { final StringBuilder buffer = new StringBuilder(); if(e instanceof AmazonServiceException) { final AmazonServiceException failure = (AmazonServiceException) e; this.append(buffer, failure.getErrorMessage()); switch(failure.getStatusCode()) { case HttpStatus.SC_BAD_REQUEST: switch(failure.getErrorCode()) { case "Throttling": return new RetriableAccessDeniedException(buffer.toString(), e); case "AccessDeniedException": return new AccessDeniedException(buffer.toString(), e); case "UnrecognizedClientException": return new LoginFailureException(buffer.toString(), e); } case HttpStatus.SC_FORBIDDEN: switch(failure.getErrorCode()) { case "SignatureDoesNotMatch": return new LoginFailureException(buffer.toString(), e); case "InvalidAccessKeyId": return new LoginFailureException(buffer.toString(), e); case "InvalidClientTokenId": return new LoginFailureException(buffer.toString(), e); case "InvalidSecurity": return new LoginFailureException(buffer.toString(), e); case "MissingClientTokenId": return new LoginFailureException(buffer.toString(), e); case "MissingAuthenticationToken": return new LoginFailureException(buffer.toString(), e); } } return new HttpResponseExceptionMappingService().map(new HttpResponseException(failure.getStatusCode(), buffer.toString())); } this.append(buffer, e.getMessage()); return this.wrap(e, buffer); }
/** * -- Explicitly set maxErrorRetry in ClientConfiguration level; * -- Custom RetryPolicy's that want to override such setting. */ @Test public void testRetryPolicyLevelMaxErrorRetry() { // This should be ignored clientConfiguration.setMaxErrorRetry(random.nextInt(3)); // A custom policy that doesn't honor the ClientConfig level maxErrorRetry int RETRY_POLICY_LEVEL_MAX_ERROR_RETRY = 5; clientConfiguration.setRetryPolicy(new RetryPolicy(null, null, RETRY_POLICY_LEVEL_MAX_ERROR_RETRY, false)); testActualRetries(RETRY_POLICY_LEVEL_MAX_ERROR_RETRY); // A custom policy that "honors" the ClientConfig level maxErrorRetry, // but actually denies any retry in its condition. clientConfiguration.setRetryPolicy(new RetryPolicy( new RetryPolicy.RetryCondition() { @Override public boolean shouldRetry( AmazonWebServiceRequest originalRequest, AmazonClientException exception, int retriesAttempted) { return false; } }, null, RETRY_POLICY_LEVEL_MAX_ERROR_RETRY, true) ); // No retry is expected testActualRetries(0); }
/** * Test that when credentials are null and response from client does not have access key/secret key, * throws AmazonClientException. */ @Test public void testLoadCredentialsThrowsAceWhenClientResponseDontHaveKeys() { // Stub for success response but without keys in the response body stubForSuccessResponseWithCustomBody(200, successResponseWithInvalidBody); TestCredentialsProvider credentialsProvider = new TestCredentialsProvider(); try { credentialsProvider.getCredentials(); fail("Expected an AmazonClientException"); } catch (AmazonClientException ace) { assertEquals("Unable to load credentials.", ace.getMessage()); } }
@Override public DescribePlacementGroupsResult describePlacementGroups(DescribePlacementGroupsRequest describePlacementGroupsRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public BucketLoggingConfiguration getBucketLoggingConfiguration(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); }
@Override public PartListing listParts(ListPartsRequest listPartsRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); }
@Override public Owner getS3AccountOwner() throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); }
@Override public boolean doesBucketExist(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); }
@Override public CreateKeyPairResult createKeyPair(CreateKeyPairRequest createKeyPairRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public void modifyNetworkInterfaceAttribute(ModifyNetworkInterfaceAttributeRequest modifyNetworkInterfaceAttributeRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public DescribeReservedInstancesResult describeReservedInstances(DescribeReservedInstancesRequest describeReservedInstancesRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public DescribeAvailabilityZonesResult describeAvailabilityZones(DescribeAvailabilityZonesRequest describeAvailabilityZonesRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public void setBucketPolicy(String bucketName, String policyText) throws AmazonClientException, AmazonServiceException { delegate.setBucketPolicy(bucketName, policyText); }
@Override public URL generatePresignedUrl(GeneratePresignedUrlRequest generatePresignedUrlRequest) throws AmazonClientException { throw new UnsupportedOperationException(); }
@Override public DescribeDhcpOptionsResult describeDhcpOptions() throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public AttachVpnGatewayResult attachVpnGateway(AttachVpnGatewayRequest attachVpnGatewayRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public InitiateMultipartUploadResult initiateMultipartUpload(InitiateMultipartUploadRequest request) throws AmazonClientException, AmazonServiceException { return delegate.initiateMultipartUpload(request); }
@Override public void setObjectAcl(String bucketName, String key, CannedAccessControlList acl) throws AmazonClientException, AmazonServiceException { delegate.setObjectAcl(bucketName, key, acl); }
@Override public ObjectMetadata getObject(GetObjectRequest getObjectRequest, File destinationFile) throws AmazonClientException, AmazonServiceException { return delegate.getObject(getObjectRequest, destinationFile); }
@Override public CompleteMultipartUploadResult completeMultipartUpload(CompleteMultipartUploadRequest completeMultipartUploadRequest) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); }
@Override public Bucket createBucket(String bucketName) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); }
@Override public StopInstancesResult stopInstances(StopInstancesRequest stopInstancesRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public DescribeImageAttributeResult describeImageAttribute(DescribeImageAttributeRequest describeImageAttributeRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public DescribeSpotFleetInstancesResult describeSpotFleetInstances(DescribeSpotFleetInstancesRequest describeSpotFleetInstancesRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public CreateSecurityGroupResult createSecurityGroup(CreateSecurityGroupRequest createSecurityGroupRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public void setBucketAcl(String bucketName, CannedAccessControlList acl) throws AmazonClientException, AmazonServiceException { throw new UnsupportedOperationException(); }
@Override public DescribeRegionsResult describeRegions(DescribeRegionsRequest describeRegionsRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }