Example usage for com.amazonaws.auth AWSCredentialsProvider getCredentials

List of usage examples for com.amazonaws.auth AWSCredentialsProvider getCredentials

Introduction

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

Prototype

public AWSCredentials getCredentials();

Source Link

Document

Returns AWSCredentials which the caller can use to authorize an AWS request.

Usage

From source file:com.github.sporcina.mule.modules.DynamoDBConnector.java

License:Open Source License

/**
 * Creates a DynamoDB client using the security values from the AWSCredentials.properties file
 *
 * @throws ConnectionException//from w w  w.  jav  a  2 s  . c om
 */
private void createDynamoDBClient() throws ConnectionException {
    AWSCredentialsProvider credentialsProvider = new ClasspathPropertiesFileCredentialsProvider();
    try {
        credentialsProvider.getCredentials();
    } catch (AmazonClientException e) {
        LOG.warn(
                "AWSCredentials.properties file was not found.  Attempting to acquire credentials from the default provider chain.");
        throw new ConnectionException(ConnectionExceptionCode.INCORRECT_CREDENTIALS, null, e.getMessage(), e);
    } catch (Exception e) {
        LOG.warn(e.getMessage() + "  Are you missing the AWSCredentials.properties file?");
        throw new ConnectionException(ConnectionExceptionCode.UNKNOWN, null, e.getMessage(), e);
    }

    try {
        setDynamoDBClient(new AmazonDynamoDBClient(credentialsProvider));
    } catch (Exception e) {
        throw new ConnectionException(ConnectionExceptionCode.UNKNOWN, null, e.getMessage(), e);
    }
}

From source file:com.ipcglobal.awscdh.util.Utils.java

License:Apache License

/**
 * Inits the credentials./*w  ww.  ja  v a  2  s.  co  m*/
 *
 * @return the AWS credentials provider
 */
public static AWSCredentialsProvider initCredentials() {
    // Get credentials from IMDS. If unsuccessful, get them from the
    // credential profiles file.
    AWSCredentialsProvider credentialsProvider = null;
    try {
        credentialsProvider = new DefaultAWSCredentialsProviderChain();
        // Verify we can fetch credentials from the provider
        credentialsProvider.getCredentials();
        //log.info("Obtained credentials from DefaultAWSCredentialsProviderChain.");
    } catch (AmazonClientException e) {
        log.error("Unable to obtain credentials from DefaultAWSCredentialsProviderChain", e);
    }
    return credentialsProvider;
}

From source file:com.ipcglobal.awscdh.util.Utils.java

License:Apache License

/**
 * Inits the credentials.//  w  w w.j  a  v  a  2s  .co  m
 *
 * @param credentialsFileName
 *            the credentials file name
 * @return the AWS credentials provider
 */
public static AWSCredentialsProvider initCredentials(String credentialsFileName) {
    // Get credentials from IMDS. If unsuccessful, get them from the
    // credential profiles file.
    AWSCredentialsProvider credentialsProvider = null;
    try {
        credentialsProvider = new InstanceProfileCredentialsProvider();
        // Verify we can fetch credentials from the provider
        credentialsProvider.getCredentials();
        log.info("Obtained credentials from the IMDS.");
    } catch (AmazonClientException e) {
        log.warn("Unable to obtain credentials from the IMDS, trying credentialsFileName");
        // If the credentialsFileName contains a path, assume it contains
        // the entire drive:/path/name.ext
        // this is necessary when running as a service on Windows
        String credentialsPathNameExt = null;
        // safest to check for both
        if (credentialsFileName.indexOf("/") > -1 || credentialsFileName.indexOf("\\") > -1)
            credentialsPathNameExt = credentialsFileName;
        else
            credentialsPathNameExt = System.getProperty("user.home") + System.getProperty("file.separator")
                    + ".aws" + System.getProperty("file.separator") + credentialsFileName;
        credentialsProvider = new PropertiesFileCredentialsProvider(credentialsPathNameExt);
        log.info("Obtained credentials from the credentialsFileName file.");
    }
    return credentialsProvider;
}

From source file:com.ipcglobal.awscdh.util.Utils.java

License:Apache License

/**
 * Inits the profile credentials provider.
 *
 * @param profileName the profile name//from ww w.  ja  va 2  s .c  o  m
 * @return the AWS credentials provider
 * @throws Exception the exception
 */
public static AWSCredentialsProvider initProfileCredentialsProvider(String profileName) throws Exception {
    // Get credentials from the ~/.aws/credentials file
    AWSCredentialsProvider credentialsProvider = null;
    try {
        credentialsProvider = new ProfileCredentialsProvider(profileName);
        // Verify we can fetch credentials from the provider
        credentialsProvider.getCredentials();
    } catch (AmazonClientException e) {
        log.error("Unable to obtain credentials from ProfileCredentialsProvider, profileName=" + profileName);
        throw e;
    }
    return credentialsProvider;
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.util.AwsCredentialUtil.java

License:Open Source License

public static AWSCredentials getAWSCredentials(String awsAccessKey, String awsSecretKey, String roleARN) {
    AWSCredentials awsCredentials;//from  w w  w  .j a  va  2s  .c om
    if (isNotEmpty(awsAccessKey) && isNotEmpty(awsSecretKey)) {
        awsCredentials = new BasicAWSCredentials(awsAccessKey.trim(), awsSecretKey.trim());

        // Use user long-term credentials to call the
        // AWS Security Token Service (STS) AssumeRole API, specifying
        // the ARN for the role -RO-role in amazon account.
        if (isNotEmpty(roleARN)) {
            AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(awsCredentials);

            AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(roleARN.trim())
                    .withRoleSessionName("JRSRequest");

            AssumeRoleResult assumeResult = null;
            try {
                assumeResult = stsClient.assumeRole(assumeRequest);
            } catch (Exception ex) {
                logger.error(ex);
                throw new JSShowOnlyErrorMessage(ex.getMessage());
            }

            // AssumeRole returns temporary security credentials for
            // the IAM role.
            awsCredentials = new BasicSessionCredentials(assumeResult.getCredentials().getAccessKeyId(),
                    assumeResult.getCredentials().getSecretAccessKey(),
                    assumeResult.getCredentials().getSessionToken());
        }
    } else {
        //Try getting Ec2 instance credentials.
        AWSCredentialsProvider instanceCredentialsProvider = new DefaultAWSCredentialsProviderChain();
        try {
            awsCredentials = instanceCredentialsProvider.getCredentials();
        } catch (Exception ex) {
            ApplicationContext ctx = StaticApplicationContext.getApplicationContext();
            MessageSource message = ctx.getBean("messageSource", MessageSource.class);

            logger.error("Exception loading default JRS instance credentials", ex);
            throw new JSShowOnlyErrorMessage(
                    message.getMessage("aws.exception.datasource.load.default.credentials", null,
                            LocaleContextHolder.getLocale()));
        }
    }
    return awsCredentials;
}

From source file:com.netflix.suro.sink.remotefile.AWSSessionCredentialsAdapter.java

License:Apache License

public AWSSessionCredentialsAdapter(AWSCredentialsProvider provider) {
    super(null, null, null);
    if (provider.getCredentials() instanceof com.amazonaws.auth.AWSSessionCredentials)
        this.provider = provider;
    else/*from w  w w .java2s.  c  o  m*/
        throw new IllegalArgumentException("provider does not contain session credentials");
}

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

License:Apache License

private static boolean retrieveAWSTempCreds(AWSCredentialsProvider awsCredProvider) {

    try {//from  w w w  .  j  a v a  2 s .com
        // 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;
}

From source file:dk.dma.nogoservice.service.S3DataLoader.java

License:Apache License

@Autowired
public S3DataLoader(@Value("${s3dataloader.tempdir:#{null}}") String tempDirLocation) {
    tempDirLocation = tempDirLocation != null ? tempDirLocation : System.getProperty("java.io.tmpdir");
    tempDir = new File(tempDirLocation);
    if (!tempDir.exists()) {
        cacheLocally = tempDir.mkdirs();
    } else {//from  w  ww  .  ja  v a  2 s.co  m
        cacheLocally = true;
    }

    AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
    try {
        credentialsProvider.getCredentials();
    } catch (SdkClientException e) {
        throw new IllegalStateException(
                "You must define AWS credentials in USER_HOME/.aws/credentials file on the machine. When running on AWS container service, "
                        + "the TaskRole should have permissions to read from S3");
    }

    AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard();
    builder.setCredentials(credentialsProvider);
    builder.setRegion("eu-west-1");
    amazonS3 = builder.build();
    Preconditions.checkArgument(amazonS3.doesBucketExist(DATA_BUCKET),
            "No AWS S3 bucket named " + DATA_BUCKET + " this bucket must exist");
}

From source file:gov.pnnl.cloud.KinesisApplication.java

License:Open Source License

private static void configure(String propertiesFile) throws IOException {

    if (propertiesFile != null) {
        loadProperties(propertiesFile);//ww  w  . ja v  a 2  s.  com
    }

    // ensure the JVM will refresh the cached IP values of AWS resources (e.g. service endpoints).
    java.security.Security.setProperty("networkaddress.cache.ttl", "60");

    String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID();
    LOG.info("Using workerId: " + workerId);

    // Get credentials from IMDS. If unsuccessful, get them from the credential profiles file.
    AWSCredentialsProvider credentialsProvider = null;
    try {
        credentialsProvider = new InstanceProfileCredentialsProvider();
        // Verify we can fetch credentials from the provider
        credentialsProvider.getCredentials();
        LOG.info("Obtained credentials from the IMDS.");
    } catch (AmazonClientException e) {
        LOG.info("Unable to obtain credentials from the IMDS, trying classpath properties", e);
        credentialsProvider = new ProfileCredentialsProvider();
        // Verify we can fetch credentials from the provider
        credentialsProvider.getCredentials();
        LOG.info("Obtained credentials from the properties file.");
    }

    LOG.info("Using credentials with access key id: "
            + credentialsProvider.getCredentials().getAWSAccessKeyId());

    kinesisClientLibConfiguration = new KinesisClientLibConfiguration(applicationName, streamName,
            credentialsProvider, workerId).withInitialPositionInStream(initialPositionInStream)
                    .withRegionName(kinesisEndpoint);
}

From source file:hudson.plugins.ec2.EC2Cloud.java

License:Open Source License

/***
 * Connect to an EC2 instance.//from   w ww. j  ava2s .  c  o m
 * @return {@link AmazonEC2} client
 */
public synchronized static AmazonEC2 connect(AWSCredentialsProvider credentialsProvider, URL endpoint) {
    awsCredentialsProvider = credentialsProvider;
    ClientConfiguration config = new ClientConfiguration();
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(endpoint.getHost());
    if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();
        config.setProxyHost(address.getHostName());
        config.setProxyPort(address.getPort());
        if (null != proxyConfig.getUserName()) {
            config.setProxyUsername(proxyConfig.getUserName());
            config.setProxyPassword(proxyConfig.getPassword());
        }
    }
    AmazonEC2 client = new AmazonEC2Client(credentialsProvider.getCredentials(), config);
    client.setEndpoint(endpoint.toString());
    return client;
}