Search in sources :

Example 26 with AmazonS3Client

use of com.amazonaws.services.s3.AmazonS3Client in project herd by FINRAOS.

the class S3DaoTest method testGetAWSCredentialsProviderAssertStaticCredentialsIsNotSetWhenSecretKeyIsNull.

@Test
public void testGetAWSCredentialsProviderAssertStaticCredentialsIsNotSetWhenSecretKeyIsNull() {
    S3Operations originalS3Operations = (S3Operations) ReflectionTestUtils.getField(s3Dao, "s3Operations");
    S3Operations mockS3Operations = mock(S3Operations.class);
    ReflectionTestUtils.setField(s3Dao, "s3Operations", mockS3Operations);
    try {
        String s3BucketName = "s3BucketName";
        String s3KeyPrefix = "s3KeyPrefix";
        String s3AccessKey = "s3AccessKey";
        String s3SecretKey = null;
        S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
        s3FileTransferRequestParamsDto.setS3BucketName(s3BucketName);
        s3FileTransferRequestParamsDto.setS3KeyPrefix(s3KeyPrefix);
        s3FileTransferRequestParamsDto.setAwsAccessKeyId(s3AccessKey);
        s3FileTransferRequestParamsDto.setAwsSecretKey(s3SecretKey);
        when(mockS3Operations.putObject(any(), any())).then(new Answer<PutObjectResult>() {

            @SuppressWarnings("unchecked")
            @Override
            public PutObjectResult answer(InvocationOnMock invocation) throws Throwable {
                AmazonS3Client amazonS3Client = invocation.getArgument(1);
                AWSCredentialsProviderChain awsCredentialsProviderChain = (AWSCredentialsProviderChain) ReflectionTestUtils.getField(amazonS3Client, "awsCredentialsProvider");
                List<AWSCredentialsProvider> credentialsProviders = (List<AWSCredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProviderChain, "credentialsProviders");
                assertEquals(1, credentialsProviders.size());
                assertEquals(DefaultAWSCredentialsProviderChain.class, credentialsProviders.get(0).getClass());
                return new PutObjectResult();
            }
        });
        s3Dao.createDirectory(s3FileTransferRequestParamsDto);
    } finally {
        ReflectionTestUtils.setField(s3Dao, "s3Operations", originalS3Operations);
    }
}
Also used : DefaultAWSCredentialsProviderChain(com.amazonaws.auth.DefaultAWSCredentialsProviderChain) S3FileTransferRequestParamsDto(org.finra.herd.model.dto.S3FileTransferRequestParamsDto) PutObjectResult(com.amazonaws.services.s3.model.PutObjectResult) DefaultAWSCredentialsProviderChain(com.amazonaws.auth.DefaultAWSCredentialsProviderChain) AWSCredentialsProviderChain(com.amazonaws.auth.AWSCredentialsProviderChain) AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) InvocationOnMock(org.mockito.invocation.InvocationOnMock) List(java.util.List) ArrayList(java.util.ArrayList) HerdAWSCredentialsProvider(org.finra.herd.model.dto.HerdAWSCredentialsProvider) AWSCredentialsProvider(com.amazonaws.auth.AWSCredentialsProvider) Test(org.junit.Test)

Example 27 with AmazonS3Client

use of com.amazonaws.services.s3.AmazonS3Client in project herd by FINRAOS.

the class S3DaoImpl method createDirectory.

@Override
public void createDirectory(final S3FileTransferRequestParamsDto params) {
    // Create metadata for the directory marker and set content-length to 0 bytes.
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(0);
    prepareMetadata(params, metadata);
    // Create empty content.
    InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
    // Create a PutObjectRequest passing the folder name suffixed by '/'.
    String directoryName = StringUtils.appendIfMissing(params.getS3KeyPrefix(), "/");
    PutObjectRequest putObjectRequest = new PutObjectRequest(params.getS3BucketName(), directoryName, emptyContent, metadata);
    // KMS key ID is being set through prepareMetadata()
    AmazonS3Client s3Client = getAmazonS3(params);
    try {
        s3Operations.putObject(putObjectRequest, s3Client);
    } catch (AmazonServiceException e) {
        throw new IllegalStateException(String.format("Failed to create 0 byte S3 object with \"%s\" key in bucket \"%s\". Reason: %s", directoryName, params.getS3BucketName(), e.getMessage()), e);
    } finally {
        // Shutdown the AmazonS3Client instance to release resources.
        s3Client.shutdown();
    }
}
Also used : AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) AmazonServiceException(com.amazonaws.AmazonServiceException) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) PutObjectRequest(com.amazonaws.services.s3.model.PutObjectRequest)

Example 28 with AmazonS3Client

use of com.amazonaws.services.s3.AmazonS3Client in project herd by FINRAOS.

the class S3DaoImpl method restoreObjects.

@Override
public void restoreObjects(final S3FileTransferRequestParamsDto params, int expirationInDays) {
    LOGGER.info("Restoring a list of objects in S3... s3KeyPrefix=\"{}\" s3BucketName=\"{}\" s3KeyCount={}", params.getS3KeyPrefix(), params.getS3BucketName(), params.getFiles().size());
    if (!CollectionUtils.isEmpty(params.getFiles())) {
        // Initialize a key value pair for the error message in the catch block.
        String key = params.getFiles().get(0).getPath().replaceAll("\\\\", "/");
        try {
            // Create an S3 client.
            AmazonS3Client s3Client = getAmazonS3(params);
            // Create a restore object request.
            RestoreObjectRequest requestRestore = new RestoreObjectRequest(params.getS3BucketName(), null, expirationInDays);
            // Make Bulk as default glacier retrieval option
            requestRestore.setGlacierJobParameters(new GlacierJobParameters().withTier(GLACIER_RETRIEVAL_OPTION));
            try {
                for (File file : params.getFiles()) {
                    key = file.getPath().replaceAll("\\\\", "/");
                    ObjectMetadata objectMetadata = s3Operations.getObjectMetadata(params.getS3BucketName(), key, s3Client);
                    // Request a restore for objects that are not already being restored.
                    if (BooleanUtils.isNotTrue(objectMetadata.getOngoingRestore())) {
                        requestRestore.setKey(key);
                        s3Operations.restoreObject(requestRestore, s3Client);
                    }
                }
            } finally {
                s3Client.shutdown();
            }
        } catch (Exception e) {
            throw new IllegalStateException(String.format("Failed to initiate a restore request for \"%s\" key in \"%s\" bucket. Reason: %s", key, params.getS3BucketName(), e.getMessage()), e);
        }
    }
}
Also used : AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) GlacierJobParameters(com.amazonaws.services.s3.model.GlacierJobParameters) RestoreObjectRequest(com.amazonaws.services.s3.model.RestoreObjectRequest) File(java.io.File) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) MultiObjectDeleteException(com.amazonaws.services.s3.model.MultiObjectDeleteException) ObjectNotFoundException(org.finra.herd.model.ObjectNotFoundException) AmazonServiceException(com.amazonaws.AmazonServiceException) AmazonClientException(com.amazonaws.AmazonClientException) AmazonS3Exception(com.amazonaws.services.s3.model.AmazonS3Exception)

Example 29 with AmazonS3Client

use of com.amazonaws.services.s3.AmazonS3Client in project herd by FINRAOS.

the class S3DaoImpl method generateGetObjectPresignedUrl.

@Override
public String generateGetObjectPresignedUrl(String bucketName, String key, Date expiration, S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto) {
    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
    generatePresignedUrlRequest.setExpiration(expiration);
    AmazonS3Client s3 = getAmazonS3(s3FileTransferRequestParamsDto);
    try {
        return s3Operations.generatePresignedUrl(generatePresignedUrlRequest, s3).toString();
    } finally {
        s3.shutdown();
    }
}
Also used : AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) GeneratePresignedUrlRequest(com.amazonaws.services.s3.model.GeneratePresignedUrlRequest)

Example 30 with AmazonS3Client

use of com.amazonaws.services.s3.AmazonS3Client in project herd by FINRAOS.

the class S3DaoImpl method deleteDirectory.

@Override
public void deleteDirectory(final S3FileTransferRequestParamsDto params) {
    LOGGER.info("Deleting keys/key versions from S3... s3KeyPrefix=\"{}\" s3BucketName=\"{}\"", params.getS3KeyPrefix(), params.getS3BucketName());
    Assert.isTrue(!isRootKeyPrefix(params.getS3KeyPrefix()), "Deleting from root directory is not allowed.");
    try {
        // List S3 versions.
        List<DeleteObjectsRequest.KeyVersion> keyVersions = listVersions(params);
        LOGGER.info("Found keys/key versions in S3 for deletion. s3KeyCount={} s3KeyPrefix=\"{}\" s3BucketName=\"{}\"", keyVersions.size(), params.getS3KeyPrefix(), params.getS3BucketName());
        // In order to avoid a MalformedXML AWS exception, we send delete request only when we have any key versions to delete.
        if (!keyVersions.isEmpty()) {
            // Create an S3 client.
            AmazonS3Client s3Client = getAmazonS3(params);
            try {
                // Delete the key versions.
                deleteKeyVersions(s3Client, params.getS3BucketName(), keyVersions);
            } finally {
                s3Client.shutdown();
            }
        }
    } catch (AmazonClientException e) {
        throw new IllegalStateException(String.format("Failed to delete keys/key versions with prefix \"%s\" from bucket \"%s\". Reason: %s", params.getS3KeyPrefix(), params.getS3BucketName(), e.getMessage()), e);
    }
}
Also used : AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) AmazonClientException(com.amazonaws.AmazonClientException)

Aggregations

AmazonS3Client (com.amazonaws.services.s3.AmazonS3Client)109 Test (org.junit.Test)23 BasicAWSCredentials (com.amazonaws.auth.BasicAWSCredentials)20 AmazonClientException (com.amazonaws.AmazonClientException)18 ClientConfiguration (com.amazonaws.ClientConfiguration)18 ArrayList (java.util.ArrayList)14 AWSCredentialsProvider (com.amazonaws.auth.AWSCredentialsProvider)13 HashMap (java.util.HashMap)13 AmazonS3 (com.amazonaws.services.s3.AmazonS3)12 File (java.io.File)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)12 AWSCredentials (com.amazonaws.auth.AWSCredentials)11 PutObjectResult (com.amazonaws.services.s3.model.PutObjectResult)11 UploadPartRequest (com.amazonaws.services.s3.model.UploadPartRequest)11 AmazonS3Exception (com.amazonaws.services.s3.model.AmazonS3Exception)10 ObjectMetadata (com.amazonaws.services.s3.model.ObjectMetadata)10 S3Object (com.amazonaws.services.s3.model.S3Object)9 InternalEvent (com.nextdoor.bender.InternalEvent)9 TestContext (com.nextdoor.bender.aws.TestContext)9 IOException (java.io.IOException)9