private AmazonIdentityManagement client() { return AmazonIdentityManagementClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(new AWSCredentials() { @Override public String getAWSAccessKeyId() { return bookmark.getCredentials().getUsername(); } @Override public String getAWSSecretKey() { return bookmark.getCredentials().getPassword(); } })) .withClientConfiguration(configuration) .withRegion(Regions.DEFAULT_REGION).build(); }
/** * Do any initialization required by this client. In this case, * initialization consists of getting the value of the AWS region * and credentials parameters. * * @param context * the context to run with. This provides access to * initialization parameters. */ @Override public void setupTest(JavaSamplerContext context) { apigatewayBaseUrl = context.getParameter("APIGATEWAY_BASE_URL"); accessKeyId = context.getParameter("ACCESS_KEY_ID"); secretKey = context.getParameter("SECRET_KEY"); sessionToken = context.getParameter("SESSION_TOKEN"); AWSCredentials awsCredentials = new BasicSessionCredentials(accessKeyId, secretKey, sessionToken); AWSStaticCredentialsProvider awsStaticCredentialsProvider = new AWSStaticCredentialsProvider( awsCredentials); String region = context.getParameter("REGION"); client = Squash.builder().iamRegion(region) .iamCredentials((AWSCredentialsProvider) awsStaticCredentialsProvider).build(); samplerName = context.getParameter(TestElement.NAME); bookingName = context.getParameter("BOOKING_NAME"); court = context.getParameter("COURT"); courtSpan = context.getParameter("COURTSPAN"); slot = context.getParameter("SLOT"); slotSpan = context.getParameter("SLOTSPAN"); date = context.getParameter("DATE"); putOrDelete = context.getParameter("PUT_OR_DELETE"); }
public void deploy(AwsKeyPair keyPair, String region, final String restApiName, final String stage, Proxy proxy) { final AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( new BasicAWSCredentials(keyPair.key, keyPair.secret)); ClientConfiguration cc = Util.createConfiguration(proxy); AmazonApiGateway ag = AmazonApiGatewayClientBuilder.standard().withCredentials(credentials) // .withClientConfiguration(cc) // .withRegion(region) // .build(); GetRestApisResult apis = ag.getRestApis(new GetRestApisRequest().withLimit(10000)); Optional<RestApi> api = apis.getItems().stream().filter(item -> item.getName().equals(restApiName)).findFirst(); RestApi a = api.orElseThrow(() -> new RuntimeException("no rest api found with name='" + restApiName + "'")); String restApiId = a.getId(); log.info("creating deployment of " + restApiId + " to stage " + stage); CreateDeploymentResult r = ag .createDeployment(new CreateDeploymentRequest().withRestApiId(restApiId).withStageName(stage)); Map<String, Map<String, MethodSnapshot>> summary = r.getApiSummary(); log.info("created deployment"); log.info("summary=" + summary); }
@Override protected void obtainResource() throws Exception { // See https://github.com/mhart/kinesalite#cbor-protocol-issues-with-the-java-sdk System.setProperty(SDKGlobalConfiguration.AWS_CBOR_DISABLE_SYSTEM_PROPERTY, "true"); this.resource = AmazonKinesisAsyncClientBuilder.standard() .withClientConfiguration( new ClientConfiguration() .withMaxErrorRetry(0) .withConnectionTimeout(1000)) .withEndpointConfiguration( new AwsClientBuilder.EndpointConfiguration("http://localhost:" + this.port, Regions.DEFAULT_REGION.getName())) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("", ""))) .build(); // Check connection this.resource.listStreams(); }
@Override public AmazonEC2Async amazonEC2Async() { User user = authenticationService.getCurrentUser(); String accessKey = user.getAwsKey(); String secretKey = user.getAwsSecret(); String region = user.getAwsRegion(); if (secretKey.equals("") || accessKey.equals("") || region.equals("")) { return null; } BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials( accessKey, secretKey); return AmazonEC2AsyncClientBuilder.standard().withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials)) .build(); }
@Override public AmazonEC2Async amazonEC2Async(User user) { String accessKey = user.getAwsKey(); String secretKey = user.getAwsSecret(); String region = user.getAwsRegion(); if (secretKey.equals("") || accessKey.equals("") || region.equals("")) { return null; } BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials( accessKey, secretKey); return AmazonEC2AsyncClientBuilder.standard().withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials)) .build(); }
@Before public void setUp() throws Exception { context = mock(Context.class); when(context.getLogger()).thenReturn(System.out::println); handler = new AuthLambdaHandler(TEST_AWS_REGION, TEST_JWT_KEY_ARN, TEST_VIDEO_STORAGE_BUCKET, TEST_USER_ACCESS_KEY_ID, TEST_USER_SECRET_ACCESS_KEY); AWSKMS kmsClient = AWSKMSClientBuilder.standard() .withRegion(TEST_AWS_REGION) .withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(TEST_USER_ACCESS_KEY_ID, TEST_USER_SECRET_ACCESS_KEY)) ) .build(); kmsEncrypt = new KMSEncrypt(kmsClient, TEST_JWT_KEY_ARN); }
/** * S3 储存客户端 * * @return 客户端 */ @Bean @ConditionalOnProperty(value = "bigbug.storage.s3.enable", havingValue = "true") AmazonS3Client amazonS3Client() { ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setProtocol(Protocol.HTTP); BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials( storageProperties.getStorage().getS3().getAccessKey(), storageProperties.getStorage().getS3().getSecretKey()); return (AmazonS3Client) AmazonS3ClientBuilder.standard() .withClientConfiguration(clientConfig) .withEndpointConfiguration( new AwsClientBuilder.EndpointConfiguration( storageProperties.getStorage().getS3().getEndpoint(), Regions.DEFAULT_REGION.getName())) .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials)) .build(); }
/** * Creates a new S3 configuration cache. * @param bucket The S3 bucket. * @param prefix The S3 object prefix. * @param pathPattern The path pattern. * @param accessKey The (optional) S3 access key. * @param secretKey The (optional) S3 secret key. * @param region The AWS region (e.g. us-east-1). * @throws IOException Thrown if the configuration cannot be read. */ public S3ConfigurationCache(String bucket, String prefix, String pathPattern, String accessKey, String secretKey, String region) throws IOException { this.bucket = bucket; this.prefix = prefix; this.pathPattern = pathPattern; if (!StringUtils.isEmpty(accessKey)) { s3 = AmazonS3Client.builder() .withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(accessKey, secretKey))) .withRegion(Regions.fromName(region)) .build(); } else { s3 = AmazonS3Client.builder() .withRegion(Regions.fromName(region)) .build(); } }
public static AmazonS3 getS3Client(final String region, final String roleArn) { final Regions awsRegion = StringUtils.isNullOrEmpty(region) ? Regions.US_EAST_1 : Regions.fromName(region); if (StringUtils.isNullOrEmpty(roleArn)) { return AmazonS3ClientBuilder.standard().withRegion(awsRegion).build(); } else { final AssumeRoleRequest assumeRole = new AssumeRoleRequest().withRoleArn(roleArn).withRoleSessionName("io-klerch-mp3-converter"); final AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder.standard().withRegion(awsRegion).build(); final Credentials credentials = sts.assumeRole(assumeRole).getCredentials(); final BasicSessionCredentials sessionCredentials = new BasicSessionCredentials( credentials.getAccessKeyId(), credentials.getSecretAccessKey(), credentials.getSessionToken()); return AmazonS3ClientBuilder.standard().withRegion(awsRegion).withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build(); } }
public static AmazonS3Client getS3Client(AuthCredentialsServiceState credentials, String regionId) { ClientConfiguration configuration = new ClientConfiguration(); configuration.withRetryPolicy(new RetryPolicy(new CustomRetryCondition(), DEFAULT_BACKOFF_STRATEGY, DEFAULT_MAX_ERROR_RETRY, false)); AWSStaticCredentialsProvider awsStaticCredentialsProvider = new AWSStaticCredentialsProvider( new BasicAWSCredentials(credentials.privateKeyId, EncryptionUtils.decrypt(credentials.privateKey))); AmazonS3ClientBuilder amazonS3ClientBuilder = AmazonS3ClientBuilder .standard() .withClientConfiguration(configuration) .withCredentials(awsStaticCredentialsProvider) .withRegion(regionId); if (isAwsClientMock()) { throw new IllegalArgumentException("AWS Mock does not support S3 client"); } return (AmazonS3Client) amazonS3ClientBuilder.build(); }
public static AmazonEC2 getEC2SynchronousClient(AuthCredentialsServiceState credentials, String region) { ClientConfiguration configuration = new ClientConfiguration(); configuration.withRetryPolicy(new RetryPolicy(new CustomRetryCondition(), DEFAULT_BACKOFF_STRATEGY, DEFAULT_MAX_ERROR_RETRY, true)); AWSStaticCredentialsProvider awsStaticCredentialsProvider = new AWSStaticCredentialsProvider( new BasicAWSCredentials(credentials.privateKeyId, EncryptionUtils.decrypt(credentials.privateKey))); AmazonEC2ClientBuilder ec2ClientBuilder = AmazonEC2ClientBuilder.standard() .withCredentials(awsStaticCredentialsProvider) .withRegion(region) .withClientConfiguration(configuration); return ec2ClientBuilder.build(); }
@Before public void setup() { store = new InMemoryStorage(); metrics = new InMemoryCollectorMetrics(); collector = new SQSCollector.Builder() .queueUrl(sqsRule.queueUrl()) .parallelism(2) .waitTimeSeconds(1) // using short wait time to make test teardown faster .endpointConfiguration(new EndpointConfiguration(sqsRule.queueUrl(), "us-east-1")) .credentialsProvider(new AWSStaticCredentialsProvider(new BasicAWSCredentials("x", "x"))) .metrics(metrics) .sampler(CollectorSampler.ALWAYS_SAMPLE) .storage(store) .build() .start(); }
/** * Creates an {@link S3Connector} instance with embedded {@link AmazonS3 Amazon Web Services S3 SDK Client} from * {@link S3ServiceInfo}. * @param serviceInfo S3ServiceInfo provided by {@link org.springframework.cloud.cloudfoundry.CloudFoundryServiceInfoCreator} * implementation included within the application. * @param serviceConnectorConfig * @return */ @Override public S3Connector create(S3ServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig) { AWSCredentials credentials = new BasicAWSCredentials(serviceInfo.getAccessKey(), serviceInfo.getSecretKey()); AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration( serviceInfo.getEndpoint(), Region.getRegion(Regions.DEFAULT_REGION).getName()); AmazonS3 amazonS3 = AmazonS3ClientBuilder .standard() .withEndpointConfiguration(endpointConfig) .withCredentials(credentialsProvider) .enablePathStyleAccess() .build(); if (serviceInfo.getBucket() != null) { log.debug("Creating connector addressing ECS bucket: " + serviceInfo.getBucket()); return new S3Connector(amazonS3, serviceInfo.getEndpoint(), serviceInfo.getBucket()); } else { log.debug("Creating connector addressing ECS namespace."); return new S3Connector(amazonS3, serviceInfo.getEndpoint()); } }
void deploy(AwsKeyPair keyPair, String region, String zipFilename, String functionName, Proxy proxy) { long t = System.currentTimeMillis(); final AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( new BasicAWSCredentials(keyPair.key, keyPair.secret)); AWSLambda lambda = AWSLambdaClientBuilder.standard().withCredentials(credentials) .withClientConfiguration(Util.createConfiguration(proxy)).withRegion(region).build(); byte[] bytes; try { bytes = IOUtils.toByteArray(new FileInputStream(zipFilename)); } catch (IOException e) { throw new RuntimeException(e); } DecimalFormat df = new DecimalFormat("0.000"); log.info("deploying " + zipFilename + ", length=" + df.format(bytes.length / 1024.0 / 1024.0) + "MB, to functionName=" + functionName); lambda.updateFunctionCode( // new UpdateFunctionCodeRequest() // .withFunctionName(functionName) // .withPublish(true) // .withZipFile(ByteBuffer.wrap(bytes))); log.info("deployed in " + (System.currentTimeMillis() - t) + "ms"); }
@Override public void execute() throws MojoExecutionException, MojoFailureException { Proxy proxy = new Proxy(httpsProxyHost, httpsProxyPort, httpsProxyUsername, httpsProxyPassword); AwsKeyPair keyPair = Util.getAwsKeyPair(serverId, awsAccessKey, awsSecretAccessKey, settings, decrypter); final AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( new BasicAWSCredentials(keyPair.key, keyPair.secret)); ClientConfiguration cc = Util.createConfiguration(proxy); AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder // .standard() // .withRegion(region) // .withCredentials(credentials) // .withClientConfiguration(cc) // .build(); String accountId = iam.getUser().getUser().getUserId(); project.getProperties().setProperty("aws.account.id", accountId); getLog().info("The following properties have been set for the project"); getLog().info("aws.account.id=" + accountId); }
private AWSCredentialsProvider buildCredentialsProvider(final AWSCredentials credentials, final String region, final String assumeRole) { AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); if (isNullOrEmpty(assumeRole)) { return credentialsProvider; } else { // STS requires a region; fall back on the SDK default if not set String stsRegion; if (isNullOrEmpty(region)) { stsRegion = defaultRegion(); } else { stsRegion = region; } AWSSecurityTokenService securityTokenService = AWSSecurityTokenServiceClientBuilder.standard() .withRegion(stsRegion) .withCredentials(credentialsProvider).build(); return new STSAssumeRoleSessionCredentialsProvider.Builder(assumeRole, "nexus-s3-session") .withStsClient(securityTokenService) .build(); } }
@Override public void execute(PostDownloadExecution execution) { AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretAccessKey); AmazonSNS sns = snsClientBuilder.withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(credentials)).build(); LOGGER.debug("SNS: Topic Arn : {}", arn); LOGGER.debug("SNS: Topic Region : {}", region); LOGGER.debug("SNS: Topic Access Key : {}", accessKey); LOGGER.debug("SNS: Topic Secret Access Key : {}", secretAccessKey); PublishRequest request = new PublishRequest(); request.setTopicArn(arn); request.setMessageStructure("json"); request.setMessage(formatJsonMessage(execution.fileName)); request.setSubject("A new file has been downloaded"); LOGGER.info("Publishing message to SNS"); PublishResult result = sns.publish(request); LOGGER.info("Publish successful!"); LOGGER.debug("{}", result.getMessageId()); }
@BeforeClass public static void setUpClass() throws IOException, InterruptedException { File dir = new File(new File("target", UUID.randomUUID().toString()), "fakes3_root").getAbsoluteFile(); Assert.assertTrue(dir.mkdirs()); fakeS3Root = dir.getAbsolutePath(); port = TestUtil.getFreePort(); fakeS3 = new FakeS3(fakeS3Root, port); Assume.assumeTrue("Please install fakes3 in your system", fakeS3.fakes3Installed()); //Start the fakes3 server executorService = Executors.newSingleThreadExecutor(); executorService.submit(fakeS3); BasicAWSCredentials credentials = new BasicAWSCredentials("foo", "bar"); s3client = AmazonS3ClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:" + port, null)) .withPathStyleAccessEnabled(true) .withChunkedEncodingDisabled(true) // FakeS3 does not correctly calculate checksums with chunked encoding enabled. .build(); TestUtil.createBucket(s3client, BUCKET_NAME); TestUtil.createBucket(s3client, SECOND_BUCKET_NAME); }
public S3Uploader(String accessKeyId, String secretKeyId, String bucketName, String region) { System.out.println("Initializing S3 Uploader..."); Preconditions.checkNotNull(accessKeyId, "S3 access key id can not be null"); Preconditions.checkNotNull(secretKeyId, "S3 secret key id can not be null"); Preconditions.checkNotNull(bucketName, "S3 bucket name can not be null"); Preconditions.checkNotNull(region, "S3 region can not be null"); System.out.println("S3 Access Key: " + accessKeyId); System.out.println("S3 Secret Key ID: " + secretKeyId); System.out.println("S3 Bucket Name: " + bucketName); System.out.println("S3 Region: " + region); BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKeyId, secretKeyId); this.s3client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .withRegion(region) .build(); this.bucketName = bucketName; }
@Test public void testAwsV2Signature() throws Exception { client = AmazonS3ClientBuilder.standard() .withClientConfiguration(V2_SIGNER_CONFIG) .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .withEndpointConfiguration(s3EndpointConfig) .build(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(BYTE_SOURCE.size()); client.putObject(containerName, "foo", BYTE_SOURCE.openStream(), metadata); S3Object object = client.getObject(containerName, "foo"); assertThat(object.getObjectMetadata().getContentLength()).isEqualTo( BYTE_SOURCE.size()); try (InputStream actual = object.getObjectContent(); InputStream expected = BYTE_SOURCE.openStream()) { assertThat(actual).hasContentEqualTo(expected); } }
@Test public void testAwsV4SignatureNonChunked() throws Exception { client = AmazonS3ClientBuilder.standard() .withChunkedEncodingDisabled(true) .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .withEndpointConfiguration(s3EndpointConfig) .build(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(BYTE_SOURCE.size()); client.putObject(containerName, "foo", BYTE_SOURCE.openStream(), metadata); S3Object object = client.getObject(containerName, "foo"); assertThat(object.getObjectMetadata().getContentLength()).isEqualTo( BYTE_SOURCE.size()); try (InputStream actual = object.getObjectContent(); InputStream expected = BYTE_SOURCE.openStream()) { assertThat(actual).hasContentEqualTo(expected); } }
@Test public void testAwsV4SignaturePayloadUnsigned() throws Exception { client = AmazonS3ClientBuilder.standard() .withChunkedEncodingDisabled(true) .withPayloadSigningEnabled(false) .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .withEndpointConfiguration(s3EndpointConfig) .build(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(BYTE_SOURCE.size()); client.putObject(containerName, "foo", BYTE_SOURCE.openStream(), metadata); S3Object object = client.getObject(containerName, "foo"); assertThat(object.getObjectMetadata().getContentLength()).isEqualTo( BYTE_SOURCE.size()); try (InputStream actual = object.getObjectContent(); InputStream expected = BYTE_SOURCE.openStream()) { assertThat(actual).hasContentEqualTo(expected); } }
@Test public void testAwsV4SignatureBadIdentity() throws Exception { client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials( "bad-access-key", awsCreds.getAWSSecretKey()))) .withEndpointConfiguration(s3EndpointConfig) .build(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(BYTE_SOURCE.size()); try { client.putObject(containerName, "foo", BYTE_SOURCE.openStream(), metadata); Fail.failBecauseExceptionWasNotThrown(AmazonS3Exception.class); } catch (AmazonS3Exception e) { assertThat(e.getErrorCode()).isEqualTo("InvalidAccessKeyId"); } }
@Test public void testAwsV4SignatureBadCredential() throws Exception { client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials( awsCreds.getAWSAccessKeyId(), "bad-secret-key"))) .withEndpointConfiguration(s3EndpointConfig) .build(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(BYTE_SOURCE.size()); try { client.putObject(containerName, "foo", BYTE_SOURCE.openStream(), metadata); Fail.failBecauseExceptionWasNotThrown(AmazonS3Exception.class); } catch (AmazonS3Exception e) { assertThat(e.getErrorCode()).isEqualTo("SignatureDoesNotMatch"); } }
@Test public void testAwsV2UrlSigning() throws Exception { client = AmazonS3ClientBuilder.standard() .withClientConfiguration(V2_SIGNER_CONFIG) .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .withEndpointConfiguration(s3EndpointConfig) .build(); String blobName = "foo"; ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(BYTE_SOURCE.size()); client.putObject(containerName, blobName, BYTE_SOURCE.openStream(), metadata); Date expiration = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)); URL url = client.generatePresignedUrl(containerName, blobName, expiration, HttpMethod.GET); try (InputStream actual = url.openStream(); InputStream expected = BYTE_SOURCE.openStream()) { assertThat(actual).hasContentEqualTo(expected); } }
/** * Returns a client instance for AWS DynamoDB. * @return a client that talks to DynamoDB */ public static AmazonDynamoDB getClient() { if (ddbClient != null) { return ddbClient; } if (Config.IN_PRODUCTION) { ddbClient = AmazonDynamoDBClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(Config.AWS_ACCESSKEY, Config.AWS_SECRETKEY))). withRegion(Config.AWS_REGION).build(); } else { ddbClient = AmazonDynamoDBClientBuilder.standard(). withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("local", "null"))). withEndpointConfiguration(new EndpointConfiguration(LOCAL_ENDPOINT, "")).build(); } if (!existsTable(Config.getRootAppIdentifier())) { createTable(Config.getRootAppIdentifier()); } ddb = new DynamoDB(ddbClient); Para.addDestroyListener(new DestroyListener() { public void onDestroy() { shutdownClient(); } }); return ddbClient; }
/** * Returns a client instance for AWS SQS. * @return a client that talks to SQS */ public static AmazonSQS getClient() { if (sqsClient != null) { return sqsClient; } if (Config.IN_PRODUCTION) { sqsClient = AmazonSQSClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(Config.AWS_ACCESSKEY, Config.AWS_SECRETKEY))). withRegion(Config.AWS_REGION).build(); } else { sqsClient = AmazonSQSClientBuilder.standard(). withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("x", "x"))). withEndpointConfiguration(new EndpointConfiguration(LOCAL_ENDPOINT, "")).build(); } Para.addDestroyListener(new DestroyListener() { public void onDestroy() { sqsClient.shutdown(); } }); return sqsClient; }
protected AWSIot getClient() { if (iotClient != null) { return iotClient; } iotClient = AWSIotClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(Config.AWS_ACCESSKEY, Config.AWS_SECRETKEY))). withRegion(Config.AWS_REGION).build(); Para.addDestroyListener(new DestroyListener() { public void onDestroy() { shutdownClient(); } }); return iotClient; }
protected AWSIotData getDataClient() { if (iotDataClient != null) { return iotDataClient; } iotDataClient = AWSIotDataClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(Config.AWS_ACCESSKEY, Config.AWS_SECRETKEY))). withRegion(Config.AWS_REGION).build(); Para.addDestroyListener(new DestroyListener() { public void onDestroy() { shutdownDataClient(); } }); return iotDataClient; }
@Test public void getObject_withCustomRegion_returnsClientWithCustomRegion() throws Exception { //Arrange AmazonWebserviceClientFactoryBean<AmazonTestWebserviceClient> factoryBean = new AmazonWebserviceClientFactoryBean<>(AmazonTestWebserviceClient.class, new AWSStaticCredentialsProvider(new BasicAWSCredentials("aaa", "bbb"))); factoryBean.setCustomRegion("eu-west-1"); //Act factoryBean.afterPropertiesSet(); AmazonTestWebserviceClient webserviceClient = factoryBean.getObject(); //Assert Assert.assertEquals("eu-west-1", webserviceClient.getRegion().getName()); }
@Test public void getObject_withRegionProvider_returnsClientWithRegionReturnedByProvider() throws Exception { //Arrange AmazonWebserviceClientFactoryBean<AmazonTestWebserviceClient> factoryBean = new AmazonWebserviceClientFactoryBean<>(AmazonTestWebserviceClient.class, new AWSStaticCredentialsProvider(new BasicAWSCredentials("aaa", "bbb"))); factoryBean.setRegionProvider(new StaticRegionProvider("eu-west-1")); //Act factoryBean.afterPropertiesSet(); AmazonTestWebserviceClient webserviceClient = factoryBean.getObject(); //Assert Assert.assertEquals("eu-west-1", webserviceClient.getRegion().getName()); }
@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()); }
@Test public void credentialsProvider_configWithAccessAndSecretKey_staticAwsCredentialsProviderConfigured() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(ApplicationConfigurationWithAccessKeyAndSecretKey.class); //Act AWSCredentialsProvider awsCredentialsProvider = this.context.getBean(AWSCredentialsProvider.class); //Assert assertNotNull(awsCredentialsProvider); @SuppressWarnings("unchecked") List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProvider, "credentialsProviders"); assertEquals(1, credentialsProviders.size()); assertTrue(AWSStaticCredentialsProvider.class.isInstance(credentialsProviders.get(0))); assertEquals("accessTest", awsCredentialsProvider.getCredentials().getAWSAccessKeyId()); assertEquals("testSecret", awsCredentialsProvider.getCredentials().getAWSSecretKey()); }
@Test public void credentialsProvider_configWithAccessAndSecretKeyAndInstanceProfile_staticAwsCredentialsProviderConfiguredWithInstanceProfile() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(ApplicationConfigurationWithAccessKeyAndSecretKeyAndInstanceProfile.class); //Act AWSCredentialsProvider awsCredentialsProvider = this.context.getBean(AWSCredentialsProvider.class); //Assert 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(EC2ContainerCredentialsProviderWrapper.class.isInstance(credentialsProviders.get(1))); }
@Test public void credentialsProvider_configWithAllProviders_allCredentialsProvidersConfigured() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(ApplicationConfigurationWithAllProviders.class); //Act AWSCredentialsProvider awsCredentialsProvider = this.context.getBean(AWSCredentialsProvider.class); //Assert assertNotNull(awsCredentialsProvider); @SuppressWarnings("unchecked") List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProvider, "credentialsProviders"); assertEquals(3, credentialsProviders.size()); assertTrue(AWSStaticCredentialsProvider.class.isInstance(credentialsProviders.get(0))); assertTrue(EC2ContainerCredentialsProviderWrapper.class.isInstance(credentialsProviders.get(1))); assertTrue(ProfileCredentialsProvider.class.isInstance(credentialsProviders.get(2))); }
@Before public void before() throws Exception { final String userHome = System.getProperty("user.home"); final String propertiesFilename = userHome + "/metamodel-integrationtest-configuration.properties"; final File file = new File(propertiesFilename); Assume.assumeTrue(file.exists()); final Properties props = new Properties(); props.load(new FileReader(file)); final String accessKey = props.getProperty("dynamodb.accessKey"); final String secretKey = props.getProperty("dynamodb.secretKey"); Assume.assumeNotNull(accessKey, secretKey); final Regions region = Regions.fromName(props.getProperty("dynamodb.region", Regions.DEFAULT_REGION.getName())); final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); final AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); client = AmazonDynamoDBClientBuilder.standard().withRegion(region).withCredentials(credentialsProvider).build(); }
private static AmazonS3 s3client() { BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsId, awsKey); AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withRegion(Regions.US_EAST_2) .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .build(); return s3Client; }
private static AmazonS3 s3client() { BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsId, awsKey); AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_2) .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build(); return s3Client; }