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

项目:apigateway-generic-java-sdk    文件:GenericApiGatewayClientTest.java   
@Test
public void testExecute_noApiKey_noCreds() throws IOException {
    client = new GenericApiGatewayClientBuilder()
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withClientConfiguration(new ClientConfiguration())
            .withHttpClient(new AmazonHttpClient(new ClientConfiguration(), mockClient, null))
            .build();

    GenericApiGatewayResponse response = client.execute(
            new GenericApiGatewayRequestBuilder()
                    .withBody(new ByteArrayInputStream("test request".getBytes()))
                    .withHttpMethod(HttpMethodName.POST)
                    .withResourcePath("/test/orders").build());

    assertEquals("Wrong response body", "test payload", response.getBody());
    assertEquals("Wrong response status", 200, response.getHttpResponse().getStatusCode());

    Mockito.verify(mockClient, times(1)).execute(argThat(new LambdaMatcher<>(
                    x -> (x.getMethod().equals("POST")
                            && x.getFirstHeader("x-api-key") == null
                            && x.getFirstHeader("Authorization") == null
                            && x.getURI().toString().equals("https://foobar.execute-api.us-east-1.amazonaws.com/test/orders")))),
            any(HttpContext.class));
}
项目: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);
    }
}
项目:aem-orchestrator    文件:AwsConfig.java   
@Bean
public Region awsRegion() {
    Region region;
    if(regionString != null && !regionString.isEmpty()) {
        region = RegionUtils.getRegion(regionString);
    } else {
        AwsRegionProvider regionProvider = new DefaultAwsRegionProviderChain();
        region = RegionUtils.getRegion(regionProvider.getRegion());
    }

    if(region == null) {
        throw new BeanInitializationException("Unable to determine AWS region");
    }

    return region;
}
项目:aem-orchestrator    文件:AwsConfig.java   
@Bean
public AmazonCloudWatch amazonCloudWatchClient(final AWSCredentialsProvider awsCredentialsProvider, 
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonCloudWatchClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
项目: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();
}
项目:soundwave    文件:EsInstanceStore.java   
@Override
public Iterator<EsInstance> getRunningInstances(Region region, String[] fields) throws Exception {

  Preconditions.checkNotNull(region);

  //state eq running and in the specificied region
  QueryBuilder queryBuilder = QueryBuilders.boolQuery()
      .must(QueryBuilders.termQuery("state", "running"))
      .must(QueryBuilders.termQuery("region", region.getName().toLowerCase()));

  ScrollableResponse<List<EsInstance>> response = this.retrieveScrollByQuery(queryBuilder,
      fields, BATCHSIZE,
      str -> (EsInstance) insertMapper.readValue(str, getInstanceClass()));

  EsIterator<EsInstance>
      iterator =
      new EsIterator<>(response, r -> scrollNext(r.getContinousToken(),
          str -> (EsInstance) insertMapper.readValue(str, getInstanceClass())));
  return iterator;
}
项目:soundwave    文件:EsInstanceStore.java   
@Override
public Iterator<EsInstance> getRecentlyTerminatedInstances(Region region,
                                                           int days) throws Exception {

  Preconditions.checkNotNull(region);
  Preconditions.checkArgument(days > 0);

  DateTime start = getStartSinceDay(days);

  QueryBuilder queryBuilder = QueryBuilders.boolQuery()
      .must(QueryBuilders.termQuery("region", region.getName().toLowerCase()))
      .must(QueryBuilders.termQuery("state", "terminated"))
      .must(QueryBuilders.rangeQuery("aws_launch_time").gte(start));

  ScrollableResponse<List<EsInstance>> response = this.retrieveScrollByQuery(queryBuilder,
      EsMapper.getIncludeFields(getInstanceClass()), BATCHSIZE,
      str -> (EsInstance) insertMapper.readValue(str, getInstanceClass()));

  EsIterator<EsInstance>
      iterator =
      new EsIterator<>(response, r -> scrollNext(r.getContinousToken(),
          str -> (EsInstance) insertMapper.readValue(str, getInstanceClass())));

  return iterator;
}
项目:ibm-cos-sdk-java    文件:S3RequestEndpointResolver.java   
/**
 * Set the request's endpoint and resource path with the new region provided
 *
 * @param request Request to set endpoint for
 * @param regionString  New region to determine endpoint to hit
 */
public void resolveRequestEndpoint(Request<?> request, String regionString) {
    if (regionString != null) {
        final Region r = RegionUtils.getRegion(regionString);

        if (r == null) {
            throw new SdkClientException("Not able to determine region" +
                    " for " + regionString + ".Please upgrade to a newer " +
                    "version of the SDK");
        }

        endpointBuilder.withRegion(r);
    }
    final URI endpoint = endpointBuilder.getServiceEndpoint();
    if (shouldUseVirtualAddressing(endpoint)) {
        request.setEndpoint(convertToVirtualHostEndpoint(endpoint, bucketName));
        request.setResourcePath(SdkHttpUtils.urlEncode(getHostStyleResourcePath(), true));
    } else {
        request.setEndpoint(endpoint);
        if (bucketName != null) {
            request.setResourcePath(SdkHttpUtils.urlEncode(getPathStyleResourcePath(), true));
        }
    }
}
项目: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 "";
}
项目:Reer    文件:S3Client.java   
private void configureClient(S3RegionalResource s3RegionalResource) {
    Optional<URI> endpoint = s3ConnectionProperties.getEndpoint();
    if (endpoint.isPresent()) {
        amazonS3Client.setEndpoint(endpoint.get().toString());
    } else {
        Optional<Region> region = s3RegionalResource.getRegion();
        if (region.isPresent()) {
            amazonS3Client.setRegion(region.get());
        }
    }
}
项目:aem-orchestrator    文件:AwsConfig.java   
@Bean
public SQSConnection sqsConnection(final AWSCredentialsProvider awsCredentialsProvider,
    final ClientConfiguration awsClientConfig, final Region awsRegion) throws JMSException {

    SQSConnectionFactory connectionFactory = SQSConnectionFactory.builder()
        .withRegion(awsRegion) //Gets region form meta data
        .withAWSCredentialsProvider(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .build();

    return connectionFactory.createConnection();
}
项目:intellij-idea-plugin-connector-for-aws-lambda    文件:ConnectorModel.java   
public List<RegionEntry> getRegions() {
    if(regionEntries != null)
        return regionEntries;

    regionEntries = new ArrayList<>();
    for(Region region : RegionUtils.getRegions()) {
        String description = regionDescriptions.get(region.getName());
        if(description != null)
            regionEntries.add(new RegionEntry(region, description));
    }
    return regionEntries;
}
项目:aem-orchestrator    文件:AwsConfig.java   
@Bean
public AmazonElasticLoadBalancing amazonElbClient(final AWSCredentialsProvider awsCredentialsProvider,
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonElasticLoadBalancingClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
项目:aem-orchestrator    文件:AwsConfig.java   
@Bean
public AmazonCloudFormation amazonCloudFormationClient(final AWSCredentialsProvider awsCredentialsProvider,
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonCloudFormationClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
项目:aem-orchestrator    文件:AwsConfig.java   
@Bean
public AmazonS3 amazonS3Client(final AWSCredentialsProvider awsCredentialsProvider, 
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonS3ClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .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    文件:GenericApiGatewayClient.java   
GenericApiGatewayClient(ClientConfiguration clientConfiguration, String endpoint, Region region,
                        AWSCredentialsProvider credentials, String apiKey, AmazonHttpClient httpClient) {
    super(clientConfiguration);
    setRegion(region);
    setEndpoint(endpoint);
    this.credentials = credentials;
    this.apiKey = apiKey;
    this.signer = new AWS4Signer();
    this.signer.setServiceName(API_GATEWAY_SERVICE_NAME);
    this.signer.setRegionName(region.getName());

    final JsonOperationMetadata metadata = new JsonOperationMetadata().withHasStreamingSuccessResponse(false).withPayloadJson(false);
    final Unmarshaller<GenericApiGatewayResponse, JsonUnmarshallerContext> responseUnmarshaller = in -> new GenericApiGatewayResponse(in.getHttpResponse());
    this.responseHandler = SdkStructuredPlainJsonFactory.SDK_JSON_FACTORY.createResponseHandler(metadata, responseUnmarshaller);
    JsonErrorUnmarshaller defaultErrorUnmarshaller = new JsonErrorUnmarshaller(GenericApiGatewayException.class, null) {
        @Override
        public AmazonServiceException unmarshall(JsonNode jsonContent) throws Exception {
            return new GenericApiGatewayException(jsonContent.toString());
        }
    };
    this.errorResponseHandler = SdkStructuredPlainJsonFactory.SDK_JSON_FACTORY.createErrorResponseHandler(
            Collections.singletonList(defaultErrorUnmarshaller), null);

    if (httpClient != null) {
        super.client = httpClient;
    }
}
项目: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());
}
项目:graylog-plugin-s3    文件:S3SQSClient.java   
public S3SQSClient(Region region, String queueName, String accessKey, String secretKey) {
    ClientConfiguration clientConfiguration = new ClientConfiguration();

    clientConfiguration.setRequestTimeout(5000);
    clientConfiguration.setRetryPolicy(new RetryPolicy(null, null, 3, true));

    if (accessKey.isEmpty() && secretKey.isEmpty()) {
        this.sqs = new AmazonSQSClient(new InstanceProfileCredentialsProvider(), clientConfiguration);
    } else {
        this.sqs = new AmazonSQSClient(new BasicAWSCredentials(accessKey, secretKey), clientConfiguration);
    }
    this.sqs.setRegion(region);

    this.queueName = queueName;
}
项目:graylog-plugin-s3    文件:S3Reader.java   
public S3Reader(Region region, String accessKey, String secretKey) {
    AmazonS3ClientBuilder clientBuilder = AmazonS3ClientBuilder.standard();
    clientBuilder.setRegion(region.getName());

    if (!accessKey.isEmpty() && !secretKey.isEmpty()) {
        clientBuilder.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)));
    }

    this.s3Client = clientBuilder.build();
}
项目:graylog-plugin-s3    文件:S3Subscriber.java   
public S3Subscriber(Region sqsRegion, Region s3Region, String queueName, MessageInput sourceInput, String accessKey, String secretKey, int threadCount) {
    this.sourceInput = sourceInput;

    this.subscriber = new S3SQSClient(
            sqsRegion,
            queueName,
            accessKey,
            secretKey
    );

    this.s3Reader = new S3Reader(s3Region, accessKey, secretKey);
    this.threadCount = threadCount;
    this.executor = new ScheduledThreadPoolExecutor(threadCount, Executors.defaultThreadFactory());
}
项目:soundwave    文件:Ec2InstanceStore.java   
private AmazonEC2Client getClient(Region region) {
  AmazonEC2Client client = regionClientsCache.get(region.getName());
  if (client == null) {
    client = AwsClientFactory.createEC2Client(region);
    regionClientsCache.put(region.getName(), client);
  }
  return client;
}
项目:soundwave    文件:Ec2InstanceStore.java   
@Override
public List<Instance> getInstances(Region region) throws Exception {
  List<Instance> ret = new ArrayList<>();
  List<AvailabilityZone> zones = getAvailabilityZones(region);
  AmazonEC2Client client = getClient(region);
  ExecutorService executor = Executors.newFixedThreadPool(zones.size());
  try {
    List<Callable<List<Instance>>> retrieveFunction = new ArrayList<>();
    for (AvailabilityZone zone : zones) {
      retrieveFunction.add(new Callable<List<Instance>>() {
        @Override
        public List<Instance> call() throws Exception {
          return getInstancesForZone(zone, client);
        }
      });
    }

    List<Future<List<Instance>>> futures = executor.invokeAll(retrieveFunction);
    for (Future<List<Instance>> future : futures) {
      ret.addAll(future.get());
    }

  } finally {
    executor.shutdown();
  }

  return ret;
}
项目:soundwave    文件:Ec2InstanceStore.java   
@Override
public List<AvailabilityZone> getAvailabilityZones(Region region) throws Exception {
  OperationStats op = new OperationStats("ec2InstanceStore", "getAvailabilityZones");
  try {
    DescribeAvailabilityZonesRequest request = new DescribeAvailabilityZonesRequest();
    DescribeAvailabilityZonesResult result = getClient(region).describeAvailabilityZones();
    List<AvailabilityZone> ret = result.getAvailabilityZones();
    op.succeed();
    return ret;
  } catch (Exception ex) {
    op.failed();
    throw ex;
  }
}
项目:soundwave    文件:Ec2InstanceStore.java   
/**
 * Get Reserved instances for a given region
 * @param region
 * @return
 */
@Override
public List<ReservedInstances> getReservedInstances(Region region) {

  OperationStats op = new OperationStats("ec2InstanceStore", "getReservedInstances");
  try {

    AmazonEC2Client client = getClient(region);
    DescribeReservedInstancesRequest request = new DescribeReservedInstancesRequest()
        .withSdkClientExecutionTimeout(
            600 * 1000) //10 minutes time out for total execution including retries
        .withSdkRequestTimeout(300 * 1000); //5 minutes time out for a single request

    DescribeReservedInstancesResult result = client.describeReservedInstances(request);

    op.succeed();
    return result.getReservedInstances();

  } catch (Exception e) {

    op.failed();
    logger.error(ExceptionUtils.getRootCauseMessage(e));
    throw e;
  }


}
项目:soundwave    文件:Ec2InstanceStore.java   
/**
 * This function is a wrapper to the ec2 describeInstanceStatus function.
 *
 * @param region
 * @return List of InstanceStatus
 */
public List<InstanceStatus> describeInstancesStatusAsync(Region region) throws Exception {

  Preconditions.checkNotNull(region);
  List<InstanceStatus> statusList = new ArrayList<>();
  List<AvailabilityZone> zones = getAvailabilityZones(region);
  AmazonEC2Client client = getClient(region);
  ExecutorService executor = Executors.newFixedThreadPool(zones.size());
  OperationStats op = new OperationStats("ec2InstanceStore", "describeInstancesStatusAsync");
  try {
    List<Callable<List<InstanceStatus>>> retrieveFunction = new ArrayList<>(zones.size());
    for (AvailabilityZone zone : zones) {
      retrieveFunction.add(new Callable<List<InstanceStatus>>() {
        @Override
        public List<InstanceStatus> call() throws Exception {
          return getInstancesStatusByZone(zone, client);
        }
      });
    }

    List<Future<List<InstanceStatus>>> futures = executor.invokeAll(retrieveFunction);
    for (Future<List<InstanceStatus>> future : futures) {
      statusList.addAll(future.get());
    }
    op.succeed();
  } catch (Exception ex) {
    op.failed();
    throw ex;
  } finally {
    executor.shutdown();
  }

  return statusList;
}
项目:soundwave    文件:EsInstanceStore.java   
@Override
public Iterator<EsAwsStatus> getRunningAndTerminatedAwsStatus(Region region, int days)
    throws Exception {
  Preconditions.checkNotNull(region);
  Preconditions.checkArgument(days > 0);

  DateTime start = getStartSinceDay(days);

  //state eq running or terminated after the start time.
  QueryBuilder queryBuilder = QueryBuilders.boolQuery()
      .should(QueryBuilders.termQuery("state", "running"))
      .must(QueryBuilders.termQuery("region", region.getName().toLowerCase()))
      .should(QueryBuilders.boolQuery()
          .must(QueryBuilders.termQuery("state", "terminated"))
          .must(QueryBuilders.termQuery("region", region.getName().toLowerCase()))
          .must(QueryBuilders.rangeQuery("aws_launch_time").gte(start)))
      .minimumNumberShouldMatch(1);

  ScrollableResponse<List<EsAwsStatus>> response =
      this.retrieveScrollByQuery(queryBuilder,
          EsMapper.getIncludeFields(EsAwsStatus.class, this.getClass()), BATCHSIZE,
          str -> updateMapper.readValue(str, EsAwsStatus.class));

  EsIterator<EsAwsStatus> iterator =
      new EsIterator<>(response, r -> scrollNext(r.getContinousToken(),
          str -> updateMapper.readValue(str, EsAwsStatus.class)));

  return iterator;
}
项目:soundwave    文件:AwsInstanceStatusJob.java   
public AwsInstanceStatusJob(CloudInstanceStore cloudInstanceStore,
                            CmdbInstanceStore cmdbInstanceStore,
                            Region region) {

  Preconditions.checkNotNull(cmdbInstanceStore);
  Preconditions.checkNotNull(cloudInstanceStore);
  Preconditions.checkNotNull(region);

  this.cmdbInstanceStore = cmdbInstanceStore;
  this.cloudInstanceStore = cloudInstanceStore;
  this.region = region;
  this.total = 0;
  this.badInstanceCount = 0;
}
项目:soundwave    文件:DailyInstanceCountPerTypeJob.java   
public DailyInstanceCountPerTypeJob(CloudInstanceStore cloudInstanceStore,
                                    EsInstanceCounterStore instanceCounterStore,
                                    Region region) {

  Preconditions.checkNotNull(cloudInstanceStore);
  Preconditions.checkNotNull(instanceCounterStore);
  Preconditions.checkNotNull(region);

  this.cloudInstanceStore = cloudInstanceStore;
  this.instanceCounterStore = instanceCounterStore;
  this.region = region;
}
项目:soundwave    文件:ReconcileWithAwsJob.java   
public ReconcileWithAwsJob(CloudInstanceStore cloudInstanceStore, CmdbInstanceStore cmdbStore,
                           Region region) {
  Preconditions.checkNotNull(cloudInstanceStore);
  Preconditions.checkNotNull(cmdbStore);
  this.cloudInstanceStore = cloudInstanceStore;
  this.cmdbStore = cmdbStore;
  this.region = region;
}
项目:CloudPrime    文件:DynamoEntry.java   
public static DynamoEntry getFromMSS(String parameter)
{
    dynamoDB = new AmazonDynamoDBClient(new ProfileCredentialsProvider().getCredentials());
    dynamoDB.setRegion(Region.getRegion(Regions.EU_WEST_1));

    HashMap<String, Condition> keyConditions = new HashMap<String, Condition>();
    keyConditions.put("Parameter", new Condition().withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue(parameter)));

    QueryRequest queryRequest = new QueryRequest();
    queryRequest.setKeyConditions(keyConditions);
    queryRequest.withTableName("MSS");

    QueryResult result = dynamoDB.query(queryRequest);
    //se houver um pedido ja tratado no MSS getCount > 0, caso contrario nao existe
    if(result.getCount() == 0)
        return null;
    else
    {
        //vamos buscar o rank
        Map<String, AttributeValue> queryResult = result.getItems().get(0);
        String rank = "";
        boolean runningState = false;

        for (Map.Entry<String, AttributeValue> entry  : queryResult.entrySet()) 
        {
            if(entry.getKey().equals("Rank"))
                rank = entry.getValue().getN();
            else if(entry.getKey().equals("Running"))
                runningState = entry.getValue().getBOOL();
        }
        DynamoEntry rankResult = new DynamoEntry(new BigInteger(rank), runningState);           
        return rankResult;
    }
}
项目:CloudPrime    文件:InstTool.java   
@Override
public void run() {
    try {
        FileInputStream logFile = new FileInputStream("logIntermedio.txt");
        BufferedReader bufReader = new BufferedReader(new InputStreamReader(logFile));

        String line;

        while ((line = bufReader.readLine()) != null) {
            String[] parts = line.split(":");

            if (parts[0].equals(threadID)) {
                AmazonDynamoDBClient dynamoDB = new AmazonDynamoDBClient(new ProfileCredentialsProvider());
                dynamoDB.setRegion(Region.getRegion(Regions.EU_WEST_1));

                String[] parameterParts = parts[1].split("=");
                String parameter = parameterParts[1];

                QueryResult result = getEntryDynamo(parameter, dynamoDB);

                if (result.getCount() == 0) // se a query nao retornar nada significa que nao temos nada no dynamo sobre este parametro
                {
                    putDynamo(parameter, metricas.i_count, metricas.b_count, metricas.fieldLoadCount,
                            metricas.loadCount, dynamoDB, true, threadID, null);
                } else { //caso contrario vamos buscar as metricas que temos para atualiza las
                    Map<String, AttributeValue> queryResult = result.getItems().get(0);
                    // runningValue fica a true se Running estiver a true, se ja estiver a false entao ja temos as metricas finais para este parametro portanto nao atualizamos o dynamo
                    boolean runningValue = queryResult.values().contains(new AttributeValue().withBOOL(true));
                    if (runningValue) {
                        putDynamo(parameter, metricas.i_count, metricas.b_count, metricas.fieldLoadCount,
                                metricas.loadCount, dynamoDB, true, threadID, result);
                    }
                }
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:aws-codecommit-trigger-plugin    文件:SQSTriggerQueue.java   
public ListBoxModel doFillRegionItems() {
    ListBoxModel items = new ListBoxModel();
    items.add("", "");
    for (Regions region : Regions.values()) {
        Region r = Region.getRegion(region);
        if (r.isServiceSupported(AmazonSQS.ENDPOINT_PREFIX) && r.isServiceSupported("codecommit")) {
            items.add(region.getName(), region.name());
        }
    }
    return items;
}
项目:strongbox    文件:KMSEncryptor.java   
protected KmsMasterKeyProvider getProvider() {
    if (!prov.isPresent()) {
        Region region = RegionUtils.getRegion(groupIdentifier.region.getName());
        prov = Optional.of(new KmsMasterKeyProvider(awsCredentials, region, transformAndVerifyOrThrow(clientConfiguration), getKeyArn()));
    }
    return prov.get();
}
项目:ibm-cos-sdk-java    文件:PartitionMetadataProvider.java   
@Override
public List<Region> getRegions() {
    final List<Region> regions = new ArrayList<Region>();

    for (Partition p : partitionMap.values()) {
        for (Map.Entry<String, com.amazonaws.partitions.model.Region>
                entry : p.getRegions().entrySet()) {
            regions.add(new Region(new PartitionRegionImpl(entry.getKey(),
                    p)));
        }
    }
    return Collections.unmodifiableList(regions);
}
项目:ibm-cos-sdk-java    文件:PartitionMetadataProvider.java   
private Region createNewRegion(String regionName) {
    for (Partition p : partitionMap.values()) {
        if (p.hasRegion(regionName)) {
            return cacheRegion(new PartitionRegionImpl(regionName, p));
        }
    }
    return null;
}
项目:ibm-cos-sdk-java    文件:PartitionMetadataProvider.java   
@Override
public List<Region> getRegionsForService(String serviceName) {
    final List<Region> allRegions = getRegions();
    final List<Region> serviceSupportedRegions = new ArrayList<Region>();

    for (Region r : allRegions) {
        if (r.isServiceSupported(serviceName)) {
            serviceSupportedRegions.add(r);
        }
    }
    return serviceSupportedRegions;
}
项目:ibm-cos-sdk-java    文件:DefaultServiceEndpointBuilder.java   
public DefaultServiceEndpointBuilder withRegion(Region region) {
    if (region == null) {
        throw new IllegalArgumentException("Region cannot be null");
    }
    this.region = region;
    return this;
}
项目:ibm-cos-sdk-java    文件:DualstackEndpointBuilder.java   
@Override
public DualstackEndpointBuilder withRegion(Region region) {
    if (region == null) {
        throw new IllegalArgumentException("Region cannot be null");
    }
    this.region = region;
    return this;
}