Java 类com.amazonaws.regions.Regions 实例源码

项目:cyberduck    文件:AmazonIdentityConfiguration.java   
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();
}
项目:alexa-skill-java    文件:DBUtil.java   
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;
}
项目:Reer    文件:S3RegionalResource.java   
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);
    }
}
项目:intellij-idea-plugin-connector-for-aws-lambda    文件:ConnectorPresenterImpl.java   
@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();
}
项目:log4j-aws-appenders    文件:AbstractLogWriter.java   
/**
 *  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;
}
项目:circus-train    文件:S3MapReduceCpOptionsParserTest.java   
@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);
}
项目:circus-train    文件:S3MapReduceCpOptionsParserTest.java   
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));
}
项目:full-javaee-app    文件:S3Object.java   
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 "";
}
项目:graylog-plugin-s3    文件:S3Transport.java   
@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();
}
项目:intellij-idea-plugin-connector-for-aws-lambda    文件:ConnectorViewFactory.java   
@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;
    }
}
项目:spring-cloud-stream-binder-aws-kinesis    文件:LocalKinesisResource.java   
@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();
}
项目:aws-codecommit-trigger-plugin    文件:SQSFactoryImpl.java   
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;
}
项目:strongbox    文件:RegionResolver.java   
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();
    }
}
项目:generator-jhipster-storage    文件:_StorageConfiguration.java   
/**
 * 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();
}
项目:strongbox    文件:IntegrationTestHelper.java   
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);
        }
    }
}
项目:ibm-cos-sdk-java    文件:AwsClientBuilderTest.java   
/**
 * 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());
}
项目:intellij-idea-plugin-connector-for-aws-lambda    文件:ConnectorPresenterImpl.java   
private Regions tryGetRegionBy(String regionName) {
    for (Regions region : Regions.values()){
        if(region.getName().equals(regionName)){
            return region;
        }
    }
    return null;
}
项目:mm-system-2017    文件:ClientDownloadFile.java   
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;
    }
项目:amazon-kinesis-video-streams-parser-library    文件:KinesisVideoExample.java   
@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);
}
项目:intellij-idea-plugin-connector-for-aws-lambda    文件:ConnectorModel.java   
public ConnectorModel(Regions region, String profileName) {

        ProfileCredentialsProvider profileCredentialsProvider = new ProfileCredentialsProvider(profileName);

        awsLambdaClient = AWSLambdaClientBuilder.standard()
                .withRegion(region)
                .withCredentials(profileCredentialsProvider)
                .build();
    }
项目:intellij-idea-plugin-connector-for-aws-lambda    文件:ConnectorPresenterImpl.java   
@Override
public void setRegion(RegionEntry regionEntry) {
    Regions region = tryGetRegionBy(regionEntry.getName());
    if(region == null) {
        return;
    }
    setRegionAndProfile(region, connectorSettings.getLastSelectedCredentialProfile());
}
项目:secrets-locker    文件:KmsEncryptionService.java   
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);
    }
项目:amazon-kinesis-video-streams-parser-library    文件:PutMediaWorker.java   
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();
}
项目:jenkins-aws-bucket-credentials    文件:AwsKmsClientBuilder.java   
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;
}
项目:intellij-idea-plugin-connector-for-aws-lambda    文件:ConnectorViewFactory.java   
@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);
    }
}
项目:circus-train    文件:S3MapReduceCpCopierTest.java   
@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));
}
项目:circus-train    文件:SnsConfiguration.java   
@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;
}
项目:StubbornJava    文件:S3Client.java   
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());
}
项目:apigateway-generic-java-sdk    文件:Main.java   
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();
}
项目:apigateway-generic-java-sdk    文件:GenericApiGatewayClientTest.java   
@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();
}
项目:apigateway-generic-java-sdk    文件:GenericApiGatewayClientBuilderTest.java   
@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());
}
项目:apigateway-generic-java-sdk    文件:GenericApiGatewayClientBuilderTest.java   
@Test(expected = IllegalArgumentException.class)
public void testBuild_noEndpoint() throws Exception {
    new GenericApiGatewayClientBuilder()
            .withClientConfiguration(new ClientConfiguration())
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .build();
}
项目:webcrawler    文件:AppConfig.java   
@Bean
public AmazonDynamoDBAsync getDynamoDBClient() {

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

}
项目:intellij-idea-plugin-connector-for-aws-lambda    文件:ConnectorPresenterImpl.java   
@Override
@NotNull
protected Regions getLastSelectedRegion() {
    String lastSelectedRegionName = connectorSettings.getLastSelectedRegionName();
    Regions region = lastSelectedRegionName == null
                        ? DEFAULT_REGION
                        : tryGetRegionBy(lastSelectedRegionName);
    return region != null ? region : DEFAULT_REGION;
}
项目:webcrawler    文件:AppConfig.java   
@Bean
public SQSConnectionFactory sqsConnectionFactory() throws JMSException {

    return new SQSConnectionFactory(
            new ProviderConfiguration(),
            AmazonSQSClientBuilder.standard()
                    .withRegion(Regions.AP_SOUTHEAST_2)
                    .withCredentials(new ProfileCredentialsProvider(CREDENTIALS_PROVIDER))
    );
}
项目:aws-xray-sdk-java    文件:TracingHandlerTest.java   
@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"));
}
项目:rxjava2-aws    文件:AwsClients.java   
public static AmazonSQS createSqsClient(AWSCredentials credentials, ClientConfiguration cc, Regions region) {
    return AmazonSQSClientBuilder //
            .standard() //
            .withCredentials(new AWSStaticCredentialsProvider(credentials)) //
            .withRegion(region) //
            .build();
}
项目:rxjava2-aws    文件:AwsClients.java   
public static AmazonS3 createS3Client(AWSCredentials credentials, ClientConfiguration cc, Regions region) {
    return AmazonS3ClientBuilder //
            .standard() //
            .withCredentials(new AWSStaticCredentialsProvider(credentials)) //
            .withRegion(region) //
            .build();
}
项目:rxjava2-aws    文件:AwsClientsTest.java   
@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);
}