Search in sources :

Example 6 with AbortMultipartUploadRequest

use of software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest in project gradle by gradle.

the class S3Client method putMultiPartObject.

private void putMultiPartObject(InputStream inputStream, Long contentLength, URI destination) {
    try {
        S3RegionalResource s3RegionalResource = new S3RegionalResource(destination);
        String bucketName = s3RegionalResource.getBucketName();
        String s3BucketKey = s3RegionalResource.getKey();
        configureClient(s3RegionalResource);
        List<PartETag> partETags = new ArrayList<>();
        InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, s3BucketKey).withCannedACL(CannedAccessControlList.BucketOwnerFullControl);
        InitiateMultipartUploadResult initResponse = amazonS3Client.initiateMultipartUpload(initRequest);
        try {
            long filePosition = 0;
            long partSize = s3ConnectionProperties.getPartSize();
            LOGGER.debug("Attempting to put resource:[{}] into s3 bucket [{}]", s3BucketKey, bucketName);
            for (int partNumber = 1; filePosition < contentLength; partNumber++) {
                partSize = Math.min(partSize, contentLength - filePosition);
                UploadPartRequest uploadPartRequest = new UploadPartRequest().withBucketName(bucketName).withKey(s3BucketKey).withUploadId(initResponse.getUploadId()).withPartNumber(partNumber).withPartSize(partSize).withInputStream(inputStream);
                partETags.add(amazonS3Client.uploadPart(uploadPartRequest).getPartETag());
                filePosition += partSize;
            }
            CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest(bucketName, s3BucketKey, initResponse.getUploadId(), partETags);
            amazonS3Client.completeMultipartUpload(completeRequest);
        } catch (AmazonClientException e) {
            amazonS3Client.abortMultipartUpload(new AbortMultipartUploadRequest(bucketName, s3BucketKey, initResponse.getUploadId()));
            throw e;
        }
    } catch (AmazonClientException e) {
        throw ResourceExceptions.putFailed(destination, e);
    }
}
Also used : InitiateMultipartUploadResult(com.amazonaws.services.s3.model.InitiateMultipartUploadResult) AmazonClientException(com.amazonaws.AmazonClientException) ArrayList(java.util.ArrayList) InitiateMultipartUploadRequest(com.amazonaws.services.s3.model.InitiateMultipartUploadRequest) UploadPartRequest(com.amazonaws.services.s3.model.UploadPartRequest) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) PartETag(com.amazonaws.services.s3.model.PartETag) CompleteMultipartUploadRequest(com.amazonaws.services.s3.model.CompleteMultipartUploadRequest)

Example 7 with AbortMultipartUploadRequest

use of software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest in project hippo by NHS-digital-website.

the class S3SdkConnectorTest method abortsS3MultipartUploadRequest_onChunkUploadFailure.

@Test
public void abortsS3MultipartUploadRequest_onChunkUploadFailure() throws Exception {
    // given
    final String contentType = newRandomString();
    final String uploadId = newRandomString();
    given(s3ObjectKeyGenerator.generateObjectKey(fileName)).willReturn(objectKey);
    final InitiateMultipartUploadResult result = mock(InitiateMultipartUploadResult.class);
    given(result.getUploadId()).willReturn(uploadId);
    given(s3.initiateMultipartUpload(any())).willReturn(result);
    final InputStream uploadedFileInputStream = mock(InputStream.class);
    final RuntimeException expectedCauseException = new RuntimeException(newRandomString());
    given(s3.uploadPart(any(UploadPartRequest.class))).willThrow(expectedCauseException);
    try {
        // when
        s3Connector.uploadFile(uploadedFileInputStream, fileName, contentType);
        // then
        fail("Exception was expected but none has been thrown.");
    } catch (final RuntimeException actualException) {
        // assert upload request - abort
        final ArgumentCaptor<AbortMultipartUploadRequest> abortMultipartUploadRequestArgumentCaptor = ArgumentCaptor.forClass(AbortMultipartUploadRequest.class);
        then(s3).should().abortMultipartUpload(abortMultipartUploadRequestArgumentCaptor.capture());
        final AbortMultipartUploadRequest actualAbortRequest = abortMultipartUploadRequestArgumentCaptor.getValue();
        assertThat("Request aborted with correct bucket name", actualAbortRequest.getBucketName(), is(bucketName));
        assertThat("Request aborted with correct object key", actualAbortRequest.getKey(), is(objectKey));
        assertThat("Request aborted with correct upload id", actualAbortRequest.getUploadId(), is(uploadId));
        // assert upload request - exception
        assertThat("Exception is thrown with correct message.", actualException.getMessage(), is("Failed to upload file " + objectKey));
        assertThat("Exception is thrown with correct cause.", actualException.getCause(), is(sameInstance(expectedCauseException)));
    }
}
Also used : InitiateMultipartUploadResult(com.amazonaws.services.s3.model.InitiateMultipartUploadResult) ArgumentCaptor(org.mockito.ArgumentCaptor) S3ObjectInputStream(com.amazonaws.services.s3.model.S3ObjectInputStream) InputStream(java.io.InputStream) UploadPartRequest(com.amazonaws.services.s3.model.UploadPartRequest) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) Test(org.junit.Test)

Example 8 with AbortMultipartUploadRequest

use of software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest in project hippo by NHS-digital-website.

the class S3SdkConnector method uploadFile.

@Override
public S3ObjectMetadata uploadFile(InputStream fileStream, String fileName, String contentType) {
    String objectKey = s3ObjectKeyGenerator.generateObjectKey(fileName);
    reportAction("Uploading S3 resource {}", objectKey);
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentType(contentType);
    // initialise multipart upload
    InitiateMultipartUploadResult initResult = s3.initiateMultipartUpload(new InitiateMultipartUploadRequest(bucketName, objectKey, metadata));
    // loop parts
    List<PartETag> partETags;
    try {
        partETags = uploadParts(fileStream, bucketName, objectKey, initResult.getUploadId());
    } catch (Exception ex) {
        final String errorMessage = "Failed to upload file " + objectKey;
        log.error(errorMessage, ex);
        s3.abortMultipartUpload(new AbortMultipartUploadRequest(bucketName, objectKey, initResult.getUploadId()));
        throw new RuntimeException(errorMessage, ex);
    }
    // finalise multipart upload
    s3.completeMultipartUpload(new CompleteMultipartUploadRequest(bucketName, objectKey, initResult.getUploadId(), partETags));
    // The above put request returns metadata object but it's empty,
    // hence the need for a separate call to fetch actual metadata.
    ObjectMetadata resultMetadata = s3.getObjectMetadata(bucketName, objectKey);
    reportAction("S3 resource uploaded {}", objectKey);
    return new S3ObjectMetadataImpl(resultMetadata, bucketName, objectKey);
}
Also used : InitiateMultipartUploadResult(com.amazonaws.services.s3.model.InitiateMultipartUploadResult) InitiateMultipartUploadRequest(com.amazonaws.services.s3.model.InitiateMultipartUploadRequest) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) PartETag(com.amazonaws.services.s3.model.PartETag) IOException(java.io.IOException) CompleteMultipartUploadRequest(com.amazonaws.services.s3.model.CompleteMultipartUploadRequest)

Example 9 with AbortMultipartUploadRequest

use of software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest in project camel by apache.

the class S3Producer method processMultiPart.

public void processMultiPart(final Exchange exchange) throws Exception {
    File filePayload = null;
    Object obj = exchange.getIn().getMandatoryBody();
    // Need to check if the message body is WrappedFile
    if (obj instanceof WrappedFile) {
        obj = ((WrappedFile<?>) obj).getFile();
    }
    if (obj instanceof File) {
        filePayload = (File) obj;
    } else {
        throw new InvalidArgumentException("aws-s3: MultiPart upload requires a File input.");
    }
    ObjectMetadata objectMetadata = determineMetadata(exchange);
    if (objectMetadata.getContentLength() == 0) {
        objectMetadata.setContentLength(filePayload.length());
    }
    final String keyName = determineKey(exchange);
    final InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(getConfiguration().getBucketName(), keyName, objectMetadata);
    String storageClass = determineStorageClass(exchange);
    if (storageClass != null) {
        initRequest.setStorageClass(StorageClass.fromValue(storageClass));
    }
    String cannedAcl = exchange.getIn().getHeader(S3Constants.CANNED_ACL, String.class);
    if (cannedAcl != null) {
        CannedAccessControlList objectAcl = CannedAccessControlList.valueOf(cannedAcl);
        initRequest.setCannedACL(objectAcl);
    }
    AccessControlList acl = exchange.getIn().getHeader(S3Constants.ACL, AccessControlList.class);
    if (acl != null) {
        // note: if cannedacl and acl are both specified the last one will be used. refer to
        // PutObjectRequest#setAccessControlList for more details
        initRequest.setAccessControlList(acl);
    }
    LOG.trace("Initiating multipart upload [{}] from exchange [{}]...", initRequest, exchange);
    final InitiateMultipartUploadResult initResponse = getEndpoint().getS3Client().initiateMultipartUpload(initRequest);
    final long contentLength = objectMetadata.getContentLength();
    final List<PartETag> partETags = new ArrayList<PartETag>();
    long partSize = getConfiguration().getPartSize();
    CompleteMultipartUploadResult uploadResult = null;
    long filePosition = 0;
    try {
        for (int part = 1; filePosition < contentLength; part++) {
            partSize = Math.min(partSize, contentLength - filePosition);
            UploadPartRequest uploadRequest = new UploadPartRequest().withBucketName(getConfiguration().getBucketName()).withKey(keyName).withUploadId(initResponse.getUploadId()).withPartNumber(part).withFileOffset(filePosition).withFile(filePayload).withPartSize(partSize);
            LOG.trace("Uploading part [{}] for {}", part, keyName);
            partETags.add(getEndpoint().getS3Client().uploadPart(uploadRequest).getPartETag());
            filePosition += partSize;
        }
        CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(getConfiguration().getBucketName(), keyName, initResponse.getUploadId(), partETags);
        uploadResult = getEndpoint().getS3Client().completeMultipartUpload(compRequest);
    } catch (Exception e) {
        getEndpoint().getS3Client().abortMultipartUpload(new AbortMultipartUploadRequest(getConfiguration().getBucketName(), keyName, initResponse.getUploadId()));
        throw e;
    }
    Message message = getMessageForResponse(exchange);
    message.setHeader(S3Constants.E_TAG, uploadResult.getETag());
    if (uploadResult.getVersionId() != null) {
        message.setHeader(S3Constants.VERSION_ID, uploadResult.getVersionId());
    }
    if (getConfiguration().isDeleteAfterWrite() && filePayload != null) {
        FileUtil.deleteFile(filePayload);
    }
}
Also used : CannedAccessControlList(com.amazonaws.services.s3.model.CannedAccessControlList) AccessControlList(com.amazonaws.services.s3.model.AccessControlList) InitiateMultipartUploadResult(com.amazonaws.services.s3.model.InitiateMultipartUploadResult) Message(org.apache.camel.Message) InitiateMultipartUploadRequest(com.amazonaws.services.s3.model.InitiateMultipartUploadRequest) ArrayList(java.util.ArrayList) UploadPartRequest(com.amazonaws.services.s3.model.UploadPartRequest) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) CompleteMultipartUploadResult(com.amazonaws.services.s3.model.CompleteMultipartUploadResult) CannedAccessControlList(com.amazonaws.services.s3.model.CannedAccessControlList) PartETag(com.amazonaws.services.s3.model.PartETag) Endpoint(org.apache.camel.Endpoint) InvalidArgumentException(com.amazonaws.services.cloudfront.model.InvalidArgumentException) InvalidArgumentException(com.amazonaws.services.cloudfront.model.InvalidArgumentException) WrappedFile(org.apache.camel.WrappedFile) File(java.io.File) WrappedFile(org.apache.camel.WrappedFile) ObjectMetadata(com.amazonaws.services.s3.model.ObjectMetadata) CompleteMultipartUploadRequest(com.amazonaws.services.s3.model.CompleteMultipartUploadRequest)

Example 10 with AbortMultipartUploadRequest

use of software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest in project Singularity by HubSpot.

the class SingularityS3Uploader method multipartUpload.

private void multipartUpload(String key, File file, ObjectMetadata objectMetadata, Optional<StorageClass> maybeStorageClass) throws Exception {
    List<PartETag> partETags = new ArrayList<>();
    InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, key, objectMetadata);
    if (maybeStorageClass.isPresent()) {
        initRequest.setStorageClass(maybeStorageClass.get());
    }
    InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest);
    long contentLength = file.length();
    long partSize = configuration.getUploadPartSize();
    try {
        long filePosition = 0;
        for (int i = 1; filePosition < contentLength; i++) {
            partSize = Math.min(partSize, (contentLength - filePosition));
            UploadPartRequest uploadRequest = new UploadPartRequest().withBucketName(bucketName).withKey(key).withUploadId(initResponse.getUploadId()).withPartNumber(i).withFileOffset(filePosition).withFile(file).withPartSize(partSize);
            partETags.add(s3Client.uploadPart(uploadRequest).getPartETag());
            filePosition += partSize;
        }
        CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest(bucketName, key, initResponse.getUploadId(), partETags);
        s3Client.completeMultipartUpload(completeRequest);
    } catch (Exception e) {
        s3Client.abortMultipartUpload(new AbortMultipartUploadRequest(bucketName, key, initResponse.getUploadId()));
        Throwables.propagate(e);
    }
}
Also used : InitiateMultipartUploadResult(com.amazonaws.services.s3.model.InitiateMultipartUploadResult) ArrayList(java.util.ArrayList) InitiateMultipartUploadRequest(com.amazonaws.services.s3.model.InitiateMultipartUploadRequest) UploadPartRequest(com.amazonaws.services.s3.model.UploadPartRequest) AbortMultipartUploadRequest(com.amazonaws.services.s3.model.AbortMultipartUploadRequest) PartETag(com.amazonaws.services.s3.model.PartETag) AmazonS3Exception(com.amazonaws.services.s3.model.AmazonS3Exception) CompleteMultipartUploadRequest(com.amazonaws.services.s3.model.CompleteMultipartUploadRequest)

Aggregations

AbortMultipartUploadRequest (com.amazonaws.services.s3.model.AbortMultipartUploadRequest)14 CompleteMultipartUploadRequest (com.amazonaws.services.s3.model.CompleteMultipartUploadRequest)9 InitiateMultipartUploadRequest (com.amazonaws.services.s3.model.InitiateMultipartUploadRequest)9 InitiateMultipartUploadResult (com.amazonaws.services.s3.model.InitiateMultipartUploadResult)9 PartETag (com.amazonaws.services.s3.model.PartETag)9 UploadPartRequest (com.amazonaws.services.s3.model.UploadPartRequest)8 ArrayList (java.util.ArrayList)7 AmazonClientException (com.amazonaws.AmazonClientException)5 ObjectMetadata (com.amazonaws.services.s3.model.ObjectMetadata)5 IOException (java.io.IOException)4 CompleteMultipartUploadResult (com.amazonaws.services.s3.model.CompleteMultipartUploadResult)3 UploadPartResult (com.amazonaws.services.s3.model.UploadPartResult)3 AmazonS3 (com.amazonaws.services.s3.AmazonS3)2 AmazonS3Exception (com.amazonaws.services.s3.model.AmazonS3Exception)2 CannedAccessControlList (com.amazonaws.services.s3.model.CannedAccessControlList)2 ListMultipartUploadsRequest (com.amazonaws.services.s3.model.ListMultipartUploadsRequest)2 MultipartUpload (com.amazonaws.services.s3.model.MultipartUpload)2 MultipartUploadListing (com.amazonaws.services.s3.model.MultipartUploadListing)2 AmazonServiceException (com.amazonaws.AmazonServiceException)1 SdkClientException (com.amazonaws.SdkClientException)1