Example usage for com.amazonaws.regions Region getRegion

List of usage examples for com.amazonaws.regions Region getRegion

Introduction

In this page you can find the example usage for com.amazonaws.regions Region getRegion.

Prototype

public static Region getRegion(Regions region) 

Source Link

Document

Returns the region with the id given, or null if it cannot be found in the current regions.xml file.

Usage

From source file:com.kpbird.aws.Main.java

private void init() {
    credentials = new BasicAWSCredentials(accessKey, secretKey);
    // end point for singapore 
    endPoint = "https://rds.ap-southeast-1.amazonaws.com";
    // regions for singapore
    region = Region.getRegion(Regions.AP_SOUTHEAST_1);
    // EC2Client object
    ec2client = new AmazonEC2Client(credentials);
    ec2client.setEndpoint(endPoint);//from   ww  w .j  av  a  2  s. c o  m
    ec2client.setRegion(region);
    // RDSClient object
    rdsclient = new AmazonRDSClient(credentials);
    rdsclient.setRegion(region);
    rdsclient.setEndpoint(endPoint);

}

From source file:com.liferay.portal.store.s3.S3Store.java

License:Open Source License

protected AmazonS3 getAmazonS3(AWSCredentialsProvider awsCredentialsProvider) {

    ClientConfiguration clientConfiguration = getClientConfiguration();

    AmazonS3 amazonS3 = new AmazonS3Client(awsCredentialsProvider, clientConfiguration);

    Region region = Region.getRegion(Regions.fromName(_s3StoreConfiguration.s3Region()));

    amazonS3.setRegion(region);//from  w ww.  j  a  va2 s . co  m

    return amazonS3;
}

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

public static void main(String[] args) throws AmazonClientException {
    System.out.println("Start process SQS");
    try {//from  w  ww  .  ja v a  2s. c  o  m
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
        System.out.println("Error");
        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);
    }

    final Thread mainThread = new Thread(() -> {
        while (!Thread.currentThread().isInterrupted()) {
            AmazonSQS sqs = new AmazonSQSClient(credentials);
            Region usWest2 = Region.getRegion(Regions.US_WEST_2);
            sqs.setRegion(usWest2);

            AmazonS3 s3 = new AmazonS3Client(credentials);
            s3.setRegion(usWest2);

            List<String> filesList = SQSConfig.getMessages(sqs, sqsURL);

            for (String file : filesList) {
                String[] files = file.split(",");
                if (!file.equals("missing parameter: fileNames"))
                    for (int i = 0; i < files.length; i++) {
                        try {
                            SQSConfig.processFile(files[i], s3, bucketName);
                        } catch (IOException e) {
                            System.out.println("Error");
                            e.printStackTrace();
                        }
                    }

            }
            System.out.println("\nWaiting for messages.........\n");
        }
    });
    mainThread.start();
}

From source file:com.maya.portAuthority.util.ImageUploader.java

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

     AWSCredentials credentials = new BasicAWSCredentials("AKIAJBFSMHRTIQQ7BKYA",
             "AdHgeP4dyWInWwPn9YlfxFCm3qP1lHjdxOxeJqDa");

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

     String folderName = "image"; //folder name
     //    String bucketName = "ppas-image-upload"; //must be unique

     try {/* ww  w  .j ava  2  s .  c o m*/
         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.mentation.alfonso.aws.ElasticLoadBalancer.java

License:Apache License

public ElasticLoadBalancer(String name) {
    _name = name;/*from  w  w w .j  a v a 2 s.  c  o  m*/

    _elbClient = new AmazonElasticLoadBalancingClient();
    // TODO Should read this from properties file
    _elbClient.setRegion(Region.getRegion(Regions.US_WEST_2));
}

From source file:com.meteotester.util.S3Util.java

License:Open Source License

public static void saveFileToS3(File file) {
    try {//w  w w  . j  a v a  2  s  .com
        AWSCredentials myCredentials = new BasicAWSCredentials(Config.AWS_ACCESS_KEY, Config.AWS_SECRET_KEY);
        AmazonS3 s3client = new AmazonS3Client(myCredentials);

        s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));
        String filename = file.getName();
        String path = file.getPath();

        PutObjectRequest req = new PutObjectRequest(Config.S3_BUCKETNAME, path, file);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.length());
        String contentType = (filename.contains("json")) ? "application/json" : "text/csv";
        metadata.setContentType(contentType);
        req.setMetadata(metadata);

        s3client.putObject(req);

        log.info(filename + " stored in S3");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.mhp.insideApp.insideApplications.utils.SendMailHelperBean.java

private String assembleAndSend(Message message, String custEmailTO, String from) throws Exception {
    log.debug("Cust Email Id:-" + custEmailTO + "  Verified Email Id is :- " + from);
    Destination destination = new Destination().withToAddresses(custEmailTO);
    // Assemble the email.
    SendEmailRequest request = new SendEmailRequest().withSource(from).withDestination(destination)
            .withMessage(message);//from ww w .  j a  v  a2  s .co  m
    try {
        log.info("Attempting to send an email!");
        Region reg = Region.getRegion(Regions.fromName(region));
        amazonSimpleEmailServiceClient.setRegion(reg);
        // Send the email.
        SendEmailResult sendEmailResult = amazonSimpleEmailServiceClient.sendEmail(request);
        log.info("Email sent!");
        return sendEmailResult.getMessageId();
    } catch (Exception ex) {
        log.error("Error while sending the email", ex);
        throw new Exception(ex);
    }
}

From source file:com.mweagle.tereus.input.TereusAWSInput.java

License:Open Source License

public TereusAWSInput(final String awsRegion, final boolean dryRun, final String loggerName) {
    this.awsRegion = (null != awsRegion) ? Region.getRegion(Regions.fromName(awsRegion))
            : Region.getRegion(Regions.US_EAST_1);
    this.dryRun = dryRun;
    DefaultAWSCredentialsProviderChain credentialProviderChain = new DefaultAWSCredentialsProviderChain();
    this.awsCredentials = credentialProviderChain.getCredentials();
    this.logger = LogManager.getLogger(loggerName);
}

From source file:com.mycompany.rproject.runnableClass.java

public static void use() throws IOException {
    AWSCredentials awsCreds = new PropertiesCredentials(
            new File("/Users/paulamontojo/Desktop/AwsCredentials.properties"));

    AmazonSQS sqs = new AmazonSQSClient(awsCreds);

    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    sqs.setRegion(usWest2);//from   w  w  w.j ava2s .  com
    String myQueueUrl = "https://sqs.us-west-2.amazonaws.com/711690152696/MyQueue";

    System.out.println("Receiving messages from MyQueue.\n");

    ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
    List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
    while (messages.isEmpty()) {

        messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
    }

    String messageRecieptHandle = messages.get(0).getReceiptHandle();

    String a = messages.get(0).getBody();

    sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

    //aqui opero y cuando acabe llamo para operar el siguiente.

    String n = "";
    String dbName = "mydb";
    String userName = "pmontojo";
    String password = "pmontojo";
    String hostname = "mydb.cued7orr1q2t.us-west-2.rds.amazonaws.com";
    String port = "3306";
    String jdbcUrl = "jdbc:mysql://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password="
            + password;
    Connection conn = null;
    Statement setupStatement = null;
    Statement readStatement = null;
    ResultSet resultSet = null;
    String results = "";
    int numresults = 0;
    String statement = null;

    try {

        conn = DriverManager.getConnection(jdbcUrl);

        setupStatement = conn.createStatement();

        String insertUrl = "select video_name from metadata where id = " + a + ";";
        String checkUrl = "select url from metadata where id = " + a + ";";

        ResultSet rs = setupStatement.executeQuery(insertUrl);

        rs.next();

        System.out.println("este es el resultdo " + rs.getString(1));

        String names = rs.getString(1);
        ResultSet ch = setupStatement.executeQuery(checkUrl);
        ch.next();
        System.out.println("este es la url" + ch.getString(1));
        String urli = ch.getString(1);

        while (urli == null) {
            ResultSet sh = setupStatement.executeQuery(checkUrl);
            sh.next();
            System.out.println("este es la url" + sh.getString(1));
            urli = sh.getString(1);

        }
        setupStatement.close();
        AmazonS3 s3Client = new AmazonS3Client(awsCreds);

        S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, names));

        IOUtils.copy(object.getObjectContent(),
                new FileOutputStream(new File("/Users/paulamontojo/Desktop/download.avi")));

        putOutput();
        write();
        putInDb(sbu.toString(), a);

    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
    } finally {
        System.out.println("Closing the connection.");
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
    }

    use();

}

From source file:com.mycompany.rproject.runnableClass.java

public static void putInDb(String s, String id) throws IOException {
    AWSCredentials credentials = new PropertiesCredentials(
            new File("/Users/paulamontojo/Desktop/AwsCredentials.properties"));

    dynamoDBClient = new AmazonDynamoDBClient(new STSSessionCredentialsProvider(credentials));
    dynamoDBClient.setRegion(Region.getRegion(Regions.US_WEST_2));
    createTable();//from ww  w . ja  v a  2 s.  c  om

    // Describe our new table
    describeTable();

    // Add some items
    putItem(newItem(id, "url", s));

}