Example usage for com.amazonaws.auth BasicAWSCredentials BasicAWSCredentials

List of usage examples for com.amazonaws.auth BasicAWSCredentials BasicAWSCredentials

Introduction

In this page you can find the example usage for com.amazonaws.auth BasicAWSCredentials BasicAWSCredentials.

Prototype

public BasicAWSCredentials(String accessKey, String secretKey) 

Source Link

Document

Constructs a new BasicAWSCredentials object, with the specified AWS access key and AWS secret key.

Usage

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 ww  w  .  j a v  a  2s .  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.app.ses.AmazonSES.java

License:Open Source License

public void sendMail(String TO, String USUARIO2, String SUBJECT, String CONTENIDO, String FOLIO,
        String USERCREATE, String NOMBRE) {

    // Construct an object to contain the recipient address.
    Destination destination = new Destination().withToAddresses(new String[] { TO });

    // Create the subject and body of the message.
    Content subject = new Content().withData(SUBJECT);

    Content htmlContent = new Content().withData(" <body bgcolor=\"#FFFFFF\">\n" + "    <!-- HEADER -->\n"
            + "        <table class=\"head-wrap\" bgcolor=\"red\">\n" + "            <tr>\n"
            + "                <td></td>\n" + "                <td class=\"header container\" >\n"
            + "                    <div class=\"content\">\n"
            + "                        <table bgcolor=\"red\">\n" + "                            <tr>\n"
            + "                                <td style=\"font-size: x-large; color:white;\">\n"
            + "                                    S G C o n\n" + "                                </td>\n"
            + "                                <td style=\"text-align: right; color:white; fon\">\n"
            + "                                    Notificaciones\n" + "                                </td>\n"
            + "                            </tr>\n" + "                        </table>\n"
            + "                    </div>\n" + "                </td>\n" + "                <td></td>\n"
            + "            </tr>\n" + "        </table><!-- /HEADER -->\n" + "        <!-- BODY -->\n"
            + "        <table class=\"body-wrap\">\n" + "            <tr>\n" + "                <td></td>\n"
            + "                <td class=\"container\" bgcolor=\"#FFFFFF\">\n"
            + "                    <div class=\"content\">\n" + "                        <table>\n"
            + "                            <tr>\n" + "                                <td>\n"
            + "                                    <h3>Hola, " + USUARIO2 + "</h3>\n"
            + "                                    <p class=\"callout\">\n"
            + "                                        " + CONTENIDO + "\n"
            + "                                    </p>\n" + "                                    <p>\n"
            + "                                        <table style=\"font-size: medium\">\n"
            + "                                            <tr>\n"
            + "                                                <td>Folio: " + FOLIO + "</td>\n"
            + "                                            </tr>\n"
            + "                                            <tr>\n"
            + "                                                <td>" + USERCREATE + "</td>\n"
            + "                                            </tr>\n"
            + "                                            <tr>\n"
            + "                                                <td>" + NOMBRE + "</td>\n"
            + "                                            </tr>\n"
            + "                                        </table>\n"
            + "                                    </p> <br/>\n"
            + "                                     <table>\n"
            + "                                         <tr>\n"
            + "                                             <td>\n"
            + "                                                 <p>\n"
            + "                                                     <a href=\"http://www.sgcon-infonavit.com\" class=\"soc-btn fb\">Ir a la aplicacin</a> \n"
            + "                                                 </p>\n"
            + "                                             </td>\n"
            + "                                         </tr>\n"
            + "                                     </table\n" + "                                </td>\n"
            + "                            </tr>\n" + "                        </table>\n"
            + "                    </div>\n" + "                </td>\n" + "                <td></td>\n"
            + "            </tr>\n" + "        </table>\n" + "    </body>");

    Body body = new Body().withHtml(htmlContent);

    // Create a message with the specified subject and body.
    Message message = new Message().withSubject(subject).withBody(body);

    // Assemble the email.
    SendEmailRequest request = new SendEmailRequest().withSource(FROM).withDestination(destination)
            .withMessage(message);//from  w  w w .  ja  va2 s  . com

    try {
        System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java...");

        /*
         * The ProfileCredentialsProvider will return your [default]
         * credential profile by reading from the credentials file located at
         * (~/.aws/credentials).
         *
         * TransferManager manages a pool of threads, so we create a
         * single instance and share it throughout our application.
         */
        /*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);
         }*/
        AWSCredentials awsCreds = new BasicAWSCredentials("AKIAJFO4NNHIPNTB4ZCQ",
                "VjYeQ9+xj3HAcLBSxxxbHTo6jy2ft0wF6tgWZXmA");
        // Instantiate an Amazon SES client, which will make the service call with the supplied AWS credentials.
        //AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials);
        AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(awsCreds);

        // Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your production
        // access status, sending limits, and Amazon SES identity-related settings are specific to a given
        // AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using
        // the US East (N. Virginia) region. Examples of other regions that Amazon SES supports are US_WEST_2
        // and EU_WEST_1. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html
        Region REGION = Region.getRegion(Regions.US_WEST_2);
        client.setRegion(REGION);

        // Send the email.
        client.sendEmail(request);
        System.out.println("Email sent!");

    } catch (Exception ex) {
        System.out.println("The email was not sent.");
        System.out.println("Error message: " + ex.getMessage());
    }
}

From source file:com.app.ses.AmazonSES.java

License:Open Source License

public void sendMailDos(String TO, String USUARIO2, String SUBJECT, String CONTENIDO, String LISTA) {

    System.out.println("Si imprime la llamada del la clase  djscnlskdncfksdlncfksdcldsncewldn");

    //operaciones con el json       
    // Construct an object to contain the recipient address.
    Destination destination = new Destination().withToAddresses(new String[] { TO });

    // Create the subject and body of the message.
    Content subject = new Content().withData(SUBJECT);

    Content htmlContent = new Content().withData(" <body bgcolor=\"#FFFFFF\">\n" + "    <!-- HEADER -->\n"
            + "        <table class=\"head-wrap\" bgcolor=\"red\">\n" + "            <tr>\n"
            + "                <td></td>\n" + "                <td class=\"header container\" >\n"
            + "                    <div class=\"content\">\n"
            + "                        <table bgcolor=\"red\">\n" + "                            <tr>\n"
            + "                                <td style=\"font-size: x-large; color:white;\">\n"
            + "                                    S G C o n\n" + "                                </td>\n"
            + "                                <td style=\"text-align: right; color:white; fon\">\n"
            + "                                    Notificaciones\n" + "                                </td>\n"
            + "                            </tr>\n" + "                        </table>\n"
            + "                    </div>\n" + "                </td>\n" + "                <td></td>\n"
            + "            </tr>\n" + "        </table><!-- /HEADER -->\n" + "        <!-- BODY -->\n"
            + "        <table class=\"body-wrap\">\n" + "            <tr>\n" + "                <td></td>\n"
            + "                <td class=\"container\" bgcolor=\"#FFFFFF\">\n"
            + "                    <div class=\"content\">\n" + "                        <table>\n"
            + "                            <tr>\n" + "                                <td>\n"
            + "                                    <h3>Hola, " + USUARIO2 + "</h3>\n"
            + "                                    <p class=\"callout\">\n"
            + "                                        " + CONTENIDO + "\n"
            + "                                    </p>\n" + "                                    <p>\n"
            + "                                        <table style=\"font-size: medium\">\n"
            + "                                            <tr>\n"
            + "                                                <td>Folio: " + LISTA + "</td>\n"
            + "                                            </tr>\n"
            + "                                        </table>\n"
            + "                                    </p> <br/>\n"
            + "                                     <table>\n"
            + "                                         <tr>\n"
            + "                                             <td>\n"
            + "                                                 <p>\n"
            + "                                                     <a href=\"http://www.sgcon-infonavit.com\" class=\"soc-btn fb\">Ir a la aplicacin</a> \n"
            + "                                                 </p>\n"
            + "                                             </td>\n"
            + "                                         </tr>\n"
            + "                                     </table\n" + "                                </td>\n"
            + "                            </tr>\n" + "                        </table>\n"
            + "                    </div>\n" + "                </td>\n" + "                <td></td>\n"
            + "            </tr>\n" + "        </table>\n" + "    </body>");

    Body body = new Body().withHtml(htmlContent);

    // Create a message with the specified subject and body.
    Message message = new Message().withSubject(subject).withBody(body);

    // Assemble the email.
    SendEmailRequest request = new SendEmailRequest().withSource(FROM).withDestination(destination)
            .withMessage(message);//w ww.  ja  v  a2 s .  com

    try {
        System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java...");

        /*
         * The ProfileCredentialsProvider will return your [default]
         * credential profile by reading from the credentials file located at
         * (~/.aws/credentials).
         *
         * TransferManager manages a pool of threads, so we create a
         * single instance and share it throughout our application.
         */
        /*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);
         }*/
        AWSCredentials awsCreds = new BasicAWSCredentials("AKIAJFO4NNHIPNTB4ZCQ",
                "VjYeQ9+xj3HAcLBSxxxbHTo6jy2ft0wF6tgWZXmA");
        // Instantiate an Amazon SES client, which will make the service call with the supplied AWS credentials.
        //AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials);
        AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(awsCreds);

        // Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your production
        // access status, sending limits, and Amazon SES identity-related settings are specific to a given
        // AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using
        // the US East (N. Virginia) region. Examples of other regions that Amazon SES supports are US_WEST_2
        // and EU_WEST_1. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html
        Region REGION = Region.getRegion(Regions.US_WEST_2);
        client.setRegion(REGION);

        // Send the email.
        client.sendEmail(request);
        System.out.println("Email sent!");

    } catch (Exception ex) {
        System.out.println("The email was not sent.");
        System.out.println("Error message: " + ex.getMessage());
    }
}

From source file:com.appdynamics.connectors.ConnectorLocator.java

License:Apache License

public AmazonEC2 getConnector(IProperty[] properties, IControllerServices controllerServices) {
    String accessKey = Utils.getAccessKey(properties, controllerServices);
    String secretKey = Utils.getSecretKey(properties, controllerServices);

    AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);

    // TODO: FIX CORE-3805
    // for now return a new instance everytime.
    // We have lot of Multi tenancy and compute centers and image repositores
    // containing the same AWS account information issues
    if (true) {/*from   w  w w .j  ava2 s .  c o m*/
        return new AmazonEC2Client(awsCredentials);
    }

    synchronized (connectorLock) {
        AmazonEC2 ec2 = accessKeyVsEc2.get(accessKey);
        if (ec2 != null)
            return ec2;
        ec2 = new AmazonEC2Client(awsCredentials);
        accessKeyVsEc2.put(accessKey, ec2);

        return ec2;
    }
}

From source file:com.appdynamics.extensions.cloudwatch.configuration.ConfigurationUtil.java

License:Apache License

private static void initializeAWSCredentials(Configuration awsConfiguration, Document doc) {
    if (doc.getElementsByTagName("AWSCredentials").item(0) == null) {
        // not specified, use default handler chain of amazon sdk like using IAM instance profiles
        return;/*w w w .  j a va2s .  co m*/
    }

    Element credentialsFromFile = (Element) doc.getElementsByTagName("AWSCredentials").item(0);
    if (credentialsFromFile.getElementsByTagName("EncryptionKey").item(0) != null) {
        String encryptionKey = doc.getElementsByTagName("EncryptionKey").item(0).getTextContent();
        String encryptedAccessKey = credentialsFromFile.getElementsByTagName("EncryptedAccessKey").item(0)
                .getTextContent();
        String encryptedSecretKey = credentialsFromFile.getElementsByTagName("EncryptedSecretKey").item(0)
                .getTextContent();
        Decryptor decryptor = new Decryptor(encryptionKey);
        awsConfiguration.awsCredentials = new BasicAWSCredentials(decryptor.decrypt(encryptedAccessKey),
                decryptor.decrypt(encryptedSecretKey));
    } else {
        String accessKey = credentialsFromFile.getElementsByTagName("AccessKey").item(0).getTextContent();
        String secretKey = credentialsFromFile.getElementsByTagName("SecretKey").item(0).getTextContent();
        awsConfiguration.awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
    }

}

From source file:com.appdynamics.monitors.s3.config.ConfigurationUtil.java

License:Apache License

/**
 * Reads the config file in the S3 monitor home directory and retrieves AWS
 * credentials and other configuration// w  w  w  . j a v a 2 s  .  com
 * 
 * @param filePath
 *            Path to the configuration file
 * @return Configuration Configuration object containing AWS credentials and
 *         other details
 */
public static Configuration getConfigurations(String filePath) {

    // Creating config object
    Configuration awsConfiguration = new Configuration();
    BufferedInputStream configFile = null;

    try {
        logger.info("Reading config file::" + filePath);

        // Getting file name and reading yaml config file
        String fileName = getConfigFilename(filePath);
        configFile = new BufferedInputStream(new FileInputStream(fileName));
        Yaml yaml = new Yaml();

        // Reading mandatory configurations (access and secret key)
        @SuppressWarnings("unchecked")
        Map<String, Object> config = (Map<String, Object>) ((Map<String, Object>) yaml.load(configFile))
                .get(AWSS3Constants.KEY_CONFIG);

        @SuppressWarnings("unchecked")
        Map<String, Object> awsCredentials = (Map<String, Object>) config
                .get(AWSS3Constants.KEY_AWSCREDENTIALS);

        awsConfiguration.setAwsCredentials(
                new BasicAWSCredentials(awsCredentials.get(AWSS3Constants.KEY_ACCESSKEY).toString(),
                        awsCredentials.get(AWSS3Constants.KEY_SECRETKEY).toString()));

        // Reading optional configurations (buckets, sizeunit, timeunit)

        if (config.containsKey(AWSS3Constants.KEY_BUCKETS) && config.get(AWSS3Constants.KEY_BUCKETS) != null) {
            @SuppressWarnings("unchecked")
            Set<String> bucketNames = (Set<String>) config.get(AWSS3Constants.KEY_BUCKETS);
            awsConfiguration.setBucketNames(bucketNames);
        }

        if (config.containsKey(AWSS3Constants.KEY_SIZEUNIT)
                && config.get(AWSS3Constants.KEY_SIZEUNIT) != null) {
            String sizeUnit = (String) config.get(AWSS3Constants.KEY_SIZEUNIT);
            awsConfiguration.setSizeUnit(sizeUnit);
        } else {
            // Setting default value (KB) for sizeunit
            awsConfiguration.setSizeUnit(AWSS3Constants.SIZE_KB);
        }

        if (config.containsKey(AWSS3Constants.KEY_TIMEUNIT)
                && config.get(AWSS3Constants.KEY_TIMEUNIT) != null) {
            String timeUnit = (String) config.get(AWSS3Constants.KEY_TIMEUNIT);
            awsConfiguration.setTimeUnit(timeUnit);
        } else {
            // Setting default value (Seconds) for sizeunit
            awsConfiguration.setTimeUnit(AWSS3Constants.TIMEUNIT_SECONDS);
        }

        return awsConfiguration;
    } catch (Exception exception) {
        logger.error("Error reading config file: " + exception.getMessage(), exception);
    }

    finally {
        try {
            if (configFile != null)
                configFile.close();
        } catch (IOException ioException) {
            logger.error("Error occurred while closing configuration file!!");
        }
    }

    return awsConfiguration;
}

From source file:com.athena.dolly.web.aws.s3.S3Service.java

License:Open Source License

@PostConstruct
public void init() {
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    s3 = new AmazonS3Client(credentials);
}

From source file:com.atlantbh.jmeter.plugins.aws.s3.AWSS3Downloader.java

License:Apache License

@Override
public SampleResult sample(Entry arg0) {
    LOGGER.info("Download started....");
    SampleResult result = new SampleResult();
    result.setSampleLabel(getName());/*  www  .j a  va  2  s. co  m*/
    result.setDataType(SampleResult.TEXT);
    result.sampleStart();
    try {
        BasicAWSCredentials creds = new BasicAWSCredentials(getKey(), getSecret());
        AmazonS3 client = new AmazonS3Client(creds);
        S3Object s3Object = client.getObject(new GetObjectRequest(new S3ObjectId(getBucket(), getObject())));
        InputStream is = s3Object.getObjectContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(getDestination())));
        char[] buffer = new char[1024 * 1024];
        while (true) {
            int c = reader.read(buffer);
            if (c == -1) {
                break;
            }
            bufferedWriter.write(buffer);
        }
        reader.close();
        bufferedWriter.close();
        LOGGER.info("Download finished.");
        result.setResponseData("Download finished".getBytes());
        result.setSuccessful(!false);
        result.setResponseCode("200");
        result.setResponseMessage("Downloaded");
    } catch (Exception e) {
        LOGGER.info("Download error.");
        result.setResponseData(("Download error: " + e.getMessage()).getBytes());
        result.setSuccessful(false);
        result.setResponseCode("500");
        result.setResponseMessage("Error");
    }
    result.sampleEnd();
    return result;
}

From source file:com.atlantbh.jmeter.plugins.aws.s3.AWSS3Reader.java

License:Apache License

@Override
public SampleResult sample(Entry arg0) {
    LOGGER.info("Read started....");
    SampleResult result = new SampleResult();
    result.setSampleLabel(getName());/*from  w  ww.j av a 2 s . c o  m*/
    result.setDataType(SampleResult.TEXT);
    result.sampleStart();
    try {
        BasicAWSCredentials creds = new BasicAWSCredentials(getKey(), getSecret());
        AmazonS3 client = new AmazonS3Client(creds);
        S3Object s3Object = client.getObject(new GetObjectRequest(new S3ObjectId(getBucket(), getObject())));
        InputStream is = s3Object.getObjectContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        result.setResponseData(sb.toString().getBytes());
        reader.close();
        LOGGER.info("Read finished.");
        result.setSuccessful(!false);
        result.setResponseCode("200");
        result.setResponseMessage("Read done");
        result.setContentType("text/plain");
    } catch (Exception e) {
        LOGGER.info("Read error.");
        result.setResponseData(("Read error: " + e.getMessage()).getBytes());
        result.setSuccessful(false);
        result.setResponseCode("500");
        result.setResponseMessage("Error");
    }
    result.sampleEnd();
    return result;
}

From source file:com.atlantbh.jmeter.plugins.aws.s3.AWSS3Uploader.java

License:Apache License

@Override
public SampleResult sample(Entry arg0) {
    LOGGER.info("Upload started....");
    SampleResult result = new SampleResult();
    result.setSampleLabel(getName());//  w  w w .  ja  v a 2s  .co m
    result.setDataType(SampleResult.TEXT);
    result.sampleStart();
    try {
        BasicAWSCredentials creds = new BasicAWSCredentials(getKey(), getSecret());
        AmazonS3 client = new AmazonS3Client(creds);

        client.putObject(getBucket(), getDestination(), new File(getObject()));

        LOGGER.info("Upload finished.");
        result.setResponseData("Upload finished".getBytes());
        result.setSuccessful(!false);
        result.setResponseCode("200");
        result.setResponseMessage("Uploaded");
    } catch (Exception e) {
        LOGGER.info("Upload error.");
        result.setResponseData(("Upload error: " + e.getMessage()).getBytes());
        result.setSuccessful(false);
        result.setResponseCode("500");
        result.setResponseMessage("Error");
    }
    result.sampleEnd();
    return result;
}