com.amazonaws.regions.Regions Java Examples

The following examples show how to use com.amazonaws.regions.Regions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: S3Encrypt.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Strict authenticated encryption mode does not support ranged GETs. This is because we must use AES/CTR for ranged
 * GETs which is not an authenticated encryption algorithm. To do a partial get using authenticated encryption you have to
 * get the whole object and filter to the data you want.
 */
public void strictAuthenticatedEncryption_RangeGet_CustomerManagedKey() throws NoSuchAlgorithmException {
    SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
    AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder
            .standard()
            .withRegion(Regions.US_WEST_2)
            .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.StrictAuthenticatedEncryption))
            .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey)))
            .build();

    s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents");
    try {
        s3Encryption.getObject(new GetObjectRequest(BUCKET_NAME, ENCRYPTED_KEY).withRange(0, 2));
    } catch (SecurityException e) {
        System.err.println("Range GET is not supported with authenticated encryption");
    }
}
 
Example #2
Source File: CloudStore.java    From athenz with Apache License 2.0 6 votes vote down vote up
public AmazonS3 getS3Client() {

        if (!awsEnabled) {
            throw new ResourceException(ResourceException.INTERNAL_SERVER_ERROR,
                    "AWS Support not enabled");
        }

        if (credentials == null) {
            throw new ResourceException(ResourceException.INTERNAL_SERVER_ERROR,
                    "AWS Role credentials are not available");
        }

        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(Regions.fromName(awsRegion))
                .build();
    }
 
Example #3
Source File: PutDynamoDBTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    outcome = new BatchWriteItemOutcome(result);
    result.setUnprocessedItems(new HashMap<String, List<WriteRequest>>());
    final DynamoDB mockDynamoDB = new DynamoDB(Regions.AP_NORTHEAST_1) {
        @Override
        public BatchWriteItemOutcome batchWriteItem(TableWriteItems... tableWriteItems) {
            return outcome;
        }
    };

    putDynamoDB = new PutDynamoDB() {
        @Override
        protected DynamoDB getDynamoDB() {
            return mockDynamoDB;
        }
    };

}
 
Example #4
Source File: ConfigurationBuilderTest.java    From chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void buildConfigurationInAws(){
    String az = "testaz";
    String instanceId = RandomStringUtils.randomAlphabetic(10);
    String region = Regions.DEFAULT_REGION.getName();

    ServerInstanceContext serverInstanceContext = EasyMock.createMock(ServerInstanceContext.class);
    EasyMock.expect(serverInstanceContext.getAvailabilityZone()).andReturn(az);
    EasyMock.expect(serverInstanceContext.getInstanceId()).andReturn(instanceId);
    EasyMock.expect(serverInstanceContext.getRegion()).andReturn(region);
    EasyMock.expect(serverInstanceContext.getPrivateIp()).andReturn("127.0.0.1");
    EasyMock.expect(serverInstanceContext.getPublicIp()).andReturn(null);

    EasyMock.replay(serverInstanceContext);

    Configuration configuration = configurationBuilder.withServerInstanceContext(serverInstanceContext).build();

    Assert.assertEquals(az, configuration.getString(BootstrapConfigKeys.AWS_INSTANCE_AVAILABILITY_ZONE.getPropertyName()));
    Assert.assertEquals(instanceId, configuration.getString(BootstrapConfigKeys.AWS_INSTANCE_ID.getPropertyName()));
    Assert.assertEquals(region, configuration.getString(BootstrapConfigKeys.AWS_INSTANCE_REGION.getPropertyName()));
    Assert.assertEquals("127.0.0.1", configuration.getString(BootstrapConfigKeys.AWS_INSTANCE_PRIVATE_IP.getPropertyName()));
    Assert.assertEquals(null, configuration.getString(BootstrapConfigKeys.AWS_INSTANCE_PUBLIC_IP.getPropertyName()));

    EasyMock.verify(serverInstanceContext);
}
 
Example #5
Source File: CreateEndpoint.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

		final String USAGE = "\n" +
                "CreateEndpoint - create an endpoint for an application in pinpoint\n\n" +
                "Usage: CreateEndpoint <appId>\n\n" +
                "Where:\n" +
                "  appId - the ID of the application to create an endpoint for.\n\n";

        if (args.length < 1) {
            System.out.println(USAGE);
            System.exit(1);
        }
        String appId = args[0];

		AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build();

		EndpointResponse response = createEndpoint(pinpoint, appId);

		System.out.println(response.getAddress());
		System.out.println(response.getChannelType());
		System.out.println(response.getApplicationId());
		System.out.println(response.getEndpointStatus());
		System.out.println(response.getRequestId());
		System.out.println(response.getUser());
	}
 
Example #6
Source File: TracingHandlerTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSNSPublish() {
    // Setup test
    // reference : https://docs.aws.amazon.com/sns/latest/api/API_Publish.html
    final String publishResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                                   "<PublishResponse xmlns=\"http://sns.amazonaws.com/doc/2010-03-31/\">" +
                                   "<PublishResult><MessageId>94f20ce6-13c5-43a0-9a9e-ca52d816e90b</MessageId>" +
                                   "</PublishResult>" +
                                   "</PublishResponse>";
    final String topicArn = "testTopicArn";
    AmazonSNS sns = AmazonSNSClientBuilder
        .standard()
        .withRequestHandlers(new TracingHandler())
        .withRegion(Regions.US_EAST_1)
        .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
        .build();
    mockHttpClient(sns, publishResponse);
    // Test logic 
    Segment segment = AWSXRay.beginSegment("test");
    sns.publish(new PublishRequest(topicArn, "testMessage"));
    Assert.assertEquals(1, segment.getSubsegments().size());
    Assert.assertEquals("Publish", segment.getSubsegments().get(0).getAws().get("operation"));
    Assert.assertEquals(topicArn, segment.getSubsegments().get(0).getAws().get("topic_arn"));
}
 
Example #7
Source File: AWSUtil.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an Amazon Kinesis Client.
 * @param configProps configuration properties containing the access key, secret key, and region
 * @param awsClientConfig preconfigured AWS SDK client configuration
 * @return a new Amazon Kinesis Client
 */
public static AmazonKinesis createKinesisClient(Properties configProps, ClientConfiguration awsClientConfig) {
	// set a Flink-specific user agent
	awsClientConfig.setUserAgentPrefix(String.format(USER_AGENT_FORMAT,
			EnvironmentInformation.getVersion(),
			EnvironmentInformation.getRevisionInformation().commitId));

	// utilize automatic refreshment of credentials by directly passing the AWSCredentialsProvider
	AmazonKinesisClientBuilder builder = AmazonKinesisClientBuilder.standard()
			.withCredentials(AWSUtil.getCredentialsProvider(configProps))
			.withClientConfiguration(awsClientConfig);

	if (configProps.containsKey(AWSConfigConstants.AWS_ENDPOINT)) {
		// Set signingRegion as null, to facilitate mocking Kinesis for local tests
		builder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
												configProps.getProperty(AWSConfigConstants.AWS_ENDPOINT),
												null));
	} else {
		builder.withRegion(Regions.fromName(configProps.getProperty(AWSConfigConstants.AWS_REGION)));
	}
	return builder.build();
}
 
Example #8
Source File: ContextRegionConfigurationRegistrarTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void regionProvider_withPlaceHolderConfiguredRegion_staticRegionProviderConfigured()
		throws Exception {
	// Arrange
	this.context = new AnnotationConfigApplicationContext();
	this.context.getEnvironment().getPropertySources().addLast(new MapPropertySource(
			"test", Collections.singletonMap("region", Regions.EU_WEST_1.getName())));
	this.context.register(ApplicationConfigurationWithPlaceHolderRegion.class);

	// Act
	this.context.refresh();
	StaticRegionProvider staticRegionProvider = this.context
			.getBean(StaticRegionProvider.class);

	// Assert
	assertThat(staticRegionProvider).isNotNull();
	assertThat(staticRegionProvider.getRegion())
			.isEqualTo(Region.getRegion(Regions.EU_WEST_1));
}
 
Example #9
Source File: KMSProviderBuilderMockTests.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBareAliasMapping_withLegacyCtor() {
    MockKMSClient client = spy(new MockKMSClient());

    RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
    when(supplier.getClient(any())).thenReturn(client);

    String key1 = client.createKey().getKeyMetadata().getKeyId();
    client.createAlias(new CreateAliasRequest()
        .withAliasName("foo")
        .withTargetKeyId(key1)
    );

    KmsMasterKeyProvider mkp0 = new KmsMasterKeyProvider(
            client, Region.getRegion(Regions.DEFAULT_REGION), Arrays.asList("alias/foo")
    );

    new AwsCrypto().encryptData(mkp0, new byte[0]);
}
 
Example #10
Source File: SsmUtil.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
private static Parameter getParameter(String parameterKey, boolean isEncrypted) {
    LOGGER.info("get ssm parameter key:" + parameterKey);
    AWSCredentialsProvider credentials = InstanceProfileCredentialsProvider.getInstance();
    AWSSimpleSystemsManagement simpleSystemsManagementClient =
        AWSSimpleSystemsManagementClientBuilder.standard().withCredentials(credentials)
            .withRegion(Regions.getCurrentRegion().getName()).build();
    GetParameterRequest parameterRequest = new GetParameterRequest();
    parameterRequest.withName(parameterKey).setWithDecryption(isEncrypted);
    GetParameterResult parameterResult = simpleSystemsManagementClient.getParameter(parameterRequest);
    return parameterResult.getParameter();
}
 
Example #11
Source File: TracingHandlerTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldNotTraceXRaySamplingOperations() {
    com.amazonaws.services.xray.AWSXRay xray = AWSXRayClientBuilder
        .standard()
        .withRequestHandlers(new TracingHandler()).withRegion(Regions.US_EAST_1)
        .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
        .build();
    mockHttpClient(xray, null);

    Segment segment = AWSXRay.beginSegment("test");
    xray.getSamplingRules(new GetSamplingRulesRequest());
    Assert.assertEquals(0, segment.getSubsegments().size());

    xray.getSamplingTargets(new GetSamplingTargetsRequest());
    Assert.assertEquals(0, segment.getSubsegments().size());
}
 
Example #12
Source File: CognitoHelper.java    From alexa-web-information-service-api-samples with MIT License 6 votes vote down vote up
/**
 * Returns the AWS credentials
 *
 * @param idprovider the IDP provider for the login map
 * @param id         the username for the login map.
 * @return returns the credentials based on the access token returned from the user pool.
 */
Credentials GetCredentials(String idprovider, String id) {
    AnonymousAWSCredentials awsCreds = new AnonymousAWSCredentials();
    AmazonCognitoIdentity provider = AmazonCognitoIdentityClientBuilder
            .standard()
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
            .withRegion(Regions.fromName(REGION))
            .build();

    GetIdRequest idrequest = new GetIdRequest();
    idrequest.setIdentityPoolId(FED_POOL_ID);
    idrequest.addLoginsEntry(idprovider, id);
    GetIdResult idResult = provider.getId(idrequest);

    GetCredentialsForIdentityRequest request = new GetCredentialsForIdentityRequest();
    request.setIdentityId(idResult.getIdentityId());
    request.addLoginsEntry(idprovider, id);

    GetCredentialsForIdentityResult result = provider.getCredentialsForIdentity(request);
    return result.getCredentials();
}
 
Example #13
Source File: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the AWS client.
 *
 * @param targetType the target type
 * @param annotation the annotation
 * @param ruleIdentifyingString the rule identifying string
 * @return the AWS client
 * @throws Exception the exception
 */
public static Map<String, Object> getAWSClient(String targetType, Map<String, String> annotation, String ruleIdentifyingString) throws Exception {

	StringBuilder roleArn = new StringBuilder();
	Map<String, Object> clientMap = null;
	roleArn.append(PacmanSdkConstants.ROLE_ARN_PREFIX).append(annotation.get(PacmanSdkConstants.ACCOUNT_ID)).append(":").append(ruleIdentifyingString);

	AWSClientManager awsClientManager = new AWSClientManagerImpl();
	try {
		clientMap = awsClientManager.getClient(annotation.get(PacmanSdkConstants.ACCOUNT_ID),roleArn.toString(), AWSService.valueOf(targetType.toUpperCase()),Regions.fromName(annotation.get(PacmanSdkConstants.REGION) == null ? Regions.DEFAULT_REGION
								.getName() : annotation
								.get(PacmanSdkConstants.REGION)), ruleIdentifyingString);
	} catch (UnableToCreateClientException e1) {
		String msg = String.format("unable to create client for account %s  and region %s",annotation.get(PacmanSdkConstants.ACCOUNT_ID), annotation.get(PacmanSdkConstants.REGION));
		logger.error(msg);
		throw new Exception(msg);
	}
	return clientMap;
}
 
Example #14
Source File: AbstractAWSProcessor.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
protected void initializeRegionAndEndpoint(ProcessContext context) {
    // if the processor supports REGION, get the configured region.
    if (getSupportedPropertyDescriptors().contains(REGION)) {
        final String region = context.getProperty(REGION).getValue();
        if (region != null) {
            this.region = Region.getRegion(Regions.fromName(region));
            client.setRegion(this.region);
        } else {
            this.region = null;
        }
    }

    // if the endpoint override has been configured, set the endpoint.
    // (per Amazon docs this should only be configured at client creation)
    final String urlstr = StringUtils.trimToEmpty(context.getProperty(ENDPOINT_OVERRIDE).getValue());
    if (!urlstr.isEmpty()) {
        this.client.setEndpoint(urlstr);
    }

}
 
Example #15
Source File: TalendKinesisProvider.java    From components with Apache License 2.0 6 votes vote down vote up
public TalendKinesisProvider(boolean specifyCredentials, String accessKey, String secretKey,
        boolean specifyEndpoint, String endpoint, Regions region, boolean specifySTS, String roleArn,
        String roleSessionName, boolean specifyRoleExternalId, String roleExternalId, boolean specifySTSEndpoint,
        String stsEndpoint) {
    this.specifyCredentials = specifyCredentials;
    this.accessKey = accessKey;
    this.secretKey = secretKey;
    this.region = region;
    this.specifyEndpoint = specifyEndpoint;
    this.endpoint = endpoint;
    this.specifySTS = specifySTS;
    this.roleArn = roleArn;
    this.roleSessionName = roleSessionName;
    this.specifyRoleExternalId = specifyRoleExternalId;
    this.roleExternalId = roleExternalId;
    this.specifySTSEndpoint = specifySTSEndpoint;
    this.stsEndpoint = stsEndpoint;
}
 
Example #16
Source File: RegionResolver.java    From strongbox with Apache License 2.0 6 votes vote down vote up
public static String getRegion() {
    if (userSetRegion.isPresent()) {
        return userSetRegion.get().getName();
    }

    if (cachedRegion.isPresent()) {
        return cachedRegion.get().getName();
    }

    CustomRegionProviderChain regionProvider = new CustomRegionProviderChain();
    try {
        Region region = regionProvider.resolveRegion();

        cachedRegion = Optional.of(region);

        return region.getName();
    } catch (FailedToResolveRegionException e) {
        return Regions.DEFAULT_REGION.getName();
    }
}
 
Example #17
Source File: IntegrationTestHelper.java    From strongbox with Apache License 2.0 6 votes vote down vote up
public static void cleanUpFromPreviousRuns(Regions testRegion, String groupPrefix) {
    LOG.info("Cleaning up from previous test runs...");

    // Get time an hour ago to clean up anything that was created more than an hour ago. That should be more than
    // enough time for test runs so anything left over by that time will be junk to clean up.
    Date createdBeforeThreshold = new Date(System.currentTimeMillis() - (60 * 60 * 1000));

    // Resource prefix for the test groups so we only clean up the resources related to the tests.
    // TODO is there a method somewhere that will construct this for me so it will always match the
    // actual names constructed by the code?
    String testResourcePrefix = String.format(
            "strongbox_%s_%s", testRegion.getName(),
            AWSResourceNameSerialization.encodeSecretsGroupName(groupPrefix));

    AWSCredentialsProvider awsCredentials = new DefaultAWSCredentialsProviderChain();

    cleanUpDynamoDBTables(testRegion, testResourcePrefix, createdBeforeThreshold, awsCredentials);
    cleanUpKMSKeys(testRegion, testResourcePrefix, createdBeforeThreshold, awsCredentials);
    cleanUpIAM(testRegion, testResourcePrefix, createdBeforeThreshold, awsCredentials);
}
 
Example #18
Source File: AmazonWebserviceClientConfigurationUtilsTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void registerAmazonWebserviceClient_withMinimalConfiguration_returnsDefaultBeanDefinition()
		throws Exception {
	// Arrange
	DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
	beanFactory.registerSingleton(
			AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME,
			new StaticAwsCredentialsProvider());

	BeanDefinitionHolder beanDefinitionHolder = AmazonWebserviceClientConfigurationUtils
			.registerAmazonWebserviceClient(new Object(), beanFactory,
					AmazonTestWebserviceClient.class.getName(), null, null);

	// Act
	beanFactory.preInstantiateSingletons();
	AmazonTestWebserviceClient client = beanFactory.getBean(
			beanDefinitionHolder.getBeanName(), AmazonTestWebserviceClient.class);

	// Assert
	assertThat(client).isNotNull();
	assertThat(beanDefinitionHolder.getBeanName()).isEqualTo("amazonTestWebservice");
	assertThat(client.getRegion())
			.isEqualTo(Region.getRegion(Regions.DEFAULT_REGION));
}
 
Example #19
Source File: AWSClientFactory.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 5 votes vote down vote up
public AWSClients getAwsClient(
        final String awsAccessKey,
        final String awsSecretKey,
        final String proxyHost,
        final int proxyPort,
        final String region,
        final String pluginUserAgentPrefix) {

    final Region awsRegion = Region.getRegion(Regions.fromName(region));
    final AWSClients aws;

    if (StringUtils.isEmpty(awsAccessKey) && StringUtils.isEmpty(awsSecretKey)) {
        aws = AWSClients.fromDefaultCredentialChain(
                awsRegion,
                proxyHost,
                proxyPort,
                pluginUserAgentPrefix);
    }
    else {
        aws = AWSClients.fromBasicCredentials(
                awsRegion,
                awsAccessKey,
                awsSecretKey,
                proxyHost,
                proxyPort,
                pluginUserAgentPrefix);
    }

    return aws;
}
 
Example #20
Source File: AbstractAWSProcessor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private static AllowableValue[] getAvailableRegions() {
    final List<AllowableValue> values = new ArrayList<>();
    for (final Regions regions : Regions.values()) {
        values.add(createAllowableValue(regions));
    }

    return (AllowableValue[]) values.toArray(new AllowableValue[values.size()]);
}
 
Example #21
Source File: PutDynamoDBTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringHashStringRangePutThrowsRuntimeException() {
    final DynamoDB mockDynamoDB = new DynamoDB(Regions.AP_NORTHEAST_1) {
        @Override
        public BatchWriteItemOutcome batchWriteItem(TableWriteItems... tableWriteItems) {
            throw new RuntimeException("runtimeException");
        }
    };

    putDynamoDB = new PutDynamoDB() {
        @Override
        protected DynamoDB getDynamoDB() {
            return mockDynamoDB;
        }
    };
    final TestRunner putRunner = TestRunners.newTestRunner(putDynamoDB);

    putRunner.setProperty(AbstractDynamoDBProcessor.ACCESS_KEY,"abcd");
    putRunner.setProperty(AbstractDynamoDBProcessor.SECRET_KEY, "cdef");
    putRunner.setProperty(AbstractDynamoDBProcessor.REGION, REGION);
    putRunner.setProperty(AbstractDynamoDBProcessor.TABLE, stringHashStringRangeTableName);
    putRunner.setProperty(AbstractDynamoDBProcessor.HASH_KEY_NAME, "hashS");
    putRunner.setProperty(AbstractDynamoDBProcessor.HASH_KEY_VALUE, "h1");
    putRunner.setProperty(AbstractDynamoDBProcessor.RANGE_KEY_NAME, "rangeS");
    putRunner.setProperty(AbstractDynamoDBProcessor.RANGE_KEY_VALUE, "r1");
    putRunner.setProperty(AbstractWriteDynamoDBProcessor.JSON_DOCUMENT, "document");
    String document = "{\"name\":\"john\"}";
    putRunner.enqueue(document.getBytes());

    putRunner.run(1);

    putRunner.assertAllFlowFilesTransferred(AbstractDynamoDBProcessor.REL_FAILURE, 1);
    List<MockFlowFile> flowFiles = putRunner.getFlowFilesForRelationship(AbstractDynamoDBProcessor.REL_FAILURE);
    for (MockFlowFile flowFile : flowFiles) {
        assertEquals("runtimeException", flowFile.getAttribute(AbstractDynamoDBProcessor.DYNAMODB_ERROR_EXCEPTION_MESSAGE));
    }

}
 
Example #22
Source File: AWSClientsTest.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 5 votes vote down vote up
@Test
public void usesUsEast1AsDefaultRegion() {
    // when
    final AWSClients awsClients = new AWSClients(null, mock(AWSCredentials.class), PROXY_HOST, PROXY_PORT, PLUGIN_VERSION, codePipelineClientFactory, s3ClientFactory);
    final AWSCodePipeline codePipelineClient = awsClients.getCodePipelineClient();
    final AmazonS3 s3Client = awsClients.getS3Client(mock(AWSCredentialsProvider.class));

    // then
    verify(codePipelineClient).setRegion(Region.getRegion(Regions.US_EAST_1));
    verify(s3Client).setRegion(Region.getRegion(Regions.US_EAST_1));

}
 
Example #23
Source File: AmazonS3Configuration.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Bean
public AmazonS3 amazonS3Client(AmazonS3ConfigurationProperties amazonS3ConfigurationProperties) {
     AmazonS3ClientBuilder amazonS3ClientBuilder = AmazonS3ClientBuilder
            .standard()
            .withRegion(Regions.fromName(amazonS3ConfigurationProperties.getRegion()));

    if (amazonS3ConfigurationProperties.getAccessKeyId() != null) {
        AWSCredentials credentials = new BasicAWSCredentials(amazonS3ConfigurationProperties.getAccessKeyId(), amazonS3ConfigurationProperties.getAccessKeySecret());
        amazonS3ClientBuilder.withCredentials(new AWSStaticCredentialsProvider(credentials));
    }

    AmazonS3 amazonS3 = amazonS3ClientBuilder.build();
    return amazonS3;
}
 
Example #24
Source File: AwsSessionService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
public AmazonEC2Client getEC2Session(AWSEnvironment environment){
    BasicSessionCredentials creds = credentialCache.getUnchecked(environment);
    AmazonEC2Client ec2 = awsSessionFactory.createEC2Session(creds);
    ec2.setRegion(Region.getRegion(Regions.fromName(environment.getRegion())));
    return ec2;

}
 
Example #25
Source File: AWSClientManager.java    From aws-mobile-self-paced-labs-samples with Apache License 2.0 5 votes vote down vote up
public static void init(Context context)
{
       provider = new CognitoCachingCredentialsProvider(context, 
               AWS_ACCOUNT_ID, COGNITO_POOL_ID, COGNTIO_ROLE_UNAUTH,
               COGNITO_ROLE_AUTH, Regions.US_EAST_1);

       //initialize the Cognito Sync Client
       
       //initialize the Other Clients
	manager = new TransferManager(provider);
	analytics = MobileAnalyticsManager.getOrCreateInstance(context, "App_ID_Here", Regions.US_EAST_1, provider);

}
 
Example #26
Source File: DeleteBucketPolicy.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    final String USAGE = "\n" +
            "Usage:\n" +
            "    DeleteBucketPolicy <bucket>\n\n" +
            "Where:\n" +
            "    bucket - the bucket to delete the policy from.\n\n" +
            "Example:\n" +
            "    DeleteBucketPolicy testbucket\n\n";

    if (args.length < 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String bucket_name = args[0];
    String policy_text = null;

    System.out.format("Deleting policy from bucket: \"%s\"\n\n", bucket_name);

    final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build();
    try {
        s3.deleteBucketPolicy(bucket_name);
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }

    System.out.println("Done!");
}
 
Example #27
Source File: AWS.java    From graylog-plugin-aws with Apache License 2.0 5 votes vote down vote up
/**
 * Build a list of region choices with both a value (persisted in configuration) and display value (shown to the user).
 *
 * The display value is formatted nicely: "EU (London): eu-west-2"
 * The value is eventually passed to Regions.fromName() to get the actual region object: eu-west-2
 * @return a choices map with configuration value map keys and display value map values.
 */
public static Map<String, String> buildRegionChoices() {
    Map<String, String> regions = Maps.newHashMap();
    for (Regions region : Regions.values()) {

        String displayValue = String.format("%s: %s", region.getDescription(), region.getName());
        regions.put(region.getName(), displayValue);
    }
    return regions;
}
 
Example #28
Source File: AWSCodePipelineSCM.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 5 votes vote down vote up
public ListBoxModel doFillRegionItems() {
    final ListBoxModel items = new ListBoxModel();

    for (final Regions region : AVAILABLE_REGIONS) {
        items.add(region.getDescription() + " " + region.getName(), region.getName());
    }

    return items;
}
 
Example #29
Source File: JavaKinesisVideoServiceClient.java    From amazon-kinesis-video-streams-producer-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public StreamDescription describeStream(@Nonnull final String streamName,
        final long timeoutInMillis,
        @Nullable final KinesisVideoCredentialsProvider credentialsProvider)
        throws KinesisVideoException {
    final AmazonKinesisVideo serviceClient = createAmazonKinesisVideoClient(credentialsProvider,
            Region.getRegion(Regions.fromName(configuration.getRegion())),
            configuration.getEndpoint(),
            (int) timeoutInMillis);

    final DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest()
            .withStreamName(streamName);

    log.debug("calling describe stream: " + describeStreamRequest.toString());

    final DescribeStreamResult describeStreamResult;
    try {
        describeStreamResult = serviceClient.describeStream(describeStreamRequest);
    } catch (final AmazonClientException e) {
        log.exception(e, "Service call failed.");
        throw new KinesisVideoException(e);
    }

    if (null == describeStreamResult) {
        log.debug("describe stream returned null");
        return null;
    }

    log.debug("describe stream result: " + describeStreamResult.toString());
    return toStreamDescription(describeStreamResult);
}
 
Example #30
Source File: S3Client.java    From StubbornJava with MIT License 5 votes vote down vote up
public static S3Client fromAccessAndScret(String accessKey, String secretKey, Regions region) {
    BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
    return new S3Client(AmazonS3ClientBuilder.standard()
                                    .withRegion(region)
                                    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                                    .build());
}