Java Code Examples for com.amazonaws.regions.Regions

The following examples show how to use com.amazonaws.regions.Regions. These examples are extracted from open source projects. 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 Project: components   Source File: TalendKinesisProvider.java    License: 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 2
Source Project: aws-xray-sdk-java   Source File: TracingHandlerTest.java    License: 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 3
@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 4
Source Project: Flink-CEPplus   Source File: AWSUtil.java    License: 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 5
Source Project: nifi   Source File: PutDynamoDBTest.java    License: 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 6
Source Project: athenz   Source File: CloudStore.java    License: 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 7
/**
 * 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 8
@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 9
Source Project: aws-doc-sdk-examples   Source File: S3Encrypt.java    License: 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 10
Source Project: pacbot   Source File: PublicAccessAutoFix.java    License: 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 11
Source Project: localization_nifi   Source File: AbstractAWSProcessor.java    License: 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 12
Source Project: strongbox   Source File: RegionResolver.java    License: 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 13
Source Project: strongbox   Source File: IntegrationTestHelper.java    License: 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 14
Source Project: aws-xray-sdk-java   Source File: TracingHandlerTest.java    License: 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 15
Source Project: aws-doc-sdk-examples   Source File: CreateEndpoint.java    License: 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 16
Source Project: chassis   Source File: ConfigurationBuilderTest.java    License: 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 17
@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 18
Source Project: titus-control-plane   Source File: Main.java    License: Apache License 2.0 6 votes vote down vote up
private static AwsIamConnector createConnector() {
    AWSCredentialsProvider baseCredentials = new ProfileCredentialsProvider("default");
    AWSSecurityTokenServiceAsync stsClient = new AmazonStsAsyncProvider(CONFIGURATION, baseCredentials).get();
    AWSCredentialsProvider credentialsProvider = new DataPlaneAgentCredentialsProvider(CONFIGURATION, stsClient, baseCredentials).get();

    Region currentRegion = Regions.getCurrentRegion();
    if (currentRegion == null) {
        currentRegion = Region.getRegion(Regions.US_EAST_1);
    }
    return new AwsIamConnector(
            CONFIGURATION,
            AmazonIdentityManagementAsyncClientBuilder.standard()
                    .withRegion(currentRegion.getName())
                    .withCredentials(credentialsProvider)
                    .build(),
            AWSSecurityTokenServiceAsyncClientBuilder.standard()
                    .withRegion(currentRegion.getName())
                    .withCredentials(credentialsProvider)
                    .build(),
            new DefaultRegistry()
    );
}
 
Example 19
/**
 * Main method to test the integration locally in desktop.
 *
 * NOTE: This uses a different approach to get the KDS events using KCL to trigger lambda.
 *
 */
public static void main(final String[] args) throws Exception {
    final KinesisVideoRekognitionLambdaExample KinesisVideoRekognitionLambdaExample =
            new KinesisVideoRekognitionLambdaExample();
    KinesisVideoRekognitionLambdaExample.initialize(
            System.getProperty("KVSStreamName"), Regions.fromName(System.getenv("AWS_REGION")));
    KinesisVideoRekognitionLambdaExample.startKDSWorker(System.getProperty("KDSStreamName"));
    Thread.sleep(KCL_INIT_DELAY_MILLIS); // Initial delay to wait for KCL to initialize
    while (true) { // For local desktop testing.
        KinesisVideoRekognitionLambdaExample.processRekognizedOutputs();
    }
}
 
Example 20
Source Project: camel-kafka-connector   Source File: AWSRemoteService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Properties getConnectionProperties() {
    Properties properties = new Properties();

    AWSCredentials credentials = getCredentials();

    properties.put(AWSConfigs.ACCESS_KEY, credentials.getAWSAccessKeyId());
    properties.put(AWSConfigs.SECRET_KEY, credentials.getAWSSecretKey());
    properties.put(AWSConfigs.REGION, Regions.US_EAST_1.name());

    return properties;
}
 
Example 21
Source Project: openhab1-addons   Source File: DynamoDBConfig.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static void invalidRegionLogHelp(String region) {
    Regions[] regions = Regions.values();
    String[] regionNames = new String[regions.length];
    for (int i = 0; i < regions.length; i++) {
        regionNames[i] = regions[i].getName();
    }
    logger.error("Specify valid AWS region to use, got {}. Valid values include: {}", region,
            StringUtils.join(regionNames, ','));
}
 
Example 22
public CamelAWSSQSPropertyFactory withAmazonConfig(Properties amazonConfigs, Map<String, String> style) {
    String accessKeyKey = style.get(AWSConfigs.ACCESS_KEY);
    String secretKeyKey = style.get(AWSConfigs.SECRET_KEY);
    String regionKey = style.get(AWSConfigs.REGION);
    String protocolKey = style.get(AWSConfigs.PROTOCOL);
    String hostKey = style.get(AWSConfigs.AMAZON_AWS_HOST);

    setProperty(accessKeyKey,
            amazonConfigs.getProperty(AWSConfigs.ACCESS_KEY, ""));
    setProperty(secretKeyKey,
            amazonConfigs.getProperty(AWSConfigs.SECRET_KEY, ""));
    setProperty(regionKey,
            amazonConfigs.getProperty(AWSConfigs.REGION, Regions.US_EAST_1.name()));

    String protocol = amazonConfigs.getProperty(AWSConfigs.PROTOCOL, "");

    if (protocol != null && !protocol.isEmpty()) {
        setProperty(protocolKey, protocol);
    }

    String amazonAwsHost = amazonConfigs.getProperty(AWSConfigs.AMAZON_AWS_HOST, "");
    if (amazonAwsHost != null && !amazonAwsHost.isEmpty()) {
        setProperty(hostKey, amazonAwsHost);
    }

    return this;
}
 
Example 23
Source Project: strongbox   Source File: StrongboxBootstrapConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
private com.schibsted.security.strongbox.sdk.types.Region getRegion() {
    com.amazonaws.regions.Region region = Regions.getCurrentRegion();
    if (region == null) {
        LOG.debug("Cannot get current AWS region, using default region eu-west-1");
        region = com.amazonaws.regions.Region.getRegion(Regions.EU_WEST_1);
    }
    return com.schibsted.security.strongbox.sdk.types.Region.fromName(region.getName());
}
 
Example 24
public ListBoxModel doFillRegionItems() {
    ListBoxModel items = new ListBoxModel();
    for (Regions region : AVAILABLE_REGIONS) {
        items.add(region.toString(), region.getName());
    }
    return items;
}
 
Example 25
Source Project: aws-lambda-jenkins-plugin   Source File: LambdaClientConfig.java    License: MIT License 5 votes vote down vote up
public AWSLambdaClient getClient() {
    if(useDefaultAWSCredentials){
        return new AWSLambdaClient(new DefaultAWSCredentialsProviderChain(), getClientConfiguration())
                .withRegion(Region.getRegion(Regions.fromName(region)));
    } else {
        return new AWSLambdaClient(new BasicAWSCredentials(accessKeyId, secretKey), getClientConfiguration())
                .withRegion(Region.getRegion(Regions.fromName(region)));
    }
}
 
Example 26
Source Project: aws-doc-sdk-examples   Source File: CopyObject.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    final String USAGE = "\n" +
            "To run this example, supply the name (key) of an S3 object, the bucket name\n" +
            "that it's contained within, and the bucket to copy it to.\n" +
            "\n" +
            "Ex: CopyObject <objectname> <frombucket> <tobucket>\n";

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

    String object_key = args[0];
    String from_bucket = args[1];
    String to_bucket = args[2];

    System.out.format("Copying object %s from bucket %s to %s\n",
            object_key, from_bucket, to_bucket);
    final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build();
    try {
        s3.copyObject(from_bucket, object_key, to_bucket, object_key);
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }
    System.out.println("Done!");
}
 
Example 27
Source Project: kinesis-aggregation   Source File: ProducerUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new Kinesis producer for publishing to Kinesis.
 * 
 * @param region The region of the Kinesis stream to publish to.
 * 
 * @return An Amazon Kinesis producer for publishing to a Kinesis stream.
 */
public static AmazonKinesis getKinesisProducer(String region)
{
    ClientConfiguration config = new ClientConfiguration();
    config.setMaxConnections(25);
    config.setConnectionTimeout(60000);
    config.setSocketTimeout(60000);

    AmazonKinesis producer = new AmazonKinesisClient(new DefaultAWSCredentialsProviderChain(), config);
    producer.setRegion(Region.getRegion(Regions.fromName(region)));

    return producer;
}
 
Example 28
Source Project: StubbornJava   Source File: S3Client.java    License: 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());
}
 
Example 29
public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("Please specify a SSM OpsItem ID value. You can obtain this value using the AWS Console.");
            System.exit(1);
        }

        // snippet-start:[ssm.Java1.get_ops.main]

        // Get the OpsItem ID value
        String opsID = args[0];

        // Create the AWSSimpleSystemsManagement client object
        AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build();

        try {
            GetOpsItemRequest opsRequest = new GetOpsItemRequest();
            opsRequest.setOpsItemId(opsID);

            GetOpsItemResult opsResults = ssm.getOpsItem(opsRequest);

            OpsItem item = opsResults.getOpsItem();

            System.out.println(item.getTitle());
            System.out.println(item.getDescription());
            System.out.println(item.getSource());

        } catch (AmazonServiceException e) {
            e.getStackTrace();
        }
        // snippet-end:[ssm.Java1.get_ops.main]
    }
 
Example 30
Source Project: nifi   Source File: DeleteDynamoDBTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testStringHashStringRangeDeleteThrowsClientException() {
    final DynamoDB mockDynamoDB = new DynamoDB(Regions.AP_NORTHEAST_1) {
        @Override
        public BatchWriteItemOutcome batchWriteItem(TableWriteItems... tableWriteItems) {
            throw new AmazonClientException("clientException");
        }
    };

    deleteDynamoDB = new DeleteDynamoDB() {
        @Override
        protected DynamoDB getDynamoDB() {
            return mockDynamoDB;
        }
    };
    final TestRunner deleteRunner = TestRunners.newTestRunner(deleteDynamoDB);

    deleteRunner.setProperty(AbstractDynamoDBProcessor.ACCESS_KEY,"abcd");
    deleteRunner.setProperty(AbstractDynamoDBProcessor.SECRET_KEY, "cdef");
    deleteRunner.setProperty(AbstractDynamoDBProcessor.REGION, REGION);
    deleteRunner.setProperty(AbstractDynamoDBProcessor.TABLE, stringHashStringRangeTableName);
    deleteRunner.setProperty(AbstractDynamoDBProcessor.HASH_KEY_NAME, "hashS");
    deleteRunner.setProperty(AbstractDynamoDBProcessor.HASH_KEY_VALUE, "h1");
    deleteRunner.setProperty(AbstractDynamoDBProcessor.RANGE_KEY_NAME, "rangeS");
    deleteRunner.setProperty(AbstractDynamoDBProcessor.RANGE_KEY_VALUE, "r1");

    deleteRunner.enqueue(new byte[] {});

    deleteRunner.run(1);

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

}