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

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

Introduction

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

Prototype

public void setRegion(com.amazonaws.regions.Region region) throws IllegalArgumentException;

Source Link

Document

An alternative to AmazonS3#setEndpoint(String) , sets the regional endpoint for this client's service calls.

Usage

From source file:jp.sanix.yokusei.java

License:Open Source License

public static void main(String[] args) throws IOException, SQLException, AmazonServiceException, JSONException,
        NullPointerException, ParseException {

    String id = "A0002441";
    String datefrom = "2015/10/01";
    String dateto = "2015/10/12";

    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
    format.setTimeZone(TimeZone.getTimeZone("JST"));
    SimpleDateFormat pgformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    pgformat.setTimeZone(TimeZone.getTimeZone("UTC"));

    Calendar cal = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    String today = toDate(cal);//from   w  w w  .  java2 s .  com

    try {
        cal.setTime(format.parse(datefrom));
    } catch (ParseException e) {
    }
    try {
        end.setTime(format.parse(dateto));
        end.add(Calendar.DAY_OF_MONTH, 1);
    } catch (ParseException e) {
    }

    AmazonS3 s3 = new AmazonS3Client();
    s3.setRegion(Region.getRegion(Regions.AP_NORTHEAST_1));

    Connection db = DriverManager.getConnection(PG_CON, PG_USER, PG_PASS);
    Statement st = db.createStatement();
    ResultSet rs = st.executeQuery(
            "SELECT data, pvs_unique_code FROM data WHERE pvs_serial_id='" + id + "' OFFSET 0 LIMIT 1;");
    rs.next();
    String json = rs.getString(1);
    String key = rs.getString(2);
    rs.close();
    db.close();
    Date recent = new Date();

    xlsSheetYokusei xls = new xlsSheetYokusei(json);
    while (cal.before(end)) {
        System.out.println("Getting data of " + toDate(cal));

        /* AWS S3????? */
        String bucketName = "pvdata-storage-production";
        System.out.println("Get s3 data by key='" + bucketName + "/data/" + key + "/" + toDate(cal) + "/'");
        ObjectListing objectListing = s3.listObjects(new ListObjectsRequest().withBucketName(bucketName)
                .withPrefix("data/" + key + "/" + toDate(cal) + "/"));

        /* get data from s3 */
        do {
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                String keyname = objectSummary.getKey();
                S3Object object = s3.getObject(new GetObjectRequest(bucketName, keyname));
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(new GZIPInputStream(object.getObjectContent())));
                String line;
                while ((line = reader.readLine()) != null) {
                    try {
                        json = line.substring(line.indexOf("{"));
                        xls.putData(json);
                    } catch (NullPointerException e) {
                    }
                }
                reader.close();
                object.close();
            }
            objectListing = s3.listNextBatchOfObjects(objectListing);
        } while (objectListing.getMarker() != null);

        /* if today, read postgres to get recent data */
        if (toDate(cal).equals(today)) {
            System.out.println("Get recent data from postgres");
            try {
                db = DriverManager.getConnection(PG_CON, PG_USER, PG_PASS);
                st = db.createStatement();
                String sql = "SELECT data FROM data WHERE pvs_unique_code='" + key + "' AND created_at > '"
                        + pgformat.format(recent) + "';";
                System.out.println(sql);
                rs = st.executeQuery(sql);
                while (rs.next()) {
                    json = rs.getString(1);
                    xls.putData(json);
                }
                rs.close();
                db.close();
            } catch (PSQLException e) {
            } catch (ParseException e) {
            }
        }
        System.out.println("Write Buffer");
        xls.writeBuffer();

        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
    File file = new File(
            "C:\\Users\\SANIX_CORERD\\Desktop\\" + id + "-Diamond" + toDate(cal).replace("/", "-") + ".xlsx");
    xls.putFile(new FileOutputStream(file));
    System.out.println("Finished: " + toDate(cal));
}

From source file:org.alanwilliamson.amazon.AmazonBase.java

License:Open Source License

/**
 * Returns back the necessary AmazonS3 class for communicating to the S3
 * //from   www.  j a  v  a  2s  .co m
 * @param _session
 * @param argStruct
 * @return
 * @throws cfmRunTimeException
 */
public AmazonS3 getAmazonS3(AmazonKey amazonKey) throws cfmRunTimeException {
    BasicAWSCredentials awsCreds = new BasicAWSCredentials(amazonKey.getKey(), amazonKey.getSecret());
    AmazonS3 s3Client = new AmazonS3Client(awsCreds);
    s3Client.setRegion(amazonKey.getAmazonRegion().toAWSRegion());
    return s3Client;
}

From source file:org.cto.VVS3Box.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*//from  w ww  .j a va2s . co m
     * This credentials provider implementation loads your AWS credentials
     * from a properties file at the root of your classpath.
     *
     * 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 ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    String bucketName = "lior.test-" + 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:org.p365.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*//w ww.  ja v  a  2 s  .  com
     * This credentials provider implementation loads your AWS credentials
     * from a properties file at the root of your classpath.
     *
     * 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 ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    String bucketName = "mynewbuket";
    String key = "Myobj/sd.jpg";

    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");
        if (!s3.doesBucketExist(bucketName)) {
            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");
        String pathname = "D:\\Program Files\\apache-tomcat-7.0.42\\webapps\\WorkerForP365\\src\\AAA_1465.jpg";
        File file = new File(pathname);
        s3.putObject(
                new PutObjectRequest(bucketName, key, file).withCannedAcl(CannedAccessControlList.PublicRead));

        /*
         * 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:org.talend.components.s3.runtime.S3Connection.java

License:Open Source License

public static AmazonS3 createClient(S3OutputProperties properties) {
    S3DatasetProperties data_set = properties.getDatasetProperties();
    S3DatastoreProperties data_store = properties.getDatasetProperties().getDatastoreProperties();

    com.amazonaws.auth.AWSCredentials credentials = new com.amazonaws.auth.BasicAWSCredentials(
            data_store.accessKey.getValue(), data_store.secretKey.getValue());

    Region region = RegionUtils.getRegion(data_set.region.getValue().getValue());
    Boolean clientSideEnc = data_set.encryptDataInMotion.getValue();

    AmazonS3 conn = null;
    if (clientSideEnc != null && clientSideEnc) {
        String kms_cmk = data_set.kmsForDataInMotion.getValue();
        KMSEncryptionMaterialsProvider encryptionMaterialsProvider = new KMSEncryptionMaterialsProvider(
                kms_cmk);/*from   w  w w.  ja  v  a 2  s  .c  o m*/
        conn = new AmazonS3EncryptionClient(credentials, encryptionMaterialsProvider,
                new CryptoConfiguration().withAwsKmsRegion(region));
    } else {
        AWSCredentialsProvider basicCredentialsProvider = new StaticCredentialsProvider(credentials);
        conn = new AmazonS3Client(basicCredentialsProvider);
    }

    conn.setRegion(region);

    return conn;
}

From source file:oulib.aws.Main.java

public static void main(String[] args) {

    try {//from  w w w  .ja v a2  s .c o  m
        AWSCredentials credentials = null;
        AmazonS3 s3Client = null;
        //            args = new String[4];
        //            args[0] = "ul-bagit";
        //            args[1] = "ul-ir-workspace";
        //            args[2] = "Borelli_1680-1681";
        //            args[3] = "6";
        try {
            credentials = new ProfileCredentialsProvider("default").getCredentials();
        } catch (Exception e) {
            String access_key_id = null;
            String secret_key_id = null;
            String credentialInfo = AwsUtil.getAwsCredentials();
            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> credentialInfoMap = new HashMap<>();
            credentialInfoMap = mapper.readValue(credentialInfo, HashMap.class);
            for (String key : credentialInfoMap.keySet()) {

                if ("AccessKeyId".equals(key)) {
                    access_key_id = credentialInfoMap.get(key);
                } else if ("SecretAccessKey".equals(key)) {
                    secret_key_id = credentialInfoMap.get(key);
                }
            }
            //                System.out.println("access_key_id = "+access_key_id+" access_key_id = "+access_key_id);
            if (null != access_key_id && null != secret_key_id) {
                credentials = new BasicAWSCredentials(access_key_id, secret_key_id);
                //                    s3Client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
            } else {
                throw new AmazonClientException("Cannot load the credentials from the credential information. "
                        + "Please make sure that your credentials file is at the correct, and is in valid format.",
                        e);
            }
        }

        ClientConfiguration config = new ClientConfiguration();
        config.setConnectionTimeout(250000);
        config.setSocketTimeout(50000);

        s3Client = new AmazonS3Client(credentials, config);
        Region usEast = Region.getRegion(Regions.US_EAST_1);
        s3Client.setRegion(usEast);

        String bookName = args[2];

        S3BookInfo bookInfo = new S3BookInfo();
        bookInfo.setBookName(bookName);
        bookInfo.setBucketSourceName(args[0]);
        bookInfo.setBucketTargetName(args[1]);
        bookInfo.setCompressionSize(15000000);

        // *** Generate metadadta *****

        //                S3Util.copyS3ObjectTiffMetadata(s3client, "ul-bagit", "ul-ir-workspace", "Zuniga_1591/data/004.tif", "Zuniga_1591/data/004.tif");
        //                S3Util.copyS3ObjectTiffMetadata(s3client, "ul-bagit", "ul-ir-workspace", "Zuniga_1591/data/004.tif", "Zuniga_1591/data/004-20.tif");
        //            S3Util.copyS3ObjectTiffMetadata(s3client, "ul-bagit", "ul-ir-workspace", "Zuniga_1591/data/004.tif", "Zuniga_1591/data/004-50.tif");

        // *** Generate small tiffs *****
        Integer threadMaxCount = 0;
        try {
            threadMaxCount = Integer.valueOf(args[3]);
        } catch (Exception ex) {
            ex.printStackTrace();//logger.error("Cannot parse the thread count! "+ex.getMessage());
            return;
        }
        System.out.println(
                "arg0 = " + args[0] + " arg1 = " + args[1] + " arg2 = " + args[2] + " arg3 = " + args[3]);
        ExecutorService executor = Executors.newFixedThreadPool(threadMaxCount);
        List<String> tiffDiff = S3Util.getBucketObjectKeyList(bookInfo.getBucketSourceName(), args[2],
                s3Client);//.getS3BucketFolderObjDiff(s3Client, args[0], bookName+"/data", args[1], bookName+"/data");
        int diff = tiffDiff.size();
        if (diff > 0) {
            System.out.println("There are totally " + String.valueOf(diff)
                    + " tiff images to process.\nStart processing at " + (new java.util.Date()).toString());
            AwsDataProcessorThreadFactory threadFactory = new AwsDataProcessorThreadFactory();
            for (int i = 0; i <= 10; i++) {
                //                    S3TiffProcessorThread s3TiffProcessorThread = new S3TiffProcessorThread(s3Client, bookInfo, String.valueOf(i)+".tif", tiffDiff);
                //                    threadFactory.setIndex(i);
                //                    threadFactory.setJobType("small-tiff-" + bookName);
                //                    executor.execute(threadFactory.newThread(s3TiffProcessorThread));
                //                    System.out.println("obj has path = "+bookInfo.getBucketSourceName() + tiffDiff.get(i));
                S3TiffMetadataProcessorThread thread = new S3TiffMetadataProcessorThread(s3Client, bookInfo,
                        String.valueOf(i) + ".tif", tiffDiff);
                threadFactory.setIndex(i);
                threadFactory.setJobType("tiff-metadata-" + bookName);
                executor.execute(threadFactory.newThread(thread));
            }
        } else {
            System.out.println("There are no tiff images to process");
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("All the derivatives were generated at " + (new java.util.Date()).toString() + "!");

    } catch (Exception ex) {
        ex.printStackTrace();//logger.error("Cannot finish generating the small tiff images" + ex.getMessage());
    }
}

From source file:oulib.aws.s3.S3TiffProcessor.java

/**
* 
* @param bookInfo : contains the information of the source bucket name, target bucket name, and the name of the book
* @param context : lambda function runtime context
* @return :// ww  w .j  a  v  a2  s  .  c  o  m
* 
*/
@Override
public String handleRequest(S3BookInfo bookInfo, Context context) {

    AmazonS3 s3client = new AmazonS3Client();
    Region usEast = Region.getRegion(Regions.US_EAST_1);
    s3client.setRegion(usEast);

    try {
        String sourceBucketName = bookInfo.getBucketSourceName();
        String targetBucketName = bookInfo.getBucketTargetName();
        String bookName = bookInfo.getBookName();

        // Every book has a folder in the target bucket:
        Map targetBucketKeyMap = S3Util.getBucketObjectKeyMap(targetBucketName, bookName, s3client);
        if (!S3Util.folderExitsts(bookName, targetBucketKeyMap)) {
            S3Util.createFolder(targetBucketName, bookName, s3client);
        }

        final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(sourceBucketName)
                .withPrefix(bookName + "/data/");
        ListObjectsV2Result result;

        do {
            result = s3client.listObjectsV2(req);

            for (S3ObjectSummary objectSummary : result.getObjectSummaries()) {
                String key = objectSummary.getKey();
                if (key.endsWith(".tif") && !targetBucketKeyMap.containsKey(key + ".tif")) {
                    S3Object object = s3client.getObject(new GetObjectRequest(sourceBucketName, key));
                    System.out.println("Start to generate smaller tif image for the object " + key);
                    S3Util.generateSmallTiffWithTargetSize(s3client, object, targetBucketName,
                            bookInfo.getCompressionSize());
                    //                       S3Util.copyS3ObjectTiffMetadata(s3client, object, s3client.getObject(new GetObjectRequest(targetBucketName, key)), targetBucketName, key+".tif");
                    System.out.println("Finished to generate smaller tif image for the object " + key + ".tif");
                    //                       break;
                }
            }
            System.out.println("Next Continuation Token : " + result.getNextContinuationToken());
            req.setContinuationToken(result.getNextContinuationToken());
        } while (result.isTruncated() == true);

    } 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, \nsuch as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
    return null;
}

From source file:oulib.aws.s3.S3Util.java

/**
 * Use the default approach to get a AWS S3 client with the default region of east.
 * //from ww w  .j ava  2 s  .  c o m
 * @return AmazonS3 : s3 client
 */
public static AmazonS3 getS3AwsClient() {

    AWSCredentials credentials = null;
    try {
        ProfileCredentialsProvider provider = new ProfileCredentialsProvider("default");
        credentials = provider.getCredentials();
        if (null == credentials) {
            throw new InvalidS3CredentialsException("Invalid credentials with default approach!");
        }
    } catch (InvalidS3CredentialsException | AmazonClientException 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 (/Users/zhao0677/.aws/credentials), and is in valid format.", e);
    }

    AmazonS3 s3client = new AmazonS3Client(credentials);
    Region usEast = Region.getRegion(Regions.US_EAST_1);
    s3client.setRegion(usEast);
    return s3client;
}

From source file:oulib.aws.s3.S3Util.java

public static AmazonS3 getS3Client() {

    AWSCredentials credentials = null;/*from  ww w  .  jav  a 2 s .  c o m*/
    try {
        credentials = new ProfileCredentialsProvider("default").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 (/Users/zhao0677/.aws/credentials), and is in valid format.", e);
    }

    AmazonS3 s3client = new AmazonS3Client(credentials);
    Region usEast = Region.getRegion(Regions.US_EAST_1);
    s3client.setRegion(usEast);
    return s3client;
}

From source file:S3Controller.DownloadingImages.java

public static void main(String[] args) throws IOException {
    AWSCredentials credentials = null;/*from w  ww  .  j  a  va  2 s. c o m*/
    String aws_access_key_id = "PUT_YOUR_aws_access_key_id_HERE";
    String aws_secret_access_key = "PUT_YOUR_aws_secret_access_key_HERE";
    try {
        credentials = new BasicAWSCredentials(aws_access_key_id, aws_secret_access_key);//.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 AP_SOUTHEAST_1 = Region.getRegion(Regions.AP_SOUTHEAST_1);
    s3.setRegion(AP_SOUTHEAST_1);

    String bucketName = "PUT_YOUR_S3-BUCKET-NAME_HERE";
    String key = "PUT_YOUR_S3-BUCKET-KEY_HERE";

    try {

        ArrayList arr = new ArrayList();
        ArrayList EmailArray = new ArrayList();
        Bucket bucket = new Bucket(bucketName);
        ObjectListing objects = s3.listObjects(bucket.getName());
        do {
            for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                //                System.out.println(objectSummary.getKey() + "\t" +
                //                        objectSummary.getSize() + "\t" +
                //                        StringUtils.fromDate(objectSummary.getLastModified()));
                arr.add(objectSummary.getKey());
            }
            objects = s3.listNextBatchOfObjects(objects);
        } while (objects.isTruncated());

        KrakenIOExampleMain kraken = new KrakenIOExampleMain();
        for (int i = 0; i < arr.size(); i++) {
            System.out.println("Compressing: " + arr.get(i));
            String s = (String) arr.get(i);
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket.getName(), s);
            System.out.println(s3.generatePresignedUrl(request));
            URL Glink = s3.generatePresignedUrl(request);
            String Dlink = Glink.toString();
            System.out.println("Download Link:" + Dlink);
            kraken.Compression(Dlink, bucketName);
            System.out.println("Compression completed: " + arr.get(i));
            EmailArray.add("Processed Image:" + arr.get(i));
        }
        System.out.println("Start Emailing list");
        EmailSender esender = new EmailSender();
        esender.EmailVerification(GetNotificationEmail, EmailArray);
        System.out.println("Kraken compression completed");
    } 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());
    } catch (ExecutionException ex) {
        Logger.getLogger(DownloadingImages.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(DownloadingImages.class.getName()).log(Level.SEVERE, null, ex);
    }
}