Java 类com.amazonaws.auth.AWSCredentialsProviderChain 实例源码

项目:detective    文件:AwsUtils.java   
public static AWSCredentialsProvider getCredentialProviderC(Parameters config){
  List<AWSCredentialsProvider> providers = new ArrayList<AWSCredentialsProvider>();

  if ("YES".equals(config.get("aws.credentials.instaneProfile")))
    providers.add(new InstanceProfileCredentialsProvider());
  if ("YES".equals(config.get("aws.credentials.environmentVariable")))
    providers.add(new EnvironmentVariableCredentialsProvider());
  if ("YES".equals(config.get("aws.credentials.systemProperties")))
    providers.add(new SystemPropertiesCredentialsProvider());

  String accessKey = config.get("aws.credentials.accessKey").toString();
  String secretKey = config.get("aws.credentials.secretKey").toString();

  if (accessKey != null && accessKey.length() > 0){
    providers.add(new AWSCredentialsConfigFileProvider(accessKey, secretKey));
  }

  return new AWSCredentialsProviderChain(providers.toArray(new AWSCredentialsProvider[0]));
}
项目:cerberus-lifecycle-cli    文件:CerberusModule.java   
public static AWSCredentialsProviderChain getAWSCredentialsProviderChain() {
    String cerberusRoleToAssume = System.getenv(CERBERUS_ASSUME_ROLE_ARN) != null ?
            System.getenv(CERBERUS_ASSUME_ROLE_ARN) : "";
    String cerberusRoleToAssumeExternalId = System.getenv(CERBERUS_ASSUME_ROLE_EXTERNAL_ID) != null ?
            System.getenv(CERBERUS_ASSUME_ROLE_EXTERNAL_ID) : "";

    STSAssumeRoleSessionCredentialsProvider sTSAssumeRoleSessionCredentialsProvider =
            new STSAssumeRoleSessionCredentialsProvider
                    .Builder(cerberusRoleToAssume, UUID.randomUUID().toString())
                    .withExternalId(cerberusRoleToAssumeExternalId)
                    .build();

    AWSCredentialsProviderChain chain = new AWSCredentialsProviderChain(
            new EnvironmentVariableCredentialsProvider(),
            new SystemPropertiesCredentialsProvider(),
            new ProfileCredentialsProvider(),
            sTSAssumeRoleSessionCredentialsProvider,
            new InstanceProfileCredentialsProvider());

    return chain;
}
项目:herd    文件:S3DaoImpl.java   
/**
 * <p> Gets the {@link AWSCredentialsProvider} based on the credentials in the given parameters. </p> <p> Returns {@link DefaultAWSCredentialsProviderChain}
 * if either access or secret key is {@code null}. Otherwise returns a {@link StaticCredentialsProvider} with the credentials. </p>
 *
 * @param params - Access parameters
 *
 * @return AWS credentials provider implementation
 */
private AWSCredentialsProvider getAWSCredentialsProvider(S3FileTransferRequestParamsDto params)
{
    List<AWSCredentialsProvider> providers = new ArrayList<>();
    String accessKey = params.getAwsAccessKeyId();
    String secretKey = params.getAwsSecretKey();
    if (accessKey != null && secretKey != null)
    {
        providers.add(new StaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)));
    }
    for (HerdAWSCredentialsProvider herdAWSCredentialsProvider : params.getAdditionalAwsCredentialsProviders())
    {
        providers.add(new HerdAwsCredentialsProviderWrapper(herdAWSCredentialsProvider));
    }
    providers.add(new DefaultAWSCredentialsProviderChain());
    return new AWSCredentialsProviderChain(providers.toArray(new AWSCredentialsProvider[providers.size()]));
}
项目:elasticsearch-river-dynamodb    文件:DynamoDbRiverTests.java   
private AmazonDynamoDBClient getDynamoClient(String tableName) {
    AWSCredentialsProvider credentials = new AWSCredentialsProviderChain(new StaticCredentialsProvider(new BasicAWSCredentials("test", "test")));
    AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient(credentials);
    amazonDynamoDBClient.setEndpoint("http://localhost:8000");

    ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput()
            .withReadCapacityUnits(5L)
            .withWriteCapacityUnits(10L);
    CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName).withProvisionedThroughput(provisionedThroughput);
    ArrayList<AttributeDefinition> attributeDefinitions= new ArrayList<AttributeDefinition>();
    attributeDefinitions.add(new AttributeDefinition().withAttributeName("id").withAttributeType("S"));
    createTableRequest.setAttributeDefinitions(attributeDefinitions);

    ArrayList<KeySchemaElement> tableKeySchema = new ArrayList<KeySchemaElement>();
    tableKeySchema.add(new KeySchemaElement().withAttributeName("id").withKeyType(KeyType.HASH));
    createTableRequest.setKeySchema(tableKeySchema);
    amazonDynamoDBClient.createTable(createTableRequest);
    return amazonDynamoDBClient;

}
项目:spring-cloud-aws    文件:ContextCredentialsAutoConfigurationTest.java   
@Test
public void credentialsProvider_accessKeyAndSecretKeyConfigured_configuresStaticCredentialsProviderWithAccessAndSecretKey() {
    this.context = new AnnotationConfigApplicationContext();
    this.context.register(ContextCredentialsAutoConfiguration.class);
    TestPropertyValues.of(
            "cloud.aws.credentials.accessKey:foo",
            "cloud.aws.credentials.secretKey:bar").applyTo(this.context);
    this.context.refresh();
    AWSCredentialsProvider awsCredentialsProvider = this.context.getBean(AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME, AWSCredentialsProviderChain.class);
    assertNotNull(awsCredentialsProvider);

    @SuppressWarnings("unchecked") List<CredentialsProvider> credentialsProviders =
            (List<CredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProvider, "credentialsProviders");
    assertEquals(2, credentialsProviders.size());
    assertTrue(AWSStaticCredentialsProvider.class.isInstance(credentialsProviders.get(0)));
    assertTrue(ProfileCredentialsProvider.class.isInstance(credentialsProviders.get(1)));

    assertEquals("foo", awsCredentialsProvider.getCredentials().getAWSAccessKeyId());
    assertEquals("bar", awsCredentialsProvider.getCredentials().getAWSSecretKey());

}
项目:aml    文件:ApiImporter.java   
@SuppressWarnings("deprecation")
public ApiImporter(String profile, String accessKey, String secret) {
    if (accessKey != null && secret != null) {
        credentialsProvider=new AWSCredentialsProvider() {

            @Override
            public void refresh() {
            }

            @Override
            public AWSCredentials getCredentials() {
                return new AWSCredentials() {

                    @Override
                    public String getAWSSecretKey() {
                        return secret;
                    }

                    @Override
                    public String getAWSAccessKeyId() {
                        return accessKey;
                    }
                };
            }
        };
    } else {
        credentialsProvider = new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider(),
                new SystemPropertiesCredentialsProvider(), new ProfileCredentialsProvider(profile),
                new InstanceProfileCredentialsProvider());
    }
    amazonApiGatewayClient = new AmazonApiGatewayClient(credentialsProvider);
}
项目:gradle-beanstalk-plugin    文件:DeployTask.java   
@TaskAction
protected void deploy() {
    String versionLabel = getVersionLabel();

    AWSCredentialsProviderChain credentialsProvider = new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider(), new SystemPropertiesCredentialsProvider(), new ProfileCredentialsProvider(beanstalk.getProfile()));

    BeanstalkDeployer deployer = new BeanstalkDeployer(beanstalk.getS3Endpoint(), beanstalk.getBeanstalkEndpoint(), credentialsProvider);

    File warFile = getProject().files(war).getSingleFile();
    deployer.deploy(warFile, deployment.getApplication(), deployment.getEnvironment(), deployment.getTemplate(), versionLabel);
}
项目:samza    文件:KinesisConfig.java   
/**
 * Get the appropriate CredentialProvider for a given system stream.
 * @param system name of the system
 * @param stream name of the stream
 * @return AWSCredentialsProvider
 */
AWSCredentialsProvider credentialsProviderForStream(String system, String stream) {
  // Try to load credentials in the following order:
  // 1. Access key from the config and passed in secretKey
  // 2. From the default credential provider chain (environment variables, system properties, AWS profile file, etc)
  return new AWSCredentialsProviderChain(
      new KinesisAWSCredentialsProvider(getStreamAccessKey(system, stream), getStreamSecretKey(system, stream)),
      new DefaultAWSCredentialsProviderChain());
}
项目:logback-sqs    文件:SqsAppender.java   
/**
 * 
 * @return
 */
private AWSCredentialsProvider getCredentials() {
  return new AWSCredentialsProviderChain(new StaticCredentialsProvider(
      new AppenderCredentials()), new SystemPropertiesCredentialsProvider(),
      new EnvironmentVariableCredentialsProvider(),
      new ProfileCredentialsProvider(),
      new InstanceProfileCredentialsProvider());
}
项目:fullstop    文件:ExtPropertiesFileConfiguration.java   
/**
 * Creates a {@link PropertiesFileConfiguration} from values provided in a classpath properties file.
 *
 * @param prop               the classpath properties file to load.
 * @param credentialProvider credential provider.
 */
public ExtPropertiesFileConfiguration(final Properties prop, final AWSCredentialsProviderChain credentialProvider) {

    this.sqsUrl = prop.getProperty(SQS_URL);
    LibraryUtils.checkArgumentNotNull(this.sqsUrl, "Cannot find SQS URL in properties file.");

    final String accessKey = prop.getProperty(ACCESS_KEY);
    final String secretKey = prop.getProperty(SECRET_KEY);

    if (accessKey != null && secretKey != null) {
        this.awsCredentialsProvider = new SimplePropertiesCredentials(prop);
    }
    else {
        this.awsCredentialsProvider = credentialProvider;
    }

    this.s3Region = prop.getProperty(S3_REGION);
    this.visibilityTimeout = this.getIntProperty(prop, VISIBILITY_TIMEOUT);

    this.sqsRegion = prop.getProperty(SQS_REGION);

    this.threadCount = this.getIntProperty(prop, THREAD_COUNT);
    this.threadTerminationDelaySeconds = this.getIntProperty(prop, THREAD_TERMINATION_DELAY_SECONDS);

    this.maxEventsPerEmit = this.getIntProperty(prop, MAX_EVENTS_PER_EMIT);
    this.enableRawEventInfo = this.getBooleanProperty(prop, ENABLE_RAW_EVENT_INFO);
}
项目:aws-request-signer    文件:V4RequestSignerTest.java   
@Before
public final void before() throws URISyntaxException {
   Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
   calendar.set(2011, 8, 9, 23, 36, 00);
   currentDate = calendar.getTime();
   uri = new URI(TEST_ENDPOINT);
   AWSCredentialsProviderChain awsCredentialsProvider = new AWSCredentialsProviderChain(
         new StaticCredentialsProvider(new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_KEY)));
   testObject = new V4RequestSigner(awsCredentialsProvider, REGION_NAME, SERVICE_NAME, currentDate);
}
项目:simplemetrics    文件:CloudWatchMetricsPersisterTest.java   
@Test
public void testCoverage() {
    AWSCredentials creds = new BasicAWSCredentials("key", "secret");
    CloudWatchMetricsPersister persister = new CloudWatchMetricsPersister(creds, "app", true);
    StaticCredentialsProvider credProv = new StaticCredentialsProvider(creds);
    persister = new CloudWatchMetricsPersister(new AWSCredentialsProviderChain(credProv), "app", true);
    persister = new CloudWatchMetricsPersister();
    persister.setAwsCredentials(creds);
    persister.setAwsCredentialsProvider(credProv);
}
项目:amediamanager    文件:ServerConfig.java   
@Bean
@Scope(WebApplicationContext.SCOPE_APPLICATION)
public AWSCredentialsProvider credentials() {
    return new AWSCredentialsProviderChain(
          new InstanceProfileCredentialsProvider(),
          new EnvironmentVariableCredentialsProvider(),
          new SystemPropertiesCredentialsProvider()
            );
}
项目:detective    文件:AwsServiceImpl.java   
private AWSCredentialsProvider createCredentialsProvider(){
  return new AWSCredentialsProviderChain(
      new InstanceProfileCredentialsProvider(),
      new EnvironmentVariableCredentialsProvider(),
      new SystemPropertiesCredentialsProvider(),
      new AWSCredentialsConfigFileProvider()
      );
}
项目:logback-ext    文件:AwsSupport.java   
public AWSCredentialsProvider getCredentials(AWSCredentials credentials) {
    return new AWSCredentialsProviderChain(
            new EnvironmentVariableCredentialsProvider(),
            new SystemPropertiesCredentialsProvider(),
            new StaticCredentialsProvider(credentials == null ? new NullCredentials() : credentials),
            new ProfileCredentialsProvider(),
            new InstanceProfileCredentialsProvider()
    );
}
项目:emr-sample-apps    文件:RSAEncryptionMaterialsProvider.java   
private void initializeAmazonS3() {
  if (s3 == null) {
    final String accessKey = conf.get(ACCESS_KEY_CONF);
    final String secretKey = conf.get(SECRET_KEY_CONF);
    s3 = new AmazonS3Client(new AWSCredentialsProviderChain(
        new AWSCredentialsProvider() {
          @Override
          public AWSCredentials getCredentials() {
            if (!Strings.isNullOrEmpty(accessKey) && !Strings.isNullOrEmpty(secretKey)) {
              return new BasicAWSCredentials(accessKey, secretKey);
            } else {
              return null;
            }
          }

          @Override
          public void refresh() {

          }
        },
        new InstanceProfileCredentialsProvider()));

    if (!Strings.isNullOrEmpty(conf.get(ENDPOINT_CONF))) {
      s3.setEndpoint(conf.get(ENDPOINT_CONF));
    } else if (Regions.getCurrentRegion() != null) {
      s3.setRegion(Regions.getCurrentRegion());
    } else {
      s3.setEndpoint(ENDPOINT_DEFAULT);
    }
  }
}
项目:circus-train    文件:SnsConfiguration.java   
@Bean
AWSCredentialsProvider awsCredentialsProvider(
    @Qualifier("replicaHiveConf") org.apache.hadoop.conf.Configuration conf) {
  return new AWSCredentialsProviderChain(new BasicAuth(conf), InstanceProfileCredentialsProvider.getInstance());
}
项目:emr-dynamodb-connector    文件:DynamoDBClient.java   
protected AWSCredentialsProvider getAWSCredentialsProvider(Configuration conf) {
  List<AWSCredentialsProvider> providersList = new ArrayList<>();

  // try to load custom credential provider, fail if a provider is specified but cannot be
  // initialized
  String providerClass = conf.get(DynamoDBConstants.CUSTOM_CREDENTIALS_PROVIDER_CONF);
  if (!Strings.isNullOrEmpty(providerClass)) {
    try {
      providersList.add(
          (AWSCredentialsProvider) ReflectionUtils.newInstance(Class.forName(providerClass), conf)
      );
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Custom AWSCredentialsProvider not found: " + providerClass, e);
    }
  }

  // try to fetch credentials from core-site
  String accessKey = conf.get(DYNAMODB_CREDENTIAL_PAIR_NAME.getAccessKeyName());
  String secretKey;
  if (Strings.isNullOrEmpty(accessKey)) {
    accessKey = conf.get(DEFAULT_CREDENTIAL_PAIR_NAME.getAccessKeyName());
    secretKey = conf.get(DEFAULT_CREDENTIAL_PAIR_NAME.getSecretKeyName());
  } else {
    secretKey = conf.get(DYNAMODB_CREDENTIAL_PAIR_NAME.getSecretKeyName());
  }

  if (Strings.isNullOrEmpty(accessKey) || Strings.isNullOrEmpty(secretKey)) {
    providersList.add(new InstanceProfileCredentialsProvider());
  } else {
    final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    providersList.add(new AWSCredentialsProvider() {
      @Override
      public AWSCredentials getCredentials() {
        return credentials;
      }

      @Override
      public void refresh() {
      }
    });
  }

  AWSCredentialsProvider[] providerArray = providersList.toArray(
      new AWSCredentialsProvider[providersList.size()]
  );

  AWSCredentialsProviderChain providerChain = new AWSCredentialsProviderChain(providerArray);
  providerChain.setReuseLastProvider(true);
  return providerChain;
}
项目:lambadaframework    文件:AWSTools.java   
protected static AWSCredentialsProviderChain getAWSCredentialsProvideChain() {
    return new DefaultAWSCredentialsProviderChain();
}
项目:herd    文件:S3DaoTest.java   
/**
 * A case where additional credentials provider is given in the request params. The credentials returned should be an AWS session credential where the
 * values are from the provided custom credentials provider.
 */
@Test
public void testGetAWSCredentialsProviderAssertAdditionalProviderIsSet() throws Exception
{
    S3Operations originalS3Operations = (S3Operations) ReflectionTestUtils.getField(s3Dao, "s3Operations");
    S3Operations mockS3Operations = mock(S3Operations.class);
    ReflectionTestUtils.setField(s3Dao, "s3Operations", mockS3Operations);

    try
    {
        String s3BucketName = "s3BucketName";
        String s3KeyPrefix = "s3KeyPrefix";
        String awsAccessKey = "awsAccessKey";
        String awsSecretKey = "awsSecretKey";
        String awsSessionToken = "awsSessionToken";

        S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
        s3FileTransferRequestParamsDto.setS3BucketName(s3BucketName);
        s3FileTransferRequestParamsDto.setS3KeyPrefix(s3KeyPrefix);
        s3FileTransferRequestParamsDto.setAdditionalAwsCredentialsProviders(Arrays.asList(new HerdAWSCredentialsProvider()
        {
            @Override
            public AwsCredential getAwsCredential()
            {
                return new AwsCredential(awsAccessKey, awsSecretKey, awsSessionToken, null);
            }
        }));

        when(mockS3Operations.putObject(any(), any())).then(new Answer<PutObjectResult>()
        {
            @SuppressWarnings("unchecked")
            @Override
            public PutObjectResult answer(InvocationOnMock invocation) throws Throwable
            {
                AmazonS3Client amazonS3Client = invocation.getArgument(1);
                AWSCredentialsProviderChain awsCredentialsProviderChain =
                    (AWSCredentialsProviderChain) ReflectionTestUtils.getField(amazonS3Client, "awsCredentialsProvider");
                List<AWSCredentialsProvider> credentialsProviders =
                    (List<AWSCredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProviderChain, "credentialsProviders");
                assertEquals(2, credentialsProviders.size());

                // refresh() does nothing, but gives code coverage
                credentialsProviders.get(0).refresh();

                /*
                 * We can't inspect the field directly since the class definition is private.
                 * Instead we call the getCredentials() and verify that it returns the credentials staged as part of this test.
                 */
                AWSCredentials credentials = awsCredentialsProviderChain.getCredentials();
                assertEquals(BasicSessionCredentials.class, credentials.getClass());

                BasicSessionCredentials basicSessionCredentials = (BasicSessionCredentials) credentials;

                assertEquals(awsAccessKey, basicSessionCredentials.getAWSAccessKeyId());
                assertEquals(awsSecretKey, basicSessionCredentials.getAWSSecretKey());
                assertEquals(awsSessionToken, basicSessionCredentials.getSessionToken());

                return new PutObjectResult();
            }
        });

        s3Dao.createDirectory(s3FileTransferRequestParamsDto);
    }
    finally
    {
        ReflectionTestUtils.setField(s3Dao, "s3Operations", originalS3Operations);
    }
}
项目:herd    文件:S3DaoTest.java   
@Test
public void testGetAWSCredentialsProviderAssertStaticCredentialsIsNotSetWhenAccessKeyIsNull()
{
    S3Operations originalS3Operations = (S3Operations) ReflectionTestUtils.getField(s3Dao, "s3Operations");
    S3Operations mockS3Operations = mock(S3Operations.class);
    ReflectionTestUtils.setField(s3Dao, "s3Operations", mockS3Operations);

    try
    {
        String s3BucketName = "s3BucketName";
        String s3KeyPrefix = "s3KeyPrefix";
        String s3AccessKey = null;
        String s3SecretKey = "s3SecretKey";

        S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
        s3FileTransferRequestParamsDto.setS3BucketName(s3BucketName);
        s3FileTransferRequestParamsDto.setS3KeyPrefix(s3KeyPrefix);
        s3FileTransferRequestParamsDto.setAwsAccessKeyId(s3AccessKey);
        s3FileTransferRequestParamsDto.setAwsSecretKey(s3SecretKey);

        when(mockS3Operations.putObject(any(), any())).then(new Answer<PutObjectResult>()
        {
            @SuppressWarnings("unchecked")
            @Override
            public PutObjectResult answer(InvocationOnMock invocation) throws Throwable
            {
                AmazonS3Client amazonS3Client = invocation.getArgument(1);
                AWSCredentialsProviderChain awsCredentialsProviderChain =
                    (AWSCredentialsProviderChain) ReflectionTestUtils.getField(amazonS3Client, "awsCredentialsProvider");
                List<AWSCredentialsProvider> credentialsProviders =
                    (List<AWSCredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProviderChain, "credentialsProviders");
                assertEquals(1, credentialsProviders.size());
                assertEquals(DefaultAWSCredentialsProviderChain.class, credentialsProviders.get(0).getClass());
                return new PutObjectResult();
            }
        });

        s3Dao.createDirectory(s3FileTransferRequestParamsDto);
    }
    finally
    {
        ReflectionTestUtils.setField(s3Dao, "s3Operations", originalS3Operations);
    }
}
项目:herd    文件:S3DaoTest.java   
@Test
public void testGetAWSCredentialsProviderAssertStaticCredentialsIsNotSetWhenSecretKeyIsNull()
{
    S3Operations originalS3Operations = (S3Operations) ReflectionTestUtils.getField(s3Dao, "s3Operations");
    S3Operations mockS3Operations = mock(S3Operations.class);
    ReflectionTestUtils.setField(s3Dao, "s3Operations", mockS3Operations);

    try
    {
        String s3BucketName = "s3BucketName";
        String s3KeyPrefix = "s3KeyPrefix";
        String s3AccessKey = "s3AccessKey";
        String s3SecretKey = null;

        S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
        s3FileTransferRequestParamsDto.setS3BucketName(s3BucketName);
        s3FileTransferRequestParamsDto.setS3KeyPrefix(s3KeyPrefix);
        s3FileTransferRequestParamsDto.setAwsAccessKeyId(s3AccessKey);
        s3FileTransferRequestParamsDto.setAwsSecretKey(s3SecretKey);

        when(mockS3Operations.putObject(any(), any())).then(new Answer<PutObjectResult>()
        {
            @SuppressWarnings("unchecked")
            @Override
            public PutObjectResult answer(InvocationOnMock invocation) throws Throwable
            {
                AmazonS3Client amazonS3Client = invocation.getArgument(1);
                AWSCredentialsProviderChain awsCredentialsProviderChain =
                    (AWSCredentialsProviderChain) ReflectionTestUtils.getField(amazonS3Client, "awsCredentialsProvider");
                List<AWSCredentialsProvider> credentialsProviders =
                    (List<AWSCredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProviderChain, "credentialsProviders");
                assertEquals(1, credentialsProviders.size());
                assertEquals(DefaultAWSCredentialsProviderChain.class, credentialsProviders.get(0).getClass());
                return new PutObjectResult();
            }
        });

        s3Dao.createDirectory(s3FileTransferRequestParamsDto);
    }
    finally
    {
        ReflectionTestUtils.setField(s3Dao, "s3Operations", originalS3Operations);
    }
}
项目:herd    文件:S3DaoTest.java   
@Test
public void testGetAWSCredentialsProviderAssertStaticCredentialsSet()
{
    S3Operations originalS3Operations = (S3Operations) ReflectionTestUtils.getField(s3Dao, "s3Operations");
    S3Operations mockS3Operations = mock(S3Operations.class);
    ReflectionTestUtils.setField(s3Dao, "s3Operations", mockS3Operations);

    try
    {
        String s3BucketName = "s3BucketName";
        String s3KeyPrefix = "s3KeyPrefix";
        String s3AccessKey = "s3AccessKey";
        String s3SecretKey = "s3SecretKey";

        S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
        s3FileTransferRequestParamsDto.setS3BucketName(s3BucketName);
        s3FileTransferRequestParamsDto.setS3KeyPrefix(s3KeyPrefix);
        s3FileTransferRequestParamsDto.setAwsAccessKeyId(s3AccessKey);
        s3FileTransferRequestParamsDto.setAwsSecretKey(s3SecretKey);

        when(mockS3Operations.putObject(any(), any())).then(new Answer<PutObjectResult>()
        {
            @SuppressWarnings("unchecked")
            @Override
            public PutObjectResult answer(InvocationOnMock invocation) throws Throwable
            {
                AmazonS3Client amazonS3Client = invocation.getArgument(1);
                AWSCredentialsProviderChain awsCredentialsProviderChain =
                    (AWSCredentialsProviderChain) ReflectionTestUtils.getField(amazonS3Client, "awsCredentialsProvider");
                List<AWSCredentialsProvider> credentialsProviders =
                    (List<AWSCredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProviderChain, "credentialsProviders");
                // Expect 2 providers: the static provider, and the default provider
                assertEquals(2, credentialsProviders.size());

                // Only verify the static value
                assertEquals(StaticCredentialsProvider.class, credentialsProviders.get(0).getClass());
                StaticCredentialsProvider staticCredentialsProvider = (StaticCredentialsProvider) credentialsProviders.get(0);
                assertEquals(s3AccessKey, staticCredentialsProvider.getCredentials().getAWSAccessKeyId());
                assertEquals(s3SecretKey, staticCredentialsProvider.getCredentials().getAWSSecretKey());
                return new PutObjectResult();
            }
        });

        s3Dao.createDirectory(s3FileTransferRequestParamsDto);
    }
    finally
    {
        ReflectionTestUtils.setField(s3Dao, "s3Operations", originalS3Operations);
    }
}
项目:elasticsearch-river-dynamodb    文件:DynamoDbRiver.java   
@Inject
public DynamoDbRiver(RiverName riverName, RiverSettings settings, Client client, @RiverIndexName String riverIndexName) {
    super(riverName, settings);
    this.client = client;
    this.riverIndexName = riverIndexName;

    if (settings.settings().containsKey("dynamodb")) {
        Map<String, Object> dynamoDbSetting = (Map<String, Object>) settings.settings().get("dynamodb");

        String accessKey = XContentMapValues.nodeStringValue(dynamoDbSetting.get("access_key"), null);
        String secretKey = XContentMapValues.nodeStringValue(dynamoDbSetting.get("secret_key"), null);
        AWSCredentialsProvider credentials = new AWSCredentialsProviderChain(new StaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)));

        dynamoDBClient = new AmazonDynamoDBClient(credentials);

        String regionStr = XContentMapValues.nodeStringValue(dynamoDbSetting.get("region"), Regions.DEFAULT_REGION.getName());
        Regions region = null;
        for (Regions regions : Regions.values()) {
            if (regions.getName().equals(regionStr)) {
                region = regions;
                break;
            }
        }
        if (region == null) {
            logger.warn("Unable to find DynamoDB region");
            dynamoDBClient.setEndpoint(regionStr);  // use regionStr as endpoint directly, this should only happen in test or user has their own DynamoDB endpoint
        } else {
            dynamoDBClient.setRegion(Region.getRegion(region));
        }

        tableName = XContentMapValues.nodeStringValue(dynamoDbSetting.get("table_name"), null);
        idField = XContentMapValues.nodeStringValue(dynamoDbSetting.get("id_field"), "id");
        updatedTimestampField = XContentMapValues.nodeStringValue(dynamoDbSetting.get("updated_timestamp_field"), null);
        deletedTimestampField = XContentMapValues.nodeStringValue(dynamoDbSetting.get("deleted_timestamp_field"), null);
        indexName = XContentMapValues.nodeStringValue(dynamoDbSetting.get("index"), tableName);
        typeName = XContentMapValues.nodeStringValue(dynamoDbSetting.get("type"), tableName);
        bulkSize = XContentMapValues.nodeIntegerValue(dynamoDbSetting.get("bulk_size"), 100);
        bulkFlushInterval = TimeValue.parseTimeValue(XContentMapValues.nodeStringValue(
                dynamoDbSetting.get("flush_interval"), "5s"), TimeValue.timeValueSeconds(5));
        maxConcurrentBulk = XContentMapValues.nodeIntegerValue(dynamoDbSetting.get("max_concurrent_bulk"), 1);
        interval = TimeValue.parseTimeValue(XContentMapValues.nodeStringValue(
                dynamoDbSetting.get("interval"), "0s"), TimeValue.timeValueSeconds(0));


    } else {
        throw new ElasticsearchException("Unable to find DynamoDB river setting");
    }
}
项目:aws-beanstalk-publisher    文件:AWSEBCredentials.java   
public AWSCredentialsProvider getAwsCredentials() {
    AWSCredentialsProvider credentials = new AWSCredentialsProviderChain(new StaticCredentialsProvider(new BasicAWSCredentials(getAwsAccessKeyId(), getAwsSecretSharedKey())));
    return credentials;
}
项目:spring-cloud-aws    文件:ContextCredentialsBeanDefinitionParserTest.java   
@Test
public void testCreateBeanDefinition() throws Exception {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());

    //Check that the result of the factory bean is available
    AWSCredentialsProvider awsCredentialsProvider = applicationContext.getBean(AWSCredentialsProvider.class);

    assertTrue(AWSCredentialsProviderChain.class.isInstance(awsCredentialsProvider));

    // Using reflection to really test if the chain is stable
    AWSCredentialsProviderChain awsCredentialsProviderChain = (AWSCredentialsProviderChain) awsCredentialsProvider;

    @SuppressWarnings("unchecked") List<AWSCredentialsProvider> providerChain = (List<AWSCredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProviderChain, "credentialsProviders");

    assertNotNull(providerChain);
    assertEquals(2, providerChain.size());

    assertTrue(InstanceProfileCredentialsProvider.class.isInstance(providerChain.get(0)));
    assertTrue(AWSStaticCredentialsProvider.class.isInstance(providerChain.get(1)));

    AWSStaticCredentialsProvider staticCredentialsProvider = (AWSStaticCredentialsProvider) providerChain.get(1);
    assertEquals("staticAccessKey", staticCredentialsProvider.getCredentials().getAWSAccessKeyId());
    assertEquals("staticSecretKey", staticCredentialsProvider.getCredentials().getAWSSecretKey());

}
项目:mybus    文件:CoreAppConfig.java   
/**
 * Returns an {@link com.amazonaws.auth.AWSCredentialsProvider} with the permissions necessary to accomplish all
 * specified tasks. At the minimum it will require read permissions for Amazon Kinesis. Additional read permissions
 * and write permissions may be required based on the Pipeline used.
 *
 * @return
 */
@Bean
public AWSCredentialsProvider getAWSCredentialsProvider() {
    return new AWSCredentialsProviderChain(new MyBusAWSCredentialsProvider());
}