Example usage for com.amazonaws.services.s3 AmazonS3 deleteObject

List of usage examples for com.amazonaws.services.s3 AmazonS3 deleteObject

Introduction

In this page you can find the example usage for com.amazonaws.services.s3 AmazonS3 deleteObject.

Prototype

public void deleteObject(String bucketName, String key) throws SdkClientException, AmazonServiceException;

Source Link

Document

Deletes the specified object in the specified bucket.

Usage

From source file:com.atlassian.localstack.sample.S3Sample.java

License:Open Source License

public static void runTest(AWSCredentials credentials) throws IOException {

    AmazonS3 s3 = new AmazonS3Client(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);//from  ww  w . j a  v  a2  s  . c  o  m
    s3.setEndpoint(LocalstackTestRunner.getEndpointS3());

    String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    String key = "MyObjectKey";

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon S3");
    System.out.println("===========================================\n");

    /*
     * Create a new S3 bucket - Amazon S3 bucket names are globally unique,
     * so once a bucket name has been taken by any user, you can't create
     * another bucket with that same name.
     *
     * You can optionally specify a location for your bucket if you want to
     * keep your data closer to your applications or users.
     */
    System.out.println("Creating bucket " + bucketName + "\n");
    s3.createBucket(bucketName);

    /*
     * List the buckets in your account
     */
    System.out.println("Listing buckets");
    for (Bucket bucket : s3.listBuckets()) {
        System.out.println(" - " + bucket.getName());
    }
    System.out.println();

    /*
     * Upload an object to your bucket - You can easily upload a file to
     * S3, or upload directly an InputStream if you know the length of
     * the data in the stream. You can also specify your own metadata
     * when uploading to S3, which allows you set a variety of options
     * like content-type and content-encoding, plus additional metadata
     * specific to your applications.
     */
    System.out.println("Uploading a new object to S3 from a file\n");
    s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

    /*
     * Download an object - When you download an object, you get all of
     * the object's metadata and a stream from which to read the contents.
     * It's important to read the contents of the stream as quickly as
     * possibly since the data is streamed directly from Amazon S3 and your
     * network connection will remain open until you read all the data or
     * close the input stream.
     *
     * GetObjectRequest also supports several other options, including
     * conditional downloading of objects based on modification times,
     * ETags, and selectively downloading a range of an object.
     */
    System.out.println("Downloading an object");
    S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
    System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
    displayTextInputStream(object.getObjectContent());

    /*
     * List objects in your bucket by prefix - There are many options for
     * listing the objects in your bucket.  Keep in mind that buckets with
     * many objects might truncate their results when listing their objects,
     * so be sure to check if the returned object listing is truncated, and
     * use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
     * additional results.
     */
    System.out.println("Listing objects");
    ObjectListing objectListing = s3
            .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
    for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
        System.out.println(" - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
    }
    System.out.println();

    /*
     * Delete an object - Unless versioning has been turned on for your bucket,
     * there is no way to undelete an object, so use caution when deleting objects.
     */
    System.out.println("Deleting an object\n");
    s3.deleteObject(bucketName, key);

    /*
     * Delete a bucket - A bucket must be completely empty before it can be
     * deleted, so remember to delete any objects from your buckets before
     * you try to delete them.
     */
    System.out.println("Deleting bucket " + bucketName + "\n");
    s3.deleteBucket(bucketName);
}

From source file:com.cloud.utils.S3Utils.java

License:Apache License

public static void deleteObject(final ClientOptions clientOptions, final String bucketName, final String key) {

    assert clientOptions != null;
    assert isNotBlank(bucketName);
    assert isNotBlank(key);

    final AmazonS3 client = acquireClient(clientOptions);

    client.deleteObject(bucketName, key);

}

From source file:com.cloud.utils.S3Utils.java

License:Apache License

public static void deleteDirectory(final ClientOptions clientOptions, final String bucketName,
        final String directoryName) {

    assert clientOptions != null;
    assert isNotBlank(bucketName);
    assert isNotBlank(directoryName);

    final AmazonS3 client = acquireClient(clientOptions);

    final List<S3ObjectSummary> objects = listDirectory(bucketName, directoryName, client);

    for (final S3ObjectSummary object : objects) {

        client.deleteObject(bucketName, object.getKey());

    }/*w w  w  .j  a va  2  s. c  om*/

    client.deleteObject(bucketName, directoryName);

}

From source file:com.cloud.utils.S3Utils.java

License:Apache License

public static boolean canReadWriteBucket(final ClientOptions clientOptions, final String bucketName) {

    assert clientOptions != null;
    assert isNotBlank(bucketName);

    try {/*from w  ww  . ja  v a  2  s. c om*/

        final AmazonS3 client = acquireClient(clientOptions);

        final String fileContent = "testing put and delete";
        final InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes());
        final String key = UUID.randomUUID().toString() + ".txt";

        final ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(fileContent.length());

        client.putObject(bucketName, key, inputStream, metadata);
        client.deleteObject(bucketName, key);

        return true;

    } catch (AmazonClientException e) {

        return false;

    }

}

From source file:com.dustindoloff.s3websitedeploy.Main.java

License:Apache License

private static boolean emptyBucket(final AmazonS3 s3Client, final String bucket) {
    final ListObjectsV2Request request = new ListObjectsV2Request();
    request.setBucketName(bucket);/*from w  w w  .j a va2s .com*/

    String continuationToken = null;
    ListObjectsV2Result result;
    do {
        request.setContinuationToken(continuationToken);
        result = s3Client.listObjectsV2(bucket);
        for (final S3ObjectSummary summary : result.getObjectSummaries()) {
            s3Client.deleteObject(bucket, summary.getKey());
        }

        continuationToken = result.getNextContinuationToken();
    } while (result.isTruncated());

    return true;
}

From source file:com.easarrive.aws.plugins.common.service.impl.S3Service.java

License:Open Source License

/**
 * {@inheritDoc}//from w ww .j av a 2s  . c  om
 */
@Override
public void deleteObject(AmazonS3 client, String bucketName, String key) {
    if (client == null) {
        return;
    } else if (StringUtil.isEmpty(bucketName)) {
        return;
    } else if (StringUtil.isEmpty(key)) {
        return;
    }
    if (client.doesObjectExist(bucketName, key)) {
        client.deleteObject(bucketName, key);
    }
}

From source file:com.emc.vipr.s3.sample._04_DeleteObject.java

License:Open Source License

public static void main(String[] args) throws Exception {
    // create the AWS S3 Client
    AmazonS3 s3 = AWSS3Factory.getS3Client();

    // retrieve the object value from user
    System.out.println("Enter the object key:");
    String key = new BufferedReader(new InputStreamReader(System.in)).readLine();

    // delete the object from the demo bucket
    s3.deleteObject(AWSS3Factory.S3_BUCKET, key);

    // print out key/value for validation
    System.out.println(String.format("object [%s/%s] deleted", AWSS3Factory.S3_BUCKET, key));
}

From source file:com.jfixby.scarabei.red.aws.test.S3Sample.java

License:Open Source License

public static void main(final String[] args) throws IOException {

    /*// w ww.  j  a v a 2  s .c o m
     * The ProfileCredentialsProvider will return your [default] credential profile by reading from the credentials file located
     * at (C:\\Users\\JCode\\.aws\\credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("default").getCredentials();
    } catch (final Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (C:\\Users\\%USERNAME%\\.aws\\credentials), and is in valid format.", e);
    }

    final AmazonS3 s3 = new AmazonS3Client(credentials);
    final Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    final String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    final String key = "MyObjectKey";

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon S3");
    System.out.println("===========================================\n");

    try {
        /*
         * Create a new S3 bucket - Amazon S3 bucket names are globally unique, so once a bucket name has been taken by any user,
         * you can't create another bucket with that same name.
         *
         * You can optionally specify a location for your bucket if you want to keep your data closer to your applications or
         * users.
         */
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (final Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        /*
         * Upload an object to your bucket - You can easily upload a file to S3, or upload directly an InputStream if you know
         * the length of the data in the stream. You can also specify your own metadata when uploading to S3, which allows you
         * set a variety of options like content-type and content-encoding, plus additional metadata specific to your
         * applications.
         */
        System.out.println("Uploading a new object to S3 from a file\n");
        s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        /*
         * Download an object - When you download an object, you get all of the object's metadata and a stream from which to read
         * the contents. It's important to read the contents of the stream as quickly as possibly since the data is streamed
         * directly from Amazon S3 and your network connection will remain open until you read all the data or close the input
         * stream.
         *
         * GetObjectRequest also supports several other options, including conditional downloading of objects based on
         * modification times, ETags, and selectively downloading a range of an object.
         */
        System.out.println("Downloading an object");
        final S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        /*
         * List objects in your bucket by prefix - There are many options for listing the objects in your bucket. Keep in mind
         * that buckets with many objects might truncate their results when listing their objects, so be sure to check if the
         * returned object listing is truncated, and use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
         * additional results.
         */
        System.out.println("Listing objects");
        final ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (final S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();

        /*
         * Delete an object - Unless versioning has been turned on for your bucket, there is no way to undelete an object, so use
         * caution when deleting objects.
         */
        System.out.println("Deleting an object\n");
        s3.deleteObject(bucketName, key);

        /*
         * Delete a bucket - A bucket must be completely empty before it can be deleted, so remember to delete any objects from
         * your buckets before you try to delete them.
         */
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    } catch (final AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon S3, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (final AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.mateusz.mateuszsqs.SQSConfig.java

public static void processFile(String key, AmazonS3 s3, String bucketName) throws IOException {
    System.out.println("Downloading an object");
    S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
    System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
    System.out.println("Deleting an object\n");
    s3.deleteObject(bucketName, key);
    System.out.println("Processing...");
    System.out.println("Uploading a new object to S3 from a file\n");
    InputStream changedStream = procesIamge(object.getObjectContent());
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(changedStream.available());
    metadata.setLastModified(new Date(System.currentTimeMillis()));
    s3.putObject(new PutObjectRequest(bucketName, key, changedStream, metadata));
}

From source file:com.springboot.demo.framework.aws.s3.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {

    /*/*w ww .j av  a 2s  . co m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials basicCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);

    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (~/.aws/credentials), and is in valid format.", e);
    }

    /*
     * Create S3 Client
     */
    AmazonS3 s3 = AmazonS3ClientBuilder.defaultClient();
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    String key = "MyObjectKey";

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon S3");
    System.out.println("===========================================\n");

    try {
        /*
         * Create a new S3 bucket - Amazon S3 bucket names are globally unique,
         * so once a bucket name has been taken by any user, you can't create
         * another bucket with that same name.
         *
         * You can optionally specify a location for your bucket if you want to
         * keep your data closer to your applications or users.
         */
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        /*
         * Upload an object to your bucket - You can easily upload a file to
         * S3, or upload directly an InputStream if you know the length of
         * the data in the stream. You can also specify your own metadata
         * when uploading to S3, which allows you set a variety of options
         * like content-type and content-encoding, plus additional metadata
         * specific to your applications.
         */
        System.out.println("Uploading a new object to S3 from a file\n");
        s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        /*
         * Returns an URL for the object stored in the specified bucket and  key
         */
        URL url = s3.getUrl(bucketName, key);
        System.out.println("upload file url : " + url.toString());

        /*
         * Download an object - When you download an object, you get all of
         * the object's metadata and a stream from which to read the contents.
         * It's important to read the contents of the stream as quickly as
         * possibly since the data is streamed directly from Amazon S3 and your
         * network connection will remain open until you read all the data or
         * close the input stream.
         *
         * GetObjectRequest also supports several other options, including
         * conditional downloading of objects based on modification times,
         * ETags, and selectively downloading a range of an object.
         */
        System.out.println("Downloading an object");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        /*
         * List objects in your bucket by prefix - There are many options for
         * listing the objects in your bucket.  Keep in mind that buckets with
         * many objects might truncate their results when listing their objects,
         * so be sure to check if the returned object listing is truncated, and
         * use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
         * additional results.
         */
        System.out.println("Listing objects");
        ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();

        /*
         * Delete an object - Unless versioning has been turned on for your bucket,
         * there is no way to undelete an object, so use caution when deleting objects.
         */
        System.out.println("Deleting an object\n");
        s3.deleteObject(bucketName, key);

        /*
         * Delete a bucket - A bucket must be completely empty before it can be
         * deleted, so remember to delete any objects from your buckets before
         * you try to delete them.
         */
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon S3, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}