Example usage for com.amazonaws.services.s3.model S3Object getObjectContent

List of usage examples for com.amazonaws.services.s3.model S3Object getObjectContent

Introduction

In this page you can find the example usage for com.amazonaws.services.s3.model S3Object getObjectContent.

Prototype

public S3ObjectInputStream getObjectContent() 

Source Link

Document

Gets the input stream containing the contents of this object.

Usage

From source file:aws.example.s3.GetObject.java

License:Open Source License

public static void main(String[] args) {
    final String USAGE = "\n" + "To run this example, supply the name of an S3 bucket and object to\n"
            + "download from it.\n" + "\n" + "Ex: GetObject <bucketname> <filename>\n";

    if (args.length < 2) {
        System.out.println(USAGE);
        System.exit(1);//from   w  ww . ja va  2s.co m
    }

    String bucket_name = args[0];
    String key_name = args[1];

    System.out.format("Downloading %s from S3 bucket %s...\n", key_name, bucket_name);
    final AmazonS3 s3 = new AmazonS3Client();
    try {
        S3Object o = s3.getObject(bucket_name, key_name);
        S3ObjectInputStream s3is = o.getObjectContent();
        FileOutputStream fos = new FileOutputStream(new File(key_name));
        byte[] read_buf = new byte[1024];
        int read_len = 0;
        while ((read_len = s3is.read(read_buf)) > 0) {
            fos.write(read_buf, 0, read_len);
        }
        s3is.close();
        fos.close();
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    } catch (FileNotFoundException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
    System.out.println("Done!");
}

From source file:aws.sample.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*// w ww. jav  a2s . co m
     * Important: Be sure to fill in your AWS access credentials in the AwsCredentials.properties file before you try to run this sample. http://aws.amazon.com/security-credentials
     */
    AmazonS3 s3 = new AmazonS3Client(
            new PropertiesCredentials(S3Sample.class.getResourceAsStream("/AwsCredentials.properties")));

    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()));

        /*
         * 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());
    }
}

From source file:br.com.g2.aws.swf.SimpleStoreActivitiesS3Impl.java

License:Open Source License

/**
 * /*  w w w  .j  av a  2  s .c  om*/
 * @param bucketName
 *          Name of S3 bucket
 * @param remoteName
 *          Key to use for uploaded S3 object
 * @param localName
 *          Name of the file locally
 * @param toBox
 *          This is an output parameter here. Used to communicate the name of
 *          the box that runs download activity
 * @return A Value object
 * @throws IOException
 */

private String downloadFileFromS3(String bucketName, String remoteName, String localName) throws IOException {
    System.out.println("downloadFileFromS3 begin remoteName=" + remoteName + ", localName=" + localName);
    FileOutputStream f = new FileOutputStream(localName);
    try {
        S3Object obj = s3Client.getObject(bucketName, remoteName);
        InputStream inputStream = obj.getObjectContent();
        long totalSize = obj.getObjectMetadata().getContentLength();

        try {
            long totalRead = 0;
            int read = 0;
            byte[] bytes = new byte[1024];
            long lastHeartbeatTime = System.currentTimeMillis();
            while ((read = inputStream.read(bytes)) != -1) {
                totalRead += read;
                f.write(bytes, 0, read);
                int progress = (int) (totalRead / totalSize * 100);
                lastHeartbeatTime = heartbeat(lastHeartbeatTime, progress);
            }
        } finally {
            inputStream.close();
        }
    } finally {
        f.close();
    }
    // Return hostname file was downloaded to
    System.out.println("downloadFileFromS3 done");
    return hostSpecificTaskList;
}

From source file:br.com.tamandua.aws.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*//from ww w  .  ja  v a  2  s.  c o  m
     * Important: Be sure to fill in your AWS access credentials in the
     *            AwsCredentials.properties file before you try to run this
     *            sample.
     * http://aws.amazon.com/security-credentials
     */
    AmazonS3 s3 = new AmazonS3Client(
            new PropertiesCredentials(S3Sample.class.getResourceAsStream("AwsCredentials.properties")));

    String bucketName = "test-bucket-everton-" + UUID.randomUUID();
    String key = "somekey";

    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()));

        /*
         * 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("some"));
        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());
    }
}

From source file:br.com.unb.aws.client.S3ClientV1.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*/*from www . j av a2s . c o  m*/
     * Create your credentials file at ~/.aws/credentials (C:\Users\USER_NAME\.aws\credentials for Windows users) 
     * and save the following lines after replacing the underlined values with your own.
     *
     * [default]
     * aws_access_key_id = YOUR_ACCESS_KEY_ID
     * aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
     */

    AmazonS3 s3 = new AmazonS3Client();
    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()));

        /*
         * 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());
    }
}

From source file:br.unb.bionimbuz.storage.bucket.methods.CloudMethodsAmazonGoogle.java

@Override
public void StorageDownloadFile(BioBucket bucket, String bucketPath, String localPath, String fileName)
        throws Exception {

    switch (bucket.getProvider()) {
    case AMAZON: {

        s3client.setEndpoint(bucket.getEndPoint());
        S3Object object = s3client
                .getObject(new GetObjectRequest(bucket.getName(), bucketPath.substring(1) + fileName));
        InputStream objectData = object.getObjectContent();
        if (!(new File(localPath + fileName)).exists()) {
            Files.copy(objectData, Paths.get(localPath + fileName));
        }//from  ww w . j  ava2  s. c  om
        objectData.close();

        break;
    }
    case GOOGLE: {

        String command = gcloudFolder + "gsutil cp gs://" + bucket.getName() + bucketPath + fileName + " "
                + localPath + fileName;
        ExecCommand(command);

        break;
    }
    default: {
        throw new Exception("Provedor incorreto!");
    }
    }
}

From source file:br.unb.cic.bionimbuz.services.storage.bucket.methods.CloudMethodsAmazonGoogle.java

@Override
public void StorageDownloadFile(BioBucket bucket, String bucketPath, String localPath, String fileName)
        throws Exception {

    switch (bucket.getProvider()) {
    case AMAZON: {

        s3client.setEndpoint(bucket.getEndPoint());
        final S3Object object = s3client
                .getObject(new GetObjectRequest(bucket.getName(), bucketPath.substring(1) + fileName));
        final InputStream objectData = object.getObjectContent();
        Files.copy(objectData, Paths.get(localPath + fileName));
        objectData.close();/*  w  ww  .  j ava 2  s .com*/

        break;
    }
    case GOOGLE: {

        final String command = gcloudFolder + "gsutil cp gs://" + bucket.getName() + bucketPath + fileName + " "
                + localPath + fileName;
        ExecCommand(command);

        break;
    }
    default: {
        throw new Exception("Provedor incorreto!");
    }
    }
}

From source file:br.unb.cic.bionimbuz.storage.bucket.methods.CloudMethodsAmazonGoogle.java

@Override
public void StorageDownloadFile(BioBucket bucket, String bucketPath, String localPath, String fileName)
        throws Exception {

    switch (bucket.getProvider()) {
    case AMAZON: {

        s3client.setEndpoint(bucket.getEndPoint());
        S3Object object = s3client
                .getObject(new GetObjectRequest(bucket.getName(), bucketPath.substring(1) + fileName));
        InputStream objectData = object.getObjectContent();
        Files.copy(objectData, Paths.get(localPath + fileName));
        objectData.close();//w  w  w . j  ava 2  s  .c o  m

        break;
    }
    case GOOGLE: {

        String command = gcloudFolder + "gsutil cp gs://" + bucket.getName() + bucketPath + fileName + " "
                + localPath + fileName;
        ExecCommand(command);

        break;
    }
    default: {
        throw new Exception("Provedor incorreto!");
    }
    }
}

From source file:ch.admin.isb.hermes5.persistence.s3.S3RemoteAdapter.java

License:Apache License

@Override
public byte[] readFile(String key) {
    try {/*w w w  . j  av  a2s  .  com*/
        S3Object s3Object = s3.getObject(bucketName.getStringValue(), key);
        if (s3Object == null) {
            return null;
        }
        byte[] file = IOUtil.readToByteArray(s3Object.getObjectContent());
        return file;
    } catch (Exception e) {
        return null;
    }
}

From source file:ch.hesso.master.sweetcity.utils.PictureUtils.java

License:Apache License

public static InputStream getPicture(Key key) {
    if (key == null)
        return null;

    try {//from ww w .jav  a 2 s  . com
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol(Protocol.HTTP);
        AmazonS3 s3Connection = new AmazonS3Client(AWS_CREDENTIALS, clientConfig);
        s3Connection.setEndpoint(ConstantsAWS.S3_END_POINT);

        S3Object obj = s3Connection.getObject(ConstantsAWS.S3_BUCKET_NAME, key.toString());
        return obj.getObjectContent();
    } catch (Exception e) {
        Log.d(Constants.PROJECT_NAME, e.toString());
    }
    return null;
}