Java Code Examples for com.amazonaws.regions.Regions

The following are top voted examples for showing how to use com.amazonaws.regions.Regions. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring-cloud-stream-binder-aws-kinesis   File: LocalKinesisResource.java   View source code 8 votes vote down vote up
@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();
}
 
Example 2
Project: cyberduck   File: AmazonIdentityConfiguration.java   View source code 7 votes vote down vote up
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();
}
 
Example 3
Project: alexa-skill-java   File: DBUtil.java   View source code 6 votes vote down vote up
private static AmazonDynamoDB getClient() {
    if (null != dynamodbClient) {
        return dynamodbClient;
    }

    String region = System.getProperty("DYNAMODB_REGION");
    if (null == region) {
        System.err.println("Region not set, default \"" + Regions.US_EAST_1.name() + "\" is used");
        region = Regions.US_EAST_1.name();
    }
    System.out.println("DynamoDB region: " + region);

    dynamodbClient = AmazonDynamoDBClientBuilder.standard()
            .withRegion(region)
            .build();

    return dynamodbClient;
}
 
Example 4
Project: Reer   File: S3RegionalResource.java   View source code 6 votes vote down vote up
private void configure() {
    Matcher matcher = REGIONAL_ENDPOINT_PATTERN.matcher(uri.toString());
    if (matcher.find()) {
        String bucketName = matcher.group(1);
        String region = matcher.group(2);
        String key = matcher.group(4);
        Region derivedRegion;
        if (region.equals("external-1")) {
            derivedRegion = Region.getRegion(Regions.US_EAST_1);
        } else {
            derivedRegion = RegionUtils.getRegion(region);
        }

        this.region = Optional.of(derivedRegion);
        this.bucketName = bucketName;
        this.key = key;
    } else {
        this.region = Optional.absent();
        this.bucketName = getBucketName(uri.getHost());
        this.key = getS3BucketKey(uri);
    }
}
 
Example 5
Project: intellij-idea-plugin-connector-for-aws-lambda   File: ConnectorPresenterImpl.java   View source code 6 votes vote down vote up
@Override
public void setCredentialProfile(CredentialProfileEntry credentialProfileEntry) {
    BasicProfile basicProfile = credentialProfileEntry.getBasicProfile();
    Regions lastSelectedRegion = getLastSelectedRegion();
    Regions region = lastSelectedRegion;
    if(!isEmpty(basicProfile.getRegion())) {
        region = tryGetRegionBy(basicProfile.getRegion());
    }
    if(region == null){
        region = lastSelectedRegion;
    }
    String credentialProfile = credentialProfileEntry.getName();
    connectorSettings.setLastSelectedCredentialProfile(credentialProfile);
    setRegionAndProfile(region, credentialProfile);
    if(!lastSelectedRegion.getName().equals(region.getName())){
        view.setRegion(region);
    }
    CredentialProfileEntry profileEntry = view.getSelectedCredentialProfileEntry();
    if(profileEntry == null) {
        view.logInfo("Credential profile is not selected.");
    } else {
        view.logInfo("Selected Credential profile: \"%s\"", profileEntry.getName());
    }
    refreshStatus();
}
 
Example 6
Project: log4j-aws-appenders   File: AbstractLogWriter.java   View source code 6 votes vote down vote up
/**
 *  Common support code: attempts to configure client endpoint and/or region.
 *
 *  @param  client      A constructed writer-specific service client.
 *  @param  endpoint    A possibly-null endpoint specification.
 */
protected <T extends AmazonWebServiceClient> T tryConfigureEndpointOrRegion(T client, String endpoint)
{
    // explicit endpoint takes precedence over region retrieved from environment
    if (endpoint != null)
    {
        LogLog.debug(getClass().getSimpleName() + ": configuring endpoint: " + endpoint);
        client.setEndpoint(endpoint);
        return client;
    }

    String region = System.getenv("AWS_REGION");
    if (region != null)
    {
        LogLog.debug(getClass().getSimpleName() + ": configuring region: " + region);
        client.configureRegion(Regions.fromName(region));
        return client;
    }

    return client;
}
 
Example 7
Project: circus-train   File: S3MapReduceCpOptionsParserTest.java   View source code 6 votes vote down vote up
@Before
public void init() {
  copierOptions.put(CREDENTIAL_PROVIDER, URI.create("localjceks://file/foo/bar.jceks"));
  copierOptions.put(MULTIPART_UPLOAD_CHUNK_SIZE, 4096);
  copierOptions.put(S3_SERVER_SIDE_ENCRYPTION, true);
  copierOptions.put(STORAGE_CLASS, StorageClass.Glacier.toString());
  copierOptions.put(TASK_BANDWIDTH, 1024);
  copierOptions.put(NUMBER_OF_WORKERS_PER_MAP, 12);
  copierOptions.put(MULTIPART_UPLOAD_THRESHOLD, 2048L);
  copierOptions.put(MAX_MAPS, 5);
  copierOptions.put(COPY_STRATEGY, "mycopystrategy");
  copierOptions.put(LOG_PATH, new Path("hdfs:///tmp/logs"));
  copierOptions.put(REGION, Regions.EU_WEST_1.getName());
  copierOptions.put(IGNORE_FAILURES, false);
  copierOptions.put(S3_ENDPOINT_URI, "http://s3.endpoint/");
  copierOptions.put(UPLOAD_RETRY_COUNT, 5);
  copierOptions.put(UPLOAD_RETRY_DELAY_MS, 520);
  copierOptions.put(UPLOAD_BUFFER_SIZE, 1024);
  parser = new S3MapReduceCpOptionsParser(SOURCES, TARGET, DEFAULT_CREDS_PROVIDER);
}
 
Example 8
Project: circus-train   File: S3MapReduceCpOptionsParserTest.java   View source code 6 votes vote down vote up
private void assertDefaults(S3MapReduceCpOptions options) {
  assertThat(options.getCredentialsProvider(), is(URI.create("localjceks://file/foo/bar.jceks")));
  assertThat(options.getMultipartUploadPartSize(), is(4096L));
  assertThat(options.isS3ServerSideEncryption(), is(true));
  assertThat(options.getStorageClass(), is(StorageClass.Glacier.toString()));
  assertThat(options.getMaxBandwidth(), is(1024L));
  assertThat(options.getNumberOfUploadWorkers(), is(12));
  assertThat(options.getMultipartUploadThreshold(), is(2048L));
  assertThat(options.getMaxMaps(), is(5));
  assertThat(options.getCopyStrategy(), is("mycopystrategy"));
  assertThat(options.getLogPath(), is(new Path("hdfs:///tmp/logs")));
  assertThat(options.getRegion(), is(Regions.EU_WEST_1.getName()));
  assertThat(options.isIgnoreFailures(), is(false));
  assertThat(options.getS3EndpointUri(), is(URI.create("http://s3.endpoint/")));
  assertThat(options.getUploadRetryCount(), is(5));
  assertThat(options.getUploadRetryDelayMs(), is(520L));
  assertThat(options.getUploadBufferSize(), is(1024));
}
 
Example 9
Project: full-javaee-app   File: S3Object.java   View source code 6 votes vote down vote up
public static String webHookDump(InputStream stream, String school, String extension) {
    if (stream != null) {
        extension = extension == null || extension.isEmpty() ? ".xml" : extension.contains(".") ? extension : "." + extension;
        String fileName = "webhooks/" + school + "/" + school + "_" + Clock.getCurrentDateDashes() + "_" + Clock.getCurrentTime() + extension;
        AmazonS3 s3 = new AmazonS3Client();
        Region region = Region.getRegion(Regions.US_WEST_2);
        s3.setRegion(region);
        try {
            File file = CustomUtilities.inputStreamToFile(stream);
            s3.putObject(new PutObjectRequest(name, fileName, file));
            return CustomUtilities.fileToString(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return "";
}
 
Example 10
Project: graylog-plugin-s3   File: S3Transport.java   View source code 6 votes vote down vote up
@Override
public void doLaunch(MessageInput input) throws MisfireException {
    serverStatus.awaitRunning(() -> lifecycleStateChange(Lifecycle.RUNNING));

    LOG.info("Starting s3 subscriber");

    final String legacyRegionName = input.getConfiguration().getString(CK_LEGACY_AWS_REGION, DEFAULT_REGION.getName());
    final String sqsRegionName = input.getConfiguration().getString(CK_AWS_SQS_REGION, legacyRegionName);
    final String s3RegionName = input.getConfiguration().getString(CK_AWS_S3_REGION, legacyRegionName);

    subscriber = new S3Subscriber(
            Region.getRegion(Regions.fromName(sqsRegionName)),
            Region.getRegion(Regions.fromName(s3RegionName)),
            input.getConfiguration().getString(CK_SQS_NAME),
            input,
            input.getConfiguration().getString(CK_ACCESS_KEY),
            input.getConfiguration().getString(CK_SECRET_KEY),
            input.getConfiguration().getInt(CK_THREAD_COUNT)
    );

    subscriber.start();
}
 
Example 11
Project: intellij-idea-plugin-connector-for-aws-lambda   File: ConnectorViewFactory.java   View source code 6 votes vote down vote up
@Override
public void setRegion(Regions region) {
    if(setRegionOperationInProgress){
        return;
    }
    try {
        setRegionOperationInProgress = true;
        for (int i = 0; i < regionList.getItemCount(); i++) {
            if(((RegionEntry) regionList.getItemAt(i)).getName().equals(region.getName())){
                regionList.setSelectedIndex(i);
                return;
            }
        }
    } finally {
        setRegionOperationInProgress = false;
    }
}
 
Example 12
Project: aws-codecommit-trigger-plugin   File: SQSFactoryImpl.java   View source code 6 votes vote down vote up
private AmazonSQSAsyncClientBuilder createStandardAsyncClientBuilder(SQSQueue queue, AWSCredentialsProvider credentials) {
    ClientConfiguration clientConfiguration = this.getClientConfiguration(queue);
    AmazonSQSAsyncClientBuilder builder = AmazonSQSAsyncClientBuilder.standard()
        .withClientConfiguration(clientConfiguration)
        .withCredentials(credentials)
        .withExecutorFactory(this.SQSExecutorFactory);

    if (queue != null) {
        Regions region = queue.getRegion();
        if (region != null) {
            builder.withRegion(region);
        }
    }

    return builder;
}
 
Example 13
Project: strongbox   File: RegionResolver.java   View source code 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 14
Project: generator-jhipster-storage   File: _StorageConfiguration.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 15
Project: strongbox   File: IntegrationTestHelper.java   View source code 6 votes vote down vote up
private static void cleanUpKMSKeys(Regions testRegion, String testResourcePrefix, Date createdBeforeThreshold,
                                   AWSCredentialsProvider awsCredentials) {
    LOG.info("Cleaning KMS...");

    AWSKMS kmsClient = AWSKMSClientBuilder.standard()
            .withCredentials(awsCredentials)
            .withRegion(testRegion)
            .build();

    List<AliasListEntry> keys = kmsClient.listAliases().getAliases();
    for (AliasListEntry entry: keys) {
        if (!entry.getAliasName().startsWith("alias/" + testResourcePrefix)) {
            continue;
        }

        DescribeKeyRequest request = new DescribeKeyRequest().withKeyId(entry.getTargetKeyId());
        KeyMetadata metadata = kmsClient.describeKey(request).getKeyMetadata();

        if (KMSKeyState.fromString(metadata.getKeyState()) != KMSKeyState.PENDING_DELETION &&
                metadata.getCreationDate().before(createdBeforeThreshold)) {
            LOG.info("Scheduling KMS key for deletion:" + entry.getAliasName());
            scheduleKeyDeletion(kmsClient, entry);
        }
    }
}
 
Example 16
Project: ibm-cos-sdk-java   File: AwsClientBuilderTest.java   View source code 6 votes vote down vote up
/**
 * The sync client is tested less thoroughly then the async client primarily because the async
 * client exercises most of the same code paths so a bug introduced in the sync client builder
 * should be exposed via tests written against the async builder. This test is mainly for
 * additional coverage of the sync builder in case there is a regression specific to sync
 * builders.
 */
@Test
public void syncClientBuilder() {
    final List<RequestHandler2> requestHandlers = createRequestHandlerList(
            new ConcreteRequestHandler(), new ConcreteRequestHandler());
    final AWSCredentialsProvider credentials = mock(AWSCredentialsProvider.class);
    final RequestMetricCollector metrics = mock(RequestMetricCollector.class);

    //@formatter:off
    AmazonConcreteClient client = new ConcreteSyncBuilder()
            .withRegion(Regions.EU_CENTRAL_1)
            .withClientConfiguration(new ClientConfiguration().withSocketTimeout(1234))
            .withCredentials(credentials)
            .withMetricsCollector(metrics)
            .withRequestHandlers(requestHandlers.toArray(new RequestHandler2[requestHandlers.size()]))
            .build();
    //@formatter:on

    assertEquals(URI.create("https://mockprefix.eu-central-1.amazonaws.com"),
                 client.getEndpoint());
    assertEquals(1234, client.getSyncParams().getClientConfiguration().getSocketTimeout());
    assertEquals(requestHandlers, client.getSyncParams().getRequestHandlers());
    assertEquals(credentials, client.getSyncParams().getCredentialsProvider());
    assertEquals(metrics, client.getSyncParams().getRequestMetricCollector());
}
 
Example 17
Project: intellij-idea-plugin-connector-for-aws-lambda   File: ConnectorPresenterImpl.java   View source code 5 votes vote down vote up
private Regions tryGetRegionBy(String regionName) {
    for (Regions region : Regions.values()){
        if(region.getName().equals(regionName)){
            return region;
        }
    }
    return null;
}
 
Example 18
Project: mm-system-2017   File: ClientDownloadFile.java   View source code 5 votes vote down vote up
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;
	}
 
Example 19
Project: amazon-kinesis-video-streams-parser-library   File: KinesisVideoExample.java   View source code 5 votes vote down vote up
@Builder
private KinesisVideoExample(Regions region,
        String streamName,
        AWSCredentialsProvider credentialsProvider,
        InputStream inputVideoStream) {
    super(region, credentialsProvider, streamName);
    final AmazonKinesisVideoClientBuilder builder = AmazonKinesisVideoClientBuilder.standard();
    configureClient(builder);
    this.amazonKinesisVideo = builder.build();
    this.inputStream = inputVideoStream;
    this.executorService = Executors.newFixedThreadPool(2);
}
 
Example 20
Project: intellij-idea-plugin-connector-for-aws-lambda   File: ConnectorModel.java   View source code 5 votes vote down vote up
public ConnectorModel(Regions region, String profileName) {

        ProfileCredentialsProvider profileCredentialsProvider = new ProfileCredentialsProvider(profileName);

        awsLambdaClient = AWSLambdaClientBuilder.standard()
                .withRegion(region)
                .withCredentials(profileCredentialsProvider)
                .build();
    }
 
Example 21
Project: intellij-idea-plugin-connector-for-aws-lambda   File: ConnectorPresenterImpl.java   View source code 5 votes vote down vote up
@Override
public void setRegion(RegionEntry regionEntry) {
    Regions region = tryGetRegionBy(regionEntry.getName());
    if(region == null) {
        return;
    }
    setRegionAndProfile(region, connectorSettings.getLastSelectedCredentialProfile());
}
 
Example 22
Project: secrets-locker   File: KmsEncryptionService.java   View source code 5 votes vote down vote up
private MasterKeyProvider<?> masterKeyProvider() {

        final AWSCredentialsProvider credentials
                = new DefaultAWSCredentialsProviderChain();

        List<KmsMasterKey> masterKeys
                = new LinkedList<>();

        for (String region : this.regions) {
            KmsMasterKeyProvider provider
                    = new KmsMasterKeyProvider(
                            credentials,
                            Region.getRegion(
                                    Regions.fromName(
                                            region)),
                            new ClientConfiguration(),
                            this.keyId);



            masterKeys.add(
                    provider.getMasterKey(
                            this.keyId));
        }

        return MultipleProviderFactory
                .buildMultiProvider(
                        masterKeys);
    }
 
Example 23
Project: amazon-kinesis-video-streams-parser-library   File: PutMediaWorker.java   View source code 5 votes vote down vote up
private PutMediaWorker(Regions region,
        AWSCredentialsProvider credentialsProvider,
        String streamName,
        InputStream inputStream,
        String endPoint) {
    super(region, credentialsProvider, streamName);
    this.inputStream = inputStream;

    AmazonKinesisVideoPutMediaClientBuilder builder =
            AmazonKinesisVideoPutMediaClient.builder().withEndpoint(endPoint);
    conifgurePutMediaClient(builder);
    this.putMedia = builder.build();
}
 
Example 24
Project: jenkins-aws-bucket-credentials   File: AwsKmsClientBuilder.java   View source code 5 votes vote down vote up
public AWSKMSClient build() {
    ClientConfiguration config = new ClientConfiguration();
    if (!Util.fixNull(host).trim().isEmpty()) {
        config.setProxyHost(this.host);
        config.setProxyPort(this.port);
    }
    AWSKMSClient client = new AWSKMSClient(new DefaultAWSCredentialsProviderChain(), config);
    if (!Util.fixNull(region).trim().isEmpty()) {
        client.setRegion(Region.getRegion(Regions.fromName(region)));
    }
    return client;
}
 
Example 25
Project: intellij-idea-plugin-connector-for-aws-lambda   File: ConnectorViewFactory.java   View source code 5 votes vote down vote up
@Override
public void setRegionList(List<RegionEntry> regions, Regions selectedRegion) {
    regionList.removeAllItems();
    RegionEntry selectedRegionEntry = null;
    for(RegionEntry entry : regions) {
        regionList.addItem(entry);
        if(selectedRegion != null && entry.getRegion().getName().equals(selectedRegion.getName())) {
            selectedRegionEntry = entry;
        }
    }
    if(selectedRegionEntry != null) {
        regionList.setSelectedItem(selectedRegionEntry);
    }
}
 
Example 26
Project: circus-train   File: S3MapReduceCpCopierTest.java   View source code 5 votes vote down vote up
@Test
public void overwriteAllCopierOptions() throws Exception {
  when(copierOptions.get(CREDENTIAL_PROVIDER)).thenReturn("jceks://hdfs/foo/bar.jceks");
  when(copierOptions.get(MULTIPART_UPLOAD_CHUNK_SIZE)).thenReturn("1234");
  when(copierOptions.get(S3_SERVER_SIDE_ENCRYPTION)).thenReturn("true");
  when(copierOptions.get(STORAGE_CLASS)).thenReturn("reduced_redundancy");
  when(copierOptions.get(TASK_BANDWIDTH)).thenReturn("567");
  when(copierOptions.get(NUMBER_OF_WORKERS_PER_MAP)).thenReturn("89");
  when(copierOptions.get(MULTIPART_UPLOAD_THRESHOLD)).thenReturn("123456");
  when(copierOptions.get(MAX_MAPS)).thenReturn("78");
  when(copierOptions.get(COPY_STRATEGY)).thenReturn("the-strategy");
  when(copierOptions.get(LOG_PATH)).thenReturn("hdfs://path/to/logs/");
  when(copierOptions.get(REGION)).thenReturn("us-east-1");
  when(copierOptions.get(IGNORE_FAILURES)).thenReturn("true");

  S3MapReduceCpCopier copier = new S3MapReduceCpCopier(conf, sourceDataBaseLocation, Collections.<Path> emptyList(),
      replicaDataLocation, copierOptions, executor, metricRegistry);
  Metrics metrics = copier.copy();
  assertThat(metrics, not(nullValue()));

  verify(executor).exec(confCaptor.capture(), optionsCaptor.capture());

  S3MapReduceCpOptions options = optionsCaptor.getValue();
  assertThat(options.getSources(), is(Arrays.asList(sourceDataBaseLocation)));
  assertThat(options.getTarget(), is(replicaDataLocation.toUri()));
  assertThat(options.getCredentialsProvider(), is(URI.create("jceks://hdfs/foo/bar.jceks")));
  assertThat(options.getMultipartUploadPartSize(), is(1234L));
  assertThat(options.isS3ServerSideEncryption(), is(true));
  assertThat(options.getStorageClass(), is(StorageClass.ReducedRedundancy.toString()));
  assertThat(options.getMaxBandwidth(), is(567L));
  assertThat(options.getNumberOfUploadWorkers(), is(89));
  assertThat(options.getMultipartUploadThreshold(), is(123456L));
  assertThat(options.getMaxMaps(), is(78));
  assertThat(options.getCopyStrategy(), is("the-strategy"));
  assertThat(options.getLogPath(), is(new Path("hdfs://path/to/logs/")));
  assertThat(options.getRegion(), is(Regions.US_EAST_1.getName()));
  assertThat(options.isIgnoreFailures(), is(true));
}
 
Example 27
Project: circus-train   File: SnsConfiguration.java   View source code 5 votes vote down vote up
@Bean
AmazonSNSAsyncClient amazonSNS(ListenerConfig config, AWSCredentialsProvider awsCredentialsProvider) {
  AmazonSNSAsyncClient client = new AmazonSNSAsyncClient(awsCredentialsProvider,
      new ClientConfiguration().withRetryPolicy(PredefinedRetryPolicies.getDefaultRetryPolicy()),
      Executors.newSingleThreadScheduledExecutor());
  client.setRegion(Region.getRegion(Regions.fromName(config.getRegion())));
  return client;
}
 
Example 28
Project: circus-train   File: OptionsParserTest.java   View source code 5 votes vote down vote up
@Test
public void regions() {
  for (Regions region : Regions.values()) {
    S3MapReduceCpOptions options = new OptionsParser().parse("--src", "hdfs://localhost:8020/source/first", "--dest",
        "hdfs://localhost:8020/target/", "--credentialsProvider",
        "jceks://[email protected]:8020/security/credentials.jceks", "--region", region.getName());
    assertThat(options.getRegion(), is(region.getName()));
  }
}
 
Example 29
Project: StubbornJava   File: S3Client.java   View source code 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 30
Project: apigateway-generic-java-sdk   File: Main.java   View source code 5 votes vote down vote up
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
    String apiIntputStream = new Scanner(inputStream).useDelimiter("\\A").next();
    JsonNode rootNode = (new ObjectMapper(new JsonFactory())).readTree(apiIntputStream);
    String myApiId = rootNode.path("requestContext").path("apiId").asText();
    if (myApiId.isEmpty()) { myApiId = "TODO"; } // Not called from API Gateway

    final GenericApiGatewayClient client = new GenericApiGatewayClientBuilder()
            .withClientConfiguration(new ClientConfiguration())
            .withCredentials(new EnvironmentVariableCredentialsProvider())
            .withEndpoint("https://" + myApiId + ".execute-api.us-west-2.amazonaws.com") // your API ID
            .withRegion(Region.getRegion(Regions.fromName("us-west-2")))
            .build();

    GenericApiGatewayResponse apiResponse;
    ProxyResponse resp;
    try {
        apiResponse = client.execute(  // throws exception for non-2xx response
                new GenericApiGatewayRequestBuilder()
                        .withHttpMethod(HttpMethodName.GET)
                        .withResourcePath("/Prod/hello").build());

        System.out.println("Response: " + apiResponse.getBody());
        System.out.println("Status: " + apiResponse.getHttpResponse().getStatusCode());

        resp = new ProxyResponse("200", apiResponse.getBody());

    } catch (GenericApiGatewayException e) {
        System.out.println("Client threw exception " + e);
        resp = new ProxyResponse("400", e.getMessage());
    }

    String responseString = new ObjectMapper(new JsonFactory()).writeValueAsString(resp);
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
    writer.write(responseString);
    writer.close();
}
 
Example 31
Project: apigateway-generic-java-sdk   File: GenericApiGatewayClientTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar"));

    mockClient = Mockito.mock(SdkHttpClient.class);
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    ClientConfiguration clientConfig = new ClientConfiguration();

    client = new GenericApiGatewayClientBuilder()
            .withClientConfiguration(clientConfig)
            .withCredentials(credentials)
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withApiKey("12345")
            .withHttpClient(new AmazonHttpClient(clientConfig, mockClient, null))
            .build();
}
 
Example 32
Project: apigateway-generic-java-sdk   File: GenericApiGatewayClientBuilderTest.java   View source code 5 votes vote down vote up
@Test
public void testBuild_happy() throws Exception {
    AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar"));

    GenericApiGatewayClient client = new GenericApiGatewayClientBuilder()
            .withClientConfiguration(new ClientConfiguration())
            .withCredentials(credentials)
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withApiKey("12345")
            .build();

    Assert.assertEquals("Wrong service name","execute-api", client.getServiceNameIntern());
}
 
Example 33
Project: apigateway-generic-java-sdk   File: GenericApiGatewayClientBuilderTest.java   View source code 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testBuild_noEndpoint() throws Exception {
    new GenericApiGatewayClientBuilder()
            .withClientConfiguration(new ClientConfiguration())
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .build();
}
 
Example 34
Project: webcrawler   File: AppConfig.java   View source code 5 votes vote down vote up
@Bean
public AmazonDynamoDBAsync getDynamoDBClient() {

    return AmazonDynamoDBAsyncClientBuilder.standard()
            .withCredentials(new ProfileCredentialsProvider(CREDENTIALS_PROVIDER))
            .withRegion(Regions.AP_SOUTHEAST_2)
            .build();

}
 
Example 35
Project: intellij-idea-plugin-connector-for-aws-lambda   File: ConnectorPresenterImpl.java   View source code 5 votes vote down vote up
@Override
@NotNull
protected Regions getLastSelectedRegion() {
    String lastSelectedRegionName = connectorSettings.getLastSelectedRegionName();
    Regions region = lastSelectedRegionName == null
                        ? DEFAULT_REGION
                        : tryGetRegionBy(lastSelectedRegionName);
    return region != null ? region : DEFAULT_REGION;
}
 
Example 36
Project: webcrawler   File: AppConfig.java   View source code 5 votes vote down vote up
@Bean
public SQSConnectionFactory sqsConnectionFactory() throws JMSException {

    return new SQSConnectionFactory(
            new ProviderConfiguration(),
            AmazonSQSClientBuilder.standard()
                    .withRegion(Regions.AP_SOUTHEAST_2)
                    .withCredentials(new ProfileCredentialsProvider(CREDENTIALS_PROVIDER))
    );
}
 
Example 37
Project: aws-xray-sdk-java   File: TracingHandlerTest.java   View source code 5 votes vote down vote up
@Test
public void testLambdaInvokeSubsegmentContainsFunctionName() {
    // Setup test
    AWSLambda lambda = AWSLambdaClientBuilder.standard().withRequestHandlers(new TracingHandler()).withRegion(Regions.US_EAST_1).withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake"))).build();

    AmazonHttpClient amazonHttpClient = new AmazonHttpClient(new ClientConfiguration());
    ConnectionManagerAwareHttpClient apacheHttpClient = Mockito.mock(ConnectionManagerAwareHttpClient.class);
    HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity responseBody = new BasicHttpEntity();
    responseBody.setContent(new ByteArrayInputStream("null".getBytes(StandardCharsets.UTF_8))); // Lambda returns "null" on successful fn. with no return value
    httpResponse.setEntity(responseBody);

    try {
        Mockito.doReturn(httpResponse).when(apacheHttpClient).execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class));
    } catch (IOException e) { }

    Whitebox.setInternalState(amazonHttpClient, "httpClient", apacheHttpClient);
    Whitebox.setInternalState(lambda, "client", amazonHttpClient);

    // Test logic
    Segment segment = AWSXRay.beginSegment("test");

    InvokeRequest request = new InvokeRequest();
    request.setFunctionName("testFunctionName");
    InvokeResult r = lambda.invoke(request);
    System.out.println(r.getStatusCode());
    System.out.println(r);

    Assert.assertEquals(1, segment.getSubsegments().size());
    Assert.assertEquals("Invoke", segment.getSubsegments().get(0).getAws().get("operation"));
    System.out.println(segment.getSubsegments().get(0).getAws());
    Assert.assertEquals("testFunctionName", segment.getSubsegments().get(0).getAws().get("function_name"));
}
 
Example 38
Project: rxjava2-aws   File: AwsClients.java   View source code 5 votes vote down vote up
public static AmazonSQS createSqsClient(AWSCredentials credentials, ClientConfiguration cc, Regions region) {
    return AmazonSQSClientBuilder //
            .standard() //
            .withCredentials(new AWSStaticCredentialsProvider(credentials)) //
            .withRegion(region) //
            .build();
}
 
Example 39
Project: rxjava2-aws   File: AwsClients.java   View source code 5 votes vote down vote up
public static AmazonS3 createS3Client(AWSCredentials credentials, ClientConfiguration cc, Regions region) {
    return AmazonS3ClientBuilder //
            .standard() //
            .withCredentials(new AWSStaticCredentialsProvider(credentials)) //
            .withRegion(region) //
            .build();
}
 
Example 40
Project: rxjava2-aws   File: AwsClientsTest.java   View source code 5 votes vote down vote up
@Test
public void tests3() {
	AwsClients.createS3Client(new AWSCredentials() {

		@Override
		public String getAWSSecretKey() {
			return "a";
		}

		@Override
		public String getAWSAccessKeyId() {
			return "b";
		}
	}, new ClientConfiguration(), Regions.AP_SOUTHEAST_2);
}