Example usage for com.amazonaws.services.s3 AmazonS3Client AmazonS3Client

List of usage examples for com.amazonaws.services.s3 AmazonS3Client AmazonS3Client

Introduction

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

Prototype

@SdkInternalApi
AmazonS3Client(AmazonS3ClientParams s3ClientParams) 

Source Link

Document

Constructs a new client to invoke service methods on S3 using the specified parameters.

Usage

From source file:com.altoukhov.svsync.fileviews.S3FileSpace.java

License:Apache License

private S3FileSpace(String root, String id, String secret) {

    s3 = new AmazonS3Client(wrapCredentials(id, secret));

    root = root.substring("s3://".length());
    root = root.endsWith("/") ? root.substring(0, root.length() - 1) : root;
    bucketName = root;/*ww w.j a  va2 s . c o  m*/

    if (root.contains("/")) {
        int splitIndex = root.indexOf("/");
        bucketName = root.substring(0, splitIndex);
        rootPath = root.substring(splitIndex + 1);
    }
}

From source file:com.amazon.aws.demo.anonymous.AmazonClientManager.java

License:Open Source License

public synchronized Response validateCredentials() {
    Response ableToGetToken = Response.SUCCESSFUL;

    if (AmazonSharedPreferencesWrapper.areCredentialsExpired(this.sharedPreferences)) {
        Log.i(LOG_TAG, "Credentials were expired.");

        clearCredentials();/*from  www .j  a  va2 s  . c  o  m*/

        AmazonTVMClient tvm = new AmazonTVMClient(this.sharedPreferences,
                PropertyLoader.getInstance().getTokenVendingMachineURL(),
                PropertyLoader.getInstance().useSSL());
        ableToGetToken = tvm.anonymousRegister();
        if (ableToGetToken.requestWasSuccessful()) {
            ableToGetToken = tvm.getToken();
        }
    }

    if (ableToGetToken.requestWasSuccessful()
            && (s3Client == null || sqsClient == null || sdbClient == null || snsClient == null)) {
        Log.i(LOG_TAG, "Creating New Credentials.");

        AWSCredentials credentials = AmazonSharedPreferencesWrapper
                .getCredentialsFromSharedPreferences(this.sharedPreferences);

        s3Client = new AmazonS3Client(credentials);
        sqsClient = new AmazonSQSClient(credentials);
        sdbClient = new AmazonSimpleDBClient(credentials);
        snsClient = new AmazonSNSClient(credentials);
    }

    return ableToGetToken;
}

From source file:com.amazon.aws.demo.identity.AmazonClientManager.java

License:Open Source License

public synchronized Response validateCredentials() {
    Response ableToGetToken = Response.SUCCESSFUL;

    if (AmazonSharedPreferencesWrapper.areCredentialsExpired(this.sharedPreferences)) {
        Log.i(LOG_TAG, "Credentials were expired.");

        clearCredentials();/*  ww  w  .  jav  a2  s.c  o m*/

        AmazonTVMClient tvm = new AmazonTVMClient(this.sharedPreferences,
                PropertyLoader.getInstance().getTokenVendingMachineURL(),
                PropertyLoader.getInstance().getAppName(), PropertyLoader.getInstance().useSSL());
        if (ableToGetToken.requestWasSuccessful()) {
            ableToGetToken = tvm.getToken();
        }
    }

    if (ableToGetToken.requestWasSuccessful()
            && (s3Client == null || sqsClient == null || sdbClient == null || snsClient == null)) {
        Log.i(LOG_TAG, "Creating New Credentials.");

        AWSCredentials credentials = AmazonSharedPreferencesWrapper
                .getCredentialsFromSharedPreferences(this.sharedPreferences);
        s3Client = new AmazonS3Client(credentials);
        sqsClient = new AmazonSQSClient(credentials);
        sdbClient = new AmazonSimpleDBClient(credentials);
        snsClient = new AmazonSNSClient(credentials);
    }

    return ableToGetToken;
}

From source file:com.amazon.photosharing.utils.ContentHelper.java

License:Open Source License

private void initS3Client() {
    s3Client = new AmazonS3Client(new DefaultAWSCredentialsProviderChain())
            .withRegion(Regions.fromName(ConfigFacade.get(Configuration.S3_REGION)));
}

From source file:com.amazon.services.awsrum.kinesis.KinesisConnectorExecutor.java

License:Open Source License

/**
 * Helper method to create the S3Bucket/*w  ww .  jav a  2s .  c  om*/
 * 
 * @param s3Bucket
 *            The name of the bucket to create
 */
private void createS3Bucket(String s3Bucket) {
    AmazonS3Client client = new AmazonS3Client(config.AWS_CREDENTIALS_PROVIDER);
    client.setEndpoint(config.S3_ENDPOINT);
    S3Utils.createBucket(client, s3Bucket);
}

From source file:com.amazon.util.ImageUploader.java

public static void uploadImage(String imageURL, String imageName, String folderName, String bucketName)
        throws MalformedURLException, IOException {
    // credentials object identifying user for authentication

    AWSCredentials credentials = new BasicAWSCredentials(System.getenv("AWS_S3_ACCESS_KEY"),
            System.getenv("AWS_S3_SECRET_ACCESS_KEY"));

    // create a client connection based on credentials
    AmazonS3 s3client = new AmazonS3Client(credentials);

    try {//from   w w w  .j a v  a2s. c  om
        if (!(s3client.doesBucketExist(bucketName))) {
            s3client.setRegion(Region.getRegion(Regions.US_EAST_1));
            // Note that CreateBucketRequest does not specify region. So bucket is 
            // created in the region specified in the client.
            s3client.createBucket(new CreateBucketRequest(bucketName));
        }

        //Enabe CORS:
        //     <?xml version="1.0" encoding="UTF-8"?>
        //<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
        //    <CORSRule>
        //        <AllowedOrigin>http://ask-ifr-download.s3.amazonaws.com</AllowedOrigin>
        //        <AllowedMethod>GET</AllowedMethod>
        //    </CORSRule>
        //</CORSConfiguration>
        BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration();

        CORSRule corsRule = new CORSRule()
                .withAllowedMethods(
                        Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.GET }))
                .withAllowedOrigins(Arrays.asList(new String[] { "http://ask-ifr-download.s3.amazonaws.com" }));
        configuration.setRules(Arrays.asList(new CORSRule[] { corsRule }));
        s3client.setBucketCrossOriginConfiguration(bucketName, configuration);

    } 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 "
                + "an internal error while trying to " + "communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }

    String fileName = folderName + SUFFIX + imageName + ".png";
    URL url = new URL(imageURL);

    ObjectMetadata omd = new ObjectMetadata();
    omd.setContentType("image/png");
    omd.setContentLength(url.openConnection().getContentLength());
    // upload file to folder and set it to public
    s3client.putObject(new PutObjectRequest(bucketName, fileName, url.openStream(), omd)
            .withCannedAcl(CannedAccessControlList.PublicRead));
}

From source file:com.amediamanager.config.S3ConfigurationProvider.java

License:Apache License

@Override
public void loadProperties() {
    this.properties = null;

    // Load properties if there is a bucket and key
    if (bucket != null && key != null) {
        AWSCredentialsProvider creds = new AWSCredentialsProviderChain(new InstanceProfileCredentialsProvider(),
                new EnvironmentVariableCredentialsProvider(), new SystemPropertiesCredentialsProvider());
        AmazonS3 s3Client = new AmazonS3Client(creds);
        try {// ww w  .  j a  v  a2s. c  o m
            S3Object object = s3Client.getObject(this.bucket, this.key);
            if (object != null) {
                this.properties = new Properties();
                try {
                    this.properties.load(object.getObjectContent());
                } catch (IOException e) {
                    this.properties = null;
                    LOG.warn("Found configuration file in S3 but failed to load properties (s3://{}/{})",
                            new Object[] { this.bucket, this.key, e });
                } finally {
                    try {
                        object.close();
                    } catch (IOException e) {
                        // Don't care
                    }
                }
            }
        } catch (AmazonS3Exception ase) {
            LOG.error("Error loading config from s3://{}/{}", new Object[] { this.bucket, this.key, ase });
        }
    }
}

From source file:com.android.demo.notepad3.Util.java

License:Open Source License

public static AmazonS3Client getS3Client(Context context) {
    if (sS3Client == null) {
        sS3Client = new AmazonS3Client(getCredProvider(context));
    }//from   ww w. j a va 2s. c  om
    return sS3Client;
}

From source file:com.appdynamics.monitors.s3.AWSS3Monitor.java

License:Apache License

/**
 * Main execution method that gets data from Amazon S3 and send metrics to
 * AppDynamics Controller//w  w w .ja  v  a 2 s  .  c o m
 */
@Override
public TaskOutput execute(final Map<String, String> argsMap, TaskExecutionContext executionContext)
        throws TaskExecutionException {

    logger.debug("The args map is:  " + argsMap);

    // Reading configurations
    configuration = ConfigurationUtil.getConfigurations(argsMap.get(AWSS3Constants.KEY_CONFIG));

    if (configuration == null || configuration.getAwsCredentials() == null
            || configuration.getAwsCredentials().getAWSAccessKeyId() == null
            || configuration.getAwsCredentials().getAWSSecretKey() == null) {
        logger.error("Sending S3 metric failed. Unable to find mandatory configuration.");
        throw new TaskExecutionException("Sending S3 metric failed. Unable to find mandatory configuration.");
    }

    logger.debug("Using access key: " + configuration.getAwsCredentials().getAWSAccessKeyId() + ", Secret key:"
            + configuration.getAwsCredentials().getAWSSecretKey());

    // Creating AmazonS3Client
    AmazonS3Client amazonS3Client = new AmazonS3Client(configuration.getAwsCredentials());

    // Getting list of buckets from configuration, for which result needs to
    // be collected
    List<Bucket> buckets = getBuckets();

    // Calling getS3Result which calls Amazon WS to get the Result
    Map<String, String> resultMap = getS3Result(buckets, amazonS3Client);

    // Sending all metrics to controller
    printAllMetrics(argsMap.get(AWSS3Constants.KEY_METRICPREFIX), resultMap);

    logger.info("Sending S3 metric complete!");
    return new TaskOutput("Sending S3 metric complete!");
}

From source file:com.arc.cloud.aws.s3.S3Sample.java

License:Open Source License

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

    /*//from  w  ww.jav  a2 s .c  o  m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    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);
    }

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