com.amazonaws.services.s3.model.ListMultipartUploadsRequest Java Examples

The following examples show how to use com.amazonaws.services.s3.model.ListMultipartUploadsRequest. 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: TestPutS3Object.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void prepareTest(String filename) {
    runner.setProperty(PutS3Object.REGION, "ap-northeast-1");
    runner.setProperty(PutS3Object.BUCKET, "test-bucket");
    runner.assertValid();

    Map<String, String> ffAttributes = new HashMap<>();
    ffAttributes.put("filename", filename);
    ffAttributes.put("tagS3PII", "true");
    runner.enqueue("Test Content", ffAttributes);

    PutObjectResult putObjectResult = new PutObjectResult();
    putObjectResult.setExpirationTime(new Date());
    putObjectResult.setMetadata(new ObjectMetadata());
    putObjectResult.setVersionId("test-version");
    putObjectResult.setETag("test-etag");

    Mockito.when(mockS3Client.putObject(Mockito.any(PutObjectRequest.class))).thenReturn(putObjectResult);

    MultipartUploadListing uploadListing = new MultipartUploadListing();
    Mockito.when(mockS3Client.listMultipartUploads(Mockito.any(ListMultipartUploadsRequest.class))).thenReturn(uploadListing);
}
 
Example #2
Source File: S3Backuper.java    From cassandra-backup with Apache License 2.0 5 votes vote down vote up
private void cleanupMultipartUploads() {
    final AmazonS3 s3Client = transferManager.getAmazonS3Client();

    final Instant yesterdayInstant = ZonedDateTime.now().minusDays(1).toInstant();

    logger.info("Cleaning up multipart uploads older than {}.", yesterdayInstant);

    final ListMultipartUploadsRequest listMultipartUploadsRequest = new ListMultipartUploadsRequest(request.storageLocation.bucket)
        .withPrefix(request.storageLocation.clusterId + "/" + request.storageLocation.datacenterId);

    while (true) {
        final MultipartUploadListing multipartUploadListing = s3Client.listMultipartUploads(listMultipartUploadsRequest);

        multipartUploadListing.getMultipartUploads().stream()
            .filter(u -> u.getInitiated().toInstant().isBefore(yesterdayInstant))
            .forEach(u -> {
                logger.info("Aborting multi-part upload for key \"{}\" initiated on {}", u.getKey(), u.getInitiated().toInstant());

                try {
                    s3Client.abortMultipartUpload(new AbortMultipartUploadRequest(request.storageLocation.bucket, u.getKey(), u.getUploadId()));

                } catch (final AmazonClientException e) {
                    logger.error("Failed to abort multipart upload for key \"{}\".", u.getKey(), e);
                }
            });

        if (!multipartUploadListing.isTruncated()) {
            break;
        }

        listMultipartUploadsRequest
            .withKeyMarker(multipartUploadListing.getKeyMarker())
            .withUploadIdMarker(multipartUploadListing.getUploadIdMarker());
    }
}
 
Example #3
Source File: PutS3Object.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
protected boolean localUploadExistsInS3(final AmazonS3Client s3, final String bucket, final MultipartState localState) {
    ListMultipartUploadsRequest listRequest = new ListMultipartUploadsRequest(bucket);
    MultipartUploadListing listing = s3.listMultipartUploads(listRequest);
    for (MultipartUpload upload : listing.getMultipartUploads()) {
        if (upload.getUploadId().equals(localState.getUploadId())) {
            return true;
        }
    }
    return false;
}
 
Example #4
Source File: MockS3OperationsImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc} <p/> <p> Since a multipart upload in progress does not exist when in-memory, this method simply returns a preconfigured list. </p> <p>
 * Returns a mock {@link MultipartUploadListing} based on the parameters and hints provided. By default returns a mock listing as defiend by {@link
 * #getMultipartUploadListing()}. </p> <p> This operation takes the following hints when suffixed in listMultipartUploadsRequest.bucketName: <dl> <p/>
 * <dt>MOCK_S3_BUCKET_NAME_SERVICE_EXCEPTION</dt> <dd>Throws a AmazonServiceException</dd> <p/> <dt>MOCK_S3_BUCKET_NAME_TRUNCATED_MULTIPART_LISTING</dt>
 * <dd>Returns the listing as if it is truncated. See below for details.</dd> <p/> </dl> </p>
 */
@Override
public MultipartUploadListing listMultipartUploads(ListMultipartUploadsRequest listMultipartUploadsRequest, AmazonS3 s3Client)
{
    if (listMultipartUploadsRequest.getBucketName().equals(MOCK_S3_BUCKET_NAME_SERVICE_EXCEPTION))
    {
        throw new AmazonServiceException(null);
    }
    else if (listMultipartUploadsRequest.getBucketName().equals(MOCK_S3_BUCKET_NAME_TRUNCATED_MULTIPART_LISTING))
    {
        MultipartUploadListing multipartUploadListing = getMultipartUploadListing();

        // If listing request does not have upload ID marker set, mark the listing as truncated - this is done to truncate the multipart listing just once.
        if (listMultipartUploadsRequest.getUploadIdMarker() == null)
        {
            multipartUploadListing.setNextUploadIdMarker("TEST_UPLOAD_MARKER_ID");
            multipartUploadListing.setNextKeyMarker("TEST_KEY_MARKER_ID");
            multipartUploadListing.setTruncated(true);
        }

        return multipartUploadListing;
    }
    else
    {
        return getMultipartUploadListing();
    }
}
 
Example #5
Source File: PutS3Object.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected boolean localUploadExistsInS3(final AmazonS3Client s3, final String bucket, final MultipartState localState) {
    ListMultipartUploadsRequest listRequest = new ListMultipartUploadsRequest(bucket);
    MultipartUploadListing listing = s3.listMultipartUploads(listRequest);

    for (MultipartUpload upload : listing.getMultipartUploads()) {
        if (upload.getUploadId().equals(localState.getUploadId())) {
            return true;
        }
    }
    return false;
}
 
Example #6
Source File: PutS3Object.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected MultipartUploadListing getS3AgeoffListAndAgeoffLocalState(final ProcessContext context, final AmazonS3Client s3, final long now) {
    final long ageoff_interval = context.getProperty(MULTIPART_S3_AGEOFF_INTERVAL).asTimePeriod(TimeUnit.MILLISECONDS);
    final String bucket = context.getProperty(BUCKET).evaluateAttributeExpressions().getValue();
    final Long maxAge = context.getProperty(MULTIPART_S3_MAX_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
    final long ageCutoff = now - maxAge;

    final List<MultipartUpload> ageoffList = new ArrayList<>();
    if ((lastS3AgeOff.get() < now - ageoff_interval) && s3BucketLock.tryLock()) {
        try {

            ListMultipartUploadsRequest listRequest = new ListMultipartUploadsRequest(bucket);
            MultipartUploadListing listing = s3.listMultipartUploads(listRequest);
            for (MultipartUpload upload : listing.getMultipartUploads()) {
                long uploadTime = upload.getInitiated().getTime();
                if (uploadTime < ageCutoff) {
                    ageoffList.add(upload);
                }
            }

            // ageoff any local state
            ageoffLocalState(ageCutoff);
            lastS3AgeOff.set(System.currentTimeMillis());
        } catch(AmazonClientException e) {
            if (e instanceof AmazonS3Exception
                    && ((AmazonS3Exception)e).getStatusCode() == 403
                    && ((AmazonS3Exception) e).getErrorCode().equals("AccessDenied")) {
                getLogger().warn("AccessDenied checking S3 Multipart Upload list for {}: {} " +
                        "** The configured user does not have the s3:ListBucketMultipartUploads permission " +
                        "for this bucket, S3 ageoff cannot occur without this permission.  Next ageoff check " +
                        "time is being advanced by interval to prevent checking on every upload **",
                        new Object[]{bucket, e.getMessage()});
                lastS3AgeOff.set(System.currentTimeMillis());
            } else {
                getLogger().error("Error checking S3 Multipart Upload list for {}: {}",
                        new Object[]{bucket, e.getMessage()});
            }
        } finally {
            s3BucketLock.unlock();
        }
    }
    MultipartUploadListing result = new MultipartUploadListing();
    result.setBucketName(bucket);
    result.setMultipartUploads(ageoffList);
    return result;
}
 
Example #7
Source File: ITPutS3Object.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public MultipartUploadListing listMultipartUploads(ListMultipartUploadsRequest listMultipartUploadsRequest)
        throws AmazonClientException, AmazonServiceException {
    return listing;
}
 
Example #8
Source File: S3OperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public MultipartUploadListing listMultipartUploads(ListMultipartUploadsRequest listMultipartUploadsRequest, AmazonS3 s3Client)
{
    return s3Client.listMultipartUploads(listMultipartUploadsRequest);
}
 
Example #9
Source File: S3DaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public int abortMultipartUploads(S3FileTransferRequestParamsDto params, Date thresholdDate)
{
    // Create an Amazon S3 client.
    AmazonS3Client s3Client = getAmazonS3(params);
    int abortedMultipartUploadsCount = 0;

    try
    {
        // List upload markers. Null implies initial list request.
        String uploadIdMarker = null;
        String keyMarker = null;

        boolean truncated;
        do
        {
            // Create the list multipart request, optionally using the last markers.
            ListMultipartUploadsRequest request = new ListMultipartUploadsRequest(params.getS3BucketName());
            request.setUploadIdMarker(uploadIdMarker);
            request.setKeyMarker(keyMarker);

            // Request the multipart upload listing.
            MultipartUploadListing uploadListing = s3Operations.listMultipartUploads(TransferManager.appendSingleObjectUserAgent(request), s3Client);

            for (MultipartUpload upload : uploadListing.getMultipartUploads())
            {
                if (upload.getInitiated().compareTo(thresholdDate) < 0)
                {
                    // Abort the upload.
                    s3Operations.abortMultipartUpload(TransferManager
                            .appendSingleObjectUserAgent(new AbortMultipartUploadRequest(params.getS3BucketName(), upload.getKey(), upload.getUploadId())),
                        s3Client);

                    // Log the information about the aborted multipart upload.
                    LOGGER.info("Aborted S3 multipart upload. s3Key=\"{}\" s3BucketName=\"{}\" s3MultipartUploadInitiatedDate=\"{}\"", upload.getKey(),
                        params.getS3BucketName(), upload.getInitiated());

                    // Increment the counter.
                    abortedMultipartUploadsCount++;
                }
            }

            // Determine whether there are more uploads to list.
            truncated = uploadListing.isTruncated();
            if (truncated)
            {
                // Record the list markers.
                uploadIdMarker = uploadListing.getNextUploadIdMarker();
                keyMarker = uploadListing.getNextKeyMarker();
            }
        }
        while (truncated);
    }
    finally
    {
        // Shutdown the Amazon S3 client instance to release resources.
        s3Client.shutdown();
    }

    return abortedMultipartUploadsCount;
}
 
Example #10
Source File: S3DaoTest.java    From herd with Apache License 2.0 4 votes vote down vote up
@Test
public void testAbortMultipartUploadsAssertTruncatedResult()
{
    S3Operations originalS3Operations = (S3Operations) ReflectionTestUtils.getField(s3Dao, "s3Operations");
    S3Operations mockS3Operations = mock(S3Operations.class);
    ReflectionTestUtils.setField(s3Dao, "s3Operations", mockS3Operations);

    try
    {
        String s3BucketName = "s3BucketName";
        String uploadKey = "uploadKey";
        String uploadId = "uploadId";
        Date uploadInitiated = new Date(0);

        S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
        s3FileTransferRequestParamsDto.setS3BucketName(s3BucketName);
        Date thresholdDate = new Date(1);

        when(mockS3Operations.listMultipartUploads(any(), any())).then(new Answer<MultipartUploadListing>()
        {
            @Override
            public MultipartUploadListing answer(InvocationOnMock invocation) throws Throwable
            {
                ListMultipartUploadsRequest listMultipartUploadsRequest = invocation.getArgument(0);
                String keyMarker = listMultipartUploadsRequest.getKeyMarker();
                String uploadIdMarker = listMultipartUploadsRequest.getUploadIdMarker();

                MultipartUploadListing multipartUploadListing = new MultipartUploadListing();
                if (keyMarker == null || uploadIdMarker == null)
                {
                    multipartUploadListing.setNextKeyMarker("nextKeyMarker");
                    multipartUploadListing.setNextUploadIdMarker("nextUploadIdMarker");
                    multipartUploadListing.setTruncated(true);
                }
                else
                {
                    assertEquals("nextKeyMarker", keyMarker);
                    assertEquals("nextUploadIdMarker", uploadIdMarker);

                    MultipartUpload multipartUpload = new MultipartUpload();
                    multipartUpload.setUploadId(uploadId);
                    multipartUpload.setKey(uploadKey);
                    multipartUpload.setInitiated(uploadInitiated);
                    multipartUploadListing.getMultipartUploads().add(multipartUpload);
                }
                return multipartUploadListing;
            }
        });

        assertEquals(1, s3Dao.abortMultipartUploads(s3FileTransferRequestParamsDto, thresholdDate));

        // Assert listMultipartUploads() is called twice due to truncation
        verify(mockS3Operations, times(2)).listMultipartUploads(any(), any());

        /*
         * Assert that S3Operations.abortMultipartUpload is called exactly ONCE with arguments matching the given ArgumentMatcher
         */
        verify(mockS3Operations).abortMultipartUpload(argThat(
            argument -> Objects.equal(s3BucketName, argument.getBucketName()) && Objects.equal(uploadKey, argument.getKey()) &&
                Objects.equal(uploadId, argument.getUploadId())), any());

        // Assert that no other interactions occur with the mock
        verifyNoMoreInteractions(mockS3Operations);
    }
    finally
    {
        ReflectionTestUtils.setField(s3Dao, "s3Operations", originalS3Operations);
    }
}
 
Example #11
Source File: DummyS3Client.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** Unsupported Operation. */
@Override public MultipartUploadListing listMultipartUploads(
    ListMultipartUploadsRequest req) throws SdkClientException {
    throw new UnsupportedOperationException("Operation not supported");
}
 
Example #12
Source File: AwsSdkTest.java    From s3proxy with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultipartUploadAbort() throws Exception {
    String blobName = "multipart-upload-abort";
    ByteSource byteSource = TestUtils.randomByteSource().slice(
            0, MINIMUM_MULTIPART_SIZE);

    InitiateMultipartUploadResult result = client.initiateMultipartUpload(
            new InitiateMultipartUploadRequest(containerName, blobName));

    // TODO: google-cloud-storage and openstack-swift cannot list multipart
    // uploads
    MultipartUploadListing multipartListing = client.listMultipartUploads(
            new ListMultipartUploadsRequest(containerName));
    if (blobStoreType.equals("azureblob")) {
        // Azure does not create a manifest during initiate multi-part
        // upload.  Instead the first part creates this.
        assertThat(multipartListing.getMultipartUploads()).isEmpty();
    } else {
        assertThat(multipartListing.getMultipartUploads()).hasSize(1);
    }

    PartListing partListing = client.listParts(new ListPartsRequest(
            containerName, blobName, result.getUploadId()));
    assertThat(partListing.getParts()).isEmpty();

    client.uploadPart(new UploadPartRequest()
            .withBucketName(containerName)
            .withKey(blobName)
            .withUploadId(result.getUploadId())
            .withPartNumber(1)
            .withPartSize(byteSource.size())
            .withInputStream(byteSource.openStream()));

    multipartListing = client.listMultipartUploads(
            new ListMultipartUploadsRequest(containerName));
    assertThat(multipartListing.getMultipartUploads()).hasSize(1);

    partListing = client.listParts(new ListPartsRequest(
            containerName, blobName, result.getUploadId()));
    assertThat(partListing.getParts()).hasSize(1);

    client.abortMultipartUpload(new AbortMultipartUploadRequest(
            containerName, blobName, result.getUploadId()));

    multipartListing = client.listMultipartUploads(
            new ListMultipartUploadsRequest(containerName));
    if (blobStoreType.equals("azureblob")) {
        // Azure does not support explicit abort.  It automatically
        // removes incomplete multi-part uploads after 7 days.
        assertThat(multipartListing.getMultipartUploads()).hasSize(1);
    } else {
        assertThat(multipartListing.getMultipartUploads()).isEmpty();
    }

    ObjectListing listing = client.listObjects(containerName);
    assertThat(listing.getObjectSummaries()).isEmpty();
}
 
Example #13
Source File: PutS3Object.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected MultipartUploadListing getS3AgeoffListAndAgeoffLocalState(final ProcessContext context, final AmazonS3Client s3, final long now, String bucket) {
    final long ageoff_interval = context.getProperty(MULTIPART_S3_AGEOFF_INTERVAL).asTimePeriod(TimeUnit.MILLISECONDS);
    final Long maxAge = context.getProperty(MULTIPART_S3_MAX_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
    final long ageCutoff = now - maxAge;

    final List<MultipartUpload> ageoffList = new ArrayList<>();
    if ((lastS3AgeOff.get() < now - ageoff_interval) && s3BucketLock.tryLock()) {
        try {

            ListMultipartUploadsRequest listRequest = new ListMultipartUploadsRequest(bucket);
            MultipartUploadListing listing = s3.listMultipartUploads(listRequest);
            for (MultipartUpload upload : listing.getMultipartUploads()) {
                long uploadTime = upload.getInitiated().getTime();
                if (uploadTime < ageCutoff) {
                    ageoffList.add(upload);
                }
            }

            // ageoff any local state
            ageoffLocalState(ageCutoff);
            lastS3AgeOff.set(System.currentTimeMillis());
        } catch(AmazonClientException e) {
            if (e instanceof AmazonS3Exception
                    && ((AmazonS3Exception)e).getStatusCode() == 403
                    && ((AmazonS3Exception) e).getErrorCode().equals("AccessDenied")) {
                getLogger().warn("AccessDenied checking S3 Multipart Upload list for {}: {} " +
                        "** The configured user does not have the s3:ListBucketMultipartUploads permission " +
                        "for this bucket, S3 ageoff cannot occur without this permission.  Next ageoff check " +
                        "time is being advanced by interval to prevent checking on every upload **",
                        new Object[]{bucket, e.getMessage()});
                lastS3AgeOff.set(System.currentTimeMillis());
            } else {
                getLogger().error("Error checking S3 Multipart Upload list for {}: {}",
                        new Object[]{bucket, e.getMessage()});
            }
        } finally {
            s3BucketLock.unlock();
        }
    }
    MultipartUploadListing result = new MultipartUploadListing();
    result.setBucketName(bucket);
    result.setMultipartUploads(ageoffList);
    return result;
}
 
Example #14
Source File: ITPutS3Object.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public MultipartUploadListing listMultipartUploads(ListMultipartUploadsRequest listMultipartUploadsRequest)
        throws AmazonClientException, AmazonServiceException {
    return listing;
}
 
Example #15
Source File: AmazonS3Mock.java    From Scribengin with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public MultipartUploadListing listMultipartUploads(ListMultipartUploadsRequest request) throws AmazonClientException,
    AmazonServiceException {
  // TODO Auto-generated method stub
  return null;
}
 
Example #16
Source File: S3Operations.java    From herd with Apache License 2.0 2 votes vote down vote up
/**
 * Lists in-progress multipart uploads. An in-progress multipart upload is a multipart upload that has been initiated, but has not yet been completed or
 * aborted. This operation returns at most 1,000 multipart uploads in the response by default.
 *
 * @param listMultipartUploadsRequest the request object that specifies all the parameters of this operation
 * @param s3Client the {@link AmazonS3} implementation to use
 *
 * @return the listing of multipart uploads from Amazon S3
 */
public MultipartUploadListing listMultipartUploads(ListMultipartUploadsRequest listMultipartUploadsRequest, AmazonS3 s3Client);