Example usage for com.amazonaws.auth AWSCredentials getAWSAccessKeyId

List of usage examples for com.amazonaws.auth AWSCredentials getAWSAccessKeyId

Introduction

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

Prototype

public String getAWSAccessKeyId();

Source Link

Document

Returns the AWS access key ID for this credentials object.

Usage

From source file:aws.sample.AmazonDynamoDBSample.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials consisting of the AWS Access Key ID and Secret Access Key. All other configuration, such as the service endpoints, are performed automatically. Client parameters, such as proxies, can be specified in an optional ClientConfiguration object when constructing a client.
 * /*w ww  .  j a v a  2  s .  c  o m*/
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.PropertiesCredentials
 * @see com.amazonaws.ClientConfiguration
 */
private static void init() throws Exception {
    System.setProperty("com.amazonaws.sdk.disableCertChecking", "true");

    AWSCredentials credentials = new PropertiesCredentials(
            AmazonDynamoDBSample.class.getResourceAsStream("/AwsCredentials.properties"));
    Debug.line(credentials.getAWSAccessKeyId(), credentials.getAWSSecretKey());
    dynamoDB = new AmazonDynamoDBClient(credentials);

}

From source file:com.ajah.email.data.AmazonSESTransport.java

License:Apache License

/**
 * Sends a message through Amazon's SES service.
 * //w w  w  .  jav  a2s  .  com
 * @param message
 *            The message to send. Subject, from and to are required.
 * @throws AddressException
 *             If there is a problem with one of the email addresses.
 * @throws MessagingException
 *             If there is a problem with the transport of the message.
 */
@Override
public void send(final EmailMessage message) throws AddressException, MessagingException {
    AjahUtils.requireParam(message, "message");
    AjahUtils.requireParam(message.getSubject(), "message.subject");
    AjahUtils.requireParam(message.getFrom(), "message.from");
    AjahUtils.requireParam(message.getRecipients(), "message.recipients");

    final AWSCredentials credentials = new BasicAWSCredentials(Config.i.get("aws.accessKey", null),
            Config.i.get("aws.secretKey", null));
    if (Config.i.getBoolean("aws.ses.verify", false)) {
        // Verification is active so we'll need to check that first
        final AmazonSimpleEmailService email = new AmazonSimpleEmailServiceClient(credentials);
        final ListVerifiedEmailAddressesResult verifiedEmails = email.listVerifiedEmailAddresses();
        boolean verified = true;
        if (!isVerified(message.getFrom(), email, verifiedEmails)) {
            log.warning("Sender " + message.getFrom() + " is not verified");
            verified = false;
        }
        for (final EmailRecipient emailRecipient : message.getRecipients()) {
            if (!isVerified(emailRecipient.getAddress(), email, verifiedEmails)) {
                log.warning("Recipient " + emailRecipient.getAddress() + " is not verified");
                verified = false;
            }
        }
        if (!verified) {
            throw new MessagingException("Message not sent because one or more addresses need to be verified");
        }
    }
    final Properties props = new Properties();
    props.setProperty("mail.transport.protocol", "aws");
    props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
    props.setProperty("mail.aws.password", credentials.getAWSSecretKey());

    final Session session = Session.getInstance(props);

    final MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress(message.getFrom().toString()));
    for (final EmailRecipient emailRecipient : message.getRecipients()) {
        switch (emailRecipient.getType()) {
        case BCC:
            mimeMessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(emailRecipient.toString()));
            break;
        case CC:
            mimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(emailRecipient.toString()));
            break;
        case TO:
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(emailRecipient.toString()));
            break;
        default:
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(emailRecipient.toString()));
            break;
        }
    }
    mimeMessage.setSubject(message.getSubject());
    final String htmlContent = message.getHtml();
    if (StringUtils.isBlank(htmlContent)) {
        // No HTML so we'll just send a plaintext message.
        mimeMessage.setText(message.getText());
    } else {
        final Multipart multiPart = new MimeMultipart("alternative");

        final BodyPart text = new MimeBodyPart();
        text.setText(message.getText());
        multiPart.addBodyPart(text);

        final BodyPart html = new MimeBodyPart();
        html.setContent(message.getHtml(), "text/html");
        multiPart.addBodyPart(html);

        mimeMessage.setContent(multiPart);
    }
    mimeMessage.saveChanges();

    final Transport transport = new AWSJavaMailTransport(session, null);
    transport.connect();
    transport.sendMessage(mimeMessage, null);
    transport.close();

}

From source file:com.ajah.email.data.EmailMessageManager.java

License:Apache License

/**
 * Sends a message through Amazon's SES service.
 * /*  ww  w . j a  v a2  s  . c  om*/
 * @param message
 *            The message to send. Subject, from and to are required.
 * @throws AddressException
 *             If there is a problem with one of the email addresses.
 * @throws MessagingException
 *             If there is a problem with the transport of the message.
 */
public static void send(final EmailMessage message) throws AddressException, MessagingException {
    AjahUtils.requireParam(message, "message");
    AjahUtils.requireParam(message.getSubject(), "message.subject");
    AjahUtils.requireParam(message.getFrom(), "message.from");
    AjahUtils.requireParam(message.getTo(), "message.to");

    final AWSCredentials credentials = new BasicAWSCredentials(Config.i.get("aws.accessKey", null),
            Config.i.get("aws.secretKey", null));
    if (Config.i.getBoolean("aws.ses.verify", false)) {
        // Verification is active so we'll need to check that first
        final AmazonSimpleEmailService email = new AmazonSimpleEmailServiceClient(credentials);
        final ListVerifiedEmailAddressesResult verifiedEmails = email.listVerifiedEmailAddresses();
        boolean verified = true;
        if (!isVerified(message.getFrom(), email, verifiedEmails)) {
            log.warning("Sender " + message.getFrom() + " is not verified");
            verified = false;
        }
        for (final EmailAddress emailAddress : message.getTo()) {
            if (!isVerified(emailAddress, email, verifiedEmails)) {
                log.warning("Recipient " + emailAddress + " is not verified");
                verified = false;
            }
        }
        if (!verified) {
            throw new MessagingException("Message not sent because one or more addresses need to be verified");
        }
    }
    final Properties props = new Properties();
    props.setProperty("mail.transport.protocol", "aws");
    props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
    props.setProperty("mail.aws.password", credentials.getAWSSecretKey());

    final Session session = Session.getInstance(props);

    final MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress(message.getFrom().toString()));
    for (final EmailAddress to : message.getTo()) {
        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to.toString()));
    }
    mimeMessage.setSubject(message.getSubject());
    final String htmlContent = message.getHtml();
    if (StringUtils.isBlank(htmlContent)) {
        // No HTML so we'll just send a plaintext message.
        mimeMessage.setText(message.getText());
    } else {
        final Multipart multiPart = new MimeMultipart("alternative");

        final BodyPart text = new MimeBodyPart();
        text.setText(message.getText());
        multiPart.addBodyPart(text);

        final BodyPart html = new MimeBodyPart();
        html.setContent(message.getHtml(), "text/html");
        multiPart.addBodyPart(html);

        mimeMessage.setContent(multiPart);
    }
    mimeMessage.saveChanges();

    final Transport transport = new AWSJavaMailTransport(session, null);
    transport.connect();
    transport.sendMessage(mimeMessage, null);
    transport.close();

}

From source file:com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentialsBinding.java

License:Open Source License

@Override
public MultiEnvironment bind(@Nonnull Run<?, ?> build, FilePath workspace, Launcher launcher,
        TaskListener listener) throws IOException, InterruptedException {
    AWSCredentials credentials = getCredentials(build).getCredentials();
    Map<String, String> m = new HashMap<String, String>();
    m.put(accessKeyVariable, credentials.getAWSAccessKeyId());
    m.put(secretKeyVariable, credentials.getAWSSecretKey());

    // If role has been assumed, STS requires AWS_SESSION_TOKEN variable set too.
    if (credentials instanceof AWSSessionCredentials) {
        m.put(SESSION_TOKEN_VARIABLE_NAME, ((AWSSessionCredentials) credentials).getSessionToken());
    }//from w  ww. j a  v  a 2s .c  om
    return new MultiEnvironment(m);
}

From source file:com.dxc.temp.SimpleQueueServiceSample.java

License:Open Source License

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

    BasicConfigurator.configure();/*from www. j ava2s.  c  om*/

    /*
     * 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);
    }
    System.out.println(String.format("Found AWSAccessKeyId: %s", credentials.getAWSAccessKeyId()));
    System.out.println(String.format("Found AWSAccessSecretKey: %s", credentials.getAWSSecretKey()));

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usEast1);

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon SQS");
    System.out.println("===========================================\n");

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called MyQueue.\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
        String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

        // List queues
        System.out.println("Listing all queues in your account.\n");
        for (String queueUrl : sqs.listQueues().getQueueUrls()) {
            System.out.println("  QueueUrl: " + queueUrl);
        }
        System.out.println();

        // Send a message
        System.out.println("Sending a message to MyQueue.\n");
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, "Message body text"));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        for (Message message : messages) {
            System.out.println("  Message");
            System.out.println("    MessageId:     " + message.getMessageId());
            System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
            System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
            System.out.println("    Body:          " + message.getBody());
            for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
        }
        System.out.println();

        // Delete a message
        //            System.out.println("Deleting a message.\n");
        //            String messageReceiptHandle = messages.get(0).getReceiptHandle();
        //            sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));

        // Delete a queue
        // You must wait 60 seconds after deleting a queue before you can create another with the same name
        //            System.out.println("Deleting the test queue.\n");
        //            sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, 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 SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.emc.vipr.services.s3.ViPRS3Signer.java

License:Open Source License

@Override
public void sign(Request<?> request, AWSCredentials credentials) throws AmazonClientException {
    if (credentials == null || credentials.getAWSSecretKey() == null) {
        log.debug("Canonical string will not be signed, as no AWS Secret Key was provided");
        return;//w ww  .  ja  v  a2  s. c  o  m
    }

    AWSCredentials sanitizedCredentials = sanitizeCredentials(credentials);
    if (sanitizedCredentials instanceof AWSSessionCredentials) {
        addSessionCredentials(request, (AWSSessionCredentials) sanitizedCredentials);
    }

    /*
     * In s3 sigv2, the way slash characters are encoded should be
     * consistent in both the request url and the encoded resource path.
     * Since we have to encode "//" to "/%2F" in the request url to make
     * httpclient works, we need to do the same encoding here for the
     * resource path.
     */
    String encodedResourcePath = HttpUtils.appendUri(request.getEndpoint().getPath(), resourcePath, true);

    Date date = getSignatureDate(request.getTimeOffset());
    request.addHeader(Headers.DATE, ServiceUtils.formatRfc822Date(date));
    String canonicalString = makeS3CanonicalString(httpVerb, encodedResourcePath, request, null);
    log.debug("Calculated string to sign:\n\"" + canonicalString + "\"");

    String signature = super.signAndBase64Encode(canonicalString, sanitizedCredentials.getAWSSecretKey(),
            SigningAlgorithm.HmacSHA1);
    request.addHeader("Authorization", "AWS " + sanitizedCredentials.getAWSAccessKeyId() + ":" + signature);
}

From source file:com.eucalyptus.objectstorage.client.OsgInternalS3Client.java

License:Open Source License

/**
 * Basically an .equals() call for AWSCreds
 * @param c1// w ww. ja  v  a2s.com
 * @param c2
 * @return
 */
private static boolean credentialsEqual(AWSCredentials c1, AWSCredentials c2) {
    return (c1 == null && c2 == null) || (c1 == null || c2 == null)
            || (c1.getAWSSecretKey() != null && c1.getAWSSecretKey().equals(c2.getAWSSecretKey())
                    && c1.getAWSAccessKeyId() != null && c1.getAWSAccessKeyId().equals(c2.getAWSAccessKeyId()));
}

From source file:com.github.jramos.snowplow.RedshiftSinkEmitter.java

License:Apache License

protected String generateCopyStatement(String s3File, AWSCredentials credentials) {
    StringBuilder exec = new StringBuilder();
    exec.append("COPY ").append(redshiftTable).append(" ");
    exec.append("FROM 's3://").append(s3Bucket).append("/").append(s3File).append("' ");
    exec.append("CREDENTIALS 'aws_access_key_id=").append(credentials.getAWSAccessKeyId());
    exec.append(";aws_secret_access_key=").append(credentials.getAWSSecretKey());
    if (credentials instanceof BasicSessionCredentials) {
        BasicSessionCredentials sessionCredentials = (BasicSessionCredentials) credentials;
        exec.append(";token=").append(sessionCredentials.getSessionToken());
    }/*from  ww  w .  jav a 2  s . c  om*/
    exec.append("' DELIMITER '").append(redshiftDelimiter).append("'");

    if (configuration instanceof RedshiftSinkConfiguration) {
        RedshiftSinkConfiguration redshiftSinkConfiguration = (RedshiftSinkConfiguration) configuration;
        if (redshiftSinkConfiguration.hasRedshiftOptions()) {
            List<String> options = redshiftSinkConfiguration.getRedshiftOptions();
            for (String option : options) {
                exec.append(" ").append(option);
            }
        }
    }
    exec.append(";");
    return exec.toString();
}

From source file:com.hussi.aws.dynamoDB.AmazonDynamoDBSample.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials
 * consisting of the AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints, are performed
 * automatically. Client parameters, such as proxies, can be specified in an
 * optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.ProfilesConfigFile
 * @see com.amazonaws.ClientConfiguration
 *//*  w  ww . j a  v  a2 s. com*/
private static void init() throws Exception {
    /*
     * 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();
        System.out.println("credentials.getAWSAccessKeyId()===>>>" + credentials.getAWSAccessKeyId());
        System.out.println("credentials.getAWSSecretKey()===>>>" + credentials.getAWSSecretKey());
        //System.exi   t(0);

    } 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);
    }
    dynamoDB = new AmazonDynamoDBClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    dynamoDB.setRegion(usWest2);
}

From source file:com.yahoo.athenz.example.zts.tls.client.ZTSAWSCredsClient.java

License:Apache License

private static boolean retrieveAWSTempCreds(AWSCredentialsProvider awsCredProvider) {

    try {/*from  w ww.  j  av  a 2s .  c  o  m*/
        // just for testing purposes we're going to run this code
        // for 2 hours and keep asking for credentials every minute
        // to make sure zts client is caching the creds and giving
        // us new ones when they're about to expire

        for (int i = 0; i < 120; i++) {
            AWSCredentials awsCreds = awsCredProvider.getCredentials();
            if (awsCreds == null) {
                System.out.println("Error: AWS Credentials are not available");
                return false;
            }
            System.out.println("AWS Temporary Credentials:\n");
            System.out.println("\tAccess Key Id : " + awsCreds.getAWSAccessKeyId());
            System.out.println("\tSecret Key    : " + awsCreds.getAWSSecretKey());
            try {
                Thread.sleep(60000);
            } catch (InterruptedException ex) {
            }
        }
    } catch (ZTSClientException ex) {
        System.out.println("Unable to retrieve AWS credentials: " + ex.getMessage());
        return false;
    }
    return true;
}