Java com.amazonaws.auth.AWSCredentialsProvider 代码实例

・19 分钟阅读

以下是展示如何使用com.amazonaws.auth.AWSCredentialsProvider的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Test
public void testWithPlaceHolder() throws Exception {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-testWithPlaceHolder.xml", getClass());
        AWSCredentialsProvider awsCredentialsProvider = applicationContext.getBean(AWSCredentialsProvider.class);
        AWSCredentials credentials = awsCredentialsProvider.getCredentials();
        assertEquals("foo", credentials.getAWSAccessKeyId());
        assertEquals("bar", credentials.getAWSSecretKey());
}
 

实例 2


/**
 * The UploadPolicy method creates the S3 upload policy for the aMediaManager application.
 * Much of this is hard coded and would have to change with any changes to the fields in the S3
 * upload form.
 *
 * @param key            this is not currently used.
 * @param redirectUrl    this is the URL to which S3 will redirect the browser on successful upload.
 * @return                the upload policy string is returned.
 */
 String generateUploadPolicy(String s3BucketName, String keyPrefix, AWSCredentialsProvider credsProvider, String redirectUrl) {
    Calendar dateTime = Calendar.getInstance();
    // add the offset from UTC
    dateTime.add(Calendar.MILLISECOND, -dateTime.getTimeZone().getOffset(dateTime.getTimeInMillis()));
    // add 15 minutes more for skew
    dateTime.add(Calendar.MINUTE, 15);
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    String expirationDate = dateFormatter.format(dateTime.getTime());
    StringBuilder sb = new StringBuilder();
    sb.append("{ "expiration": "" + expirationDate + "",");
    sb.append(""conditions": [ { "bucket": "" + s3BucketName  + "" }, ");
    sb.append("["starts-with", "$key", "" + keyPrefix + "/"], ");
    sb.append("{ "success_action_redirect": "" + redirectUrl + "" },");
    sb.append("["eq", "$x-amz-meta-bucket", "" + s3BucketName + ""], ");
    sb.append("["starts-with", "$x-amz-meta-owner", ""], ");
    sb.append("["starts-with", "$x-amz-meta-uuid", ""], ");
    sb.append("["starts-with", "$x-amz-meta-title", ""], ");
    sb.append("["starts-with", "$x-amz-meta-tags", ""], ");
    sb.append("["starts-with", "$x-amz-meta-createdDate", ""], ");
    sb.append("["starts-with", "$x-amz-meta-description", ""], ");
    sb.append("["starts-with", "$x-amz-meta-privacy", ""], ");
    sb.append("["starts-with", "$Content-Type", "video/"], ");
    if(credsProvider.getCredentials() instanceof BasicSessionCredentials) {
        sb.append("["starts-with", "$x-amz-security-token", ""], ");
    }
    sb.append("["content-length-range", 0, 1073741824] ] }");
    return sb.toString();
}
 

实例 3


@Test
public void testStream() throws IOException {
    AWSCredentialsProvider provider = new ProfileCredentialsProvider("aws-testing");
    ClientConfiguration config = new ClientConfiguration();
    AmazonS3 client = new AmazonS3Client(provider.getCredentials(), config);
    String bucketName = "test-bucket-" + System.currentTimeMillis();
    client.createBucket(bucketName);
    TransferManager tx = new TransferManager(client);
    Uploader uploader = new PutRequestUploader(tx.getAmazonS3Client());
    OutputStream outputStream = new S3MemBufferedOutputStream(uploader, bucketName,
            new DefaultFileNameFormat().withPrefix("test"), "text/plain");
    OutputStreamWriter writer = new OutputStreamWriter(outputStream);
    PrintWriter printer = new PrintWriter(writer);
    printer.println("line1");
    printer.println("line2");
    printer.close();
    ObjectListing objectListing = client.listObjects(bucketName);
    List<S3ObjectSummary> objectSummaries = objectListing.getObjectSummaries();
    assertEquals(1, objectSummaries.size());
    S3ObjectSummary s3ObjectSummary = objectSummaries.get(0);
    InputStreamReader reader = new InputStreamReader(client.getObject(bucketName, s3ObjectSummary.getKey()).getObjectContent());
    BufferedReader r = new BufferedReader(reader);
    assertEquals("line1", r.readLine());
    assertEquals("line2", r.readLine());
    client.deleteObject(bucketName, s3ObjectSummary.getKey());
    client.deleteBucket(bucketName);
}
 

实例 4


/**
 * The only information needed to create a client are security credentials -
 * your AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints have defaults provided.
 *
 * Additional client parameters, such as proxy configuration, can be specified
 * in an optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.PropertiesCredentials
 * @see com.amazonaws.ClientConfiguration
 */
private static void init() throws Exception {
    /*
     * ProfileCredentialsProvider loads AWS security credentials from a
     * .aws/config file in your home directory.
     *
     * These same credentials are used when working with other AWS SDKs and the AWS CLI.
     *
     * You can find more information on the AWS profiles config file here:
     * http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
     */
    File configFile = new File(System.getProperty("user.home"), ".aws/credentials");
    AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider(
        new ProfilesConfigFile(configFile), "default");
    if (credentialsProvider.getCredentials() == null) {
        throw new RuntimeException("No AWS security credentials found:n"
                + "Make sure you've configured your credentials in: " + configFile.getAbsolutePath() + "n"
                + "For more information on configuring your credentials, see "
                + "http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html");
    }
    ec2 = new AmazonEC2Client(credentialsProvider);
    s3  = new AmazonS3Client(credentialsProvider);
}
 

实例 5


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

实例 6


private AWSCredentialsProvider initCredentials() {
    // Attempt to use any credentials specified in context.xml first
    if (credentialsExistInContextConfig()) {
        // Fail fast if credentials aren't valid as user has likely made a configuration mistake
        if (credentialsInContextConfigAreValid()) {
            throw new AmazonClientException("Incomplete AWS security credentials specified in context.xml.");
        }
        logger.debug("Using AWS access key ID and secret key from context.xml");
        return new StaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey));
    }
    // Use any explicitly specified credentials properties file next
    if (credentialsFile != null) {
        try {
            logger.debug("Reading security credentials from properties file: " + credentialsFile);
            PropertiesCredentials credentials = new PropertiesCredentials(credentialsFile);
            logger.debug("Using AWS credentials from file: " + credentialsFile);
            return new StaticCredentialsProvider(credentials);
        } catch (Exception e) {
            throw new AmazonClientException(
                    "Unable to read AWS security credentials from file specified in context.xml: "
                            + credentialsFile,
                    e);
        }
    }
    // Fall back to the default credentials chain provider if credentials weren't explicitly set
    AWSCredentialsProvider defaultChainProvider = new DefaultAWSCredentialsProviderChain();
    if (defaultChainProvider.getCredentials() == null) {
        logger.debug("Loading security credentials from default credentials provider chain.");
        throw new AmazonClientException("Unable to find AWS security credentials.  "
                + "Searched JVM system properties, OS env vars, and EC2 instance roles.  "
                + "Specify credentials in Tomcat's context.xml file or put them in one of the places mentioned 上面.");
    }
    logger.debug("Using default AWS credentials provider chain to load credentials");
    return defaultChainProvider;
}
 

实例 7


private static void configure(String propertiesFile) throws IOException {
    if (propertiesFile != null) {
        loadProperties(propertiesFile);
    }
    // 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 classpath. 
   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 ClasspathPropertiesFileCredentialsProvider();
        // 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 ); 
}
 

实例 8


private static void configure(String propertiesFile) throws IOException {
       if (propertiesFile != null) {
           loadProperties(propertiesFile);
       }
       // 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);
   }
 

实例 9


private static void configure(String propertiesFile) throws IOException {
        if (propertiesFile != null) {
            loadProperties(propertiesFile);
        }
        // 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);
    }
 

实例 10


@Test
public void testWithFixedAWSKeys() {
  S3StorageDruidModule module = new S3StorageDruidModule();
  AWSCredentialsConfig config = EasyMock.createMock(AWSCredentialsConfig.class);
  EasyMock.expect(config.getAccessKey()).andReturn("accessKeySample").atLeastOnce();
  EasyMock.expect(config.getSecretKey()).andReturn("secretKeySample").atLeastOnce();
  EasyMock.replay(config);
  AWSCredentialsProvider provider = module.getAWSCredentialsProvider(config);
  AWSCredentials credentials = provider.getCredentials();
  assertEquals(credentials.getAWSAccessKeyId(), "accessKeySample");
  assertEquals(credentials.getAWSSecretKey(), "secretKeySample");
  // try to create
  module.getRestS3Service(provider);
}
 

实例 11


/**
 * Inits the credentials.
 *
 * @return the AWS credentials provider
 * @throws Exception the exception
 */
public static AWSCredentialsProvider initCredentials() throws Exception {
        // 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;
}
 
讨论
淘淘あ西西 profile image