Java Code Examples for com.amazonaws.regions.Region

The following are top voted examples for showing how to use com.amazonaws.regions.Region. 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: apigateway-generic-java-sdk   File: GenericApiGatewayClientTest.java   View source code 10 votes vote down vote up
@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));
}
 
Example 2
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 3
Project: aem-orchestrator   File: AwsConfig.java   View source code 6 votes vote down vote up
@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;
}
 
Example 4
Project: aem-orchestrator   File: AwsConfig.java   View source code 6 votes vote down vote up
@Bean
public AmazonCloudWatch amazonCloudWatchClient(final AWSCredentialsProvider awsCredentialsProvider, 
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonCloudWatchClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
 
Example 5
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 6
Project: soundwave   File: EsInstanceStore.java   View source code 6 votes vote down vote up
@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;
}
 
Example 7
Project: soundwave   File: EsInstanceStore.java   View source code 6 votes vote down vote up
@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;
}
 
Example 8
Project: ibm-cos-sdk-java   File: S3RequestEndpointResolver.java   View source code 6 votes vote down vote up
/**
 * 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));
        }
    }
}
 
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: Reer   File: S3Client.java   View source code 5 votes vote down vote up
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());
        }
    }
}
 
Example 11
Project: aem-orchestrator   File: AwsConfig.java   View source code 5 votes vote down vote up
@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();
}
 
Example 12
Project: intellij-idea-plugin-connector-for-aws-lambda   File: ConnectorModel.java   View source code 5 votes vote down vote up
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;
}
 
Example 13
Project: aem-orchestrator   File: AwsConfig.java   View source code 5 votes vote down vote up
@Bean
public AmazonElasticLoadBalancing amazonElbClient(final AWSCredentialsProvider awsCredentialsProvider,
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonElasticLoadBalancingClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
 
Example 14
Project: aem-orchestrator   File: AwsConfig.java   View source code 5 votes vote down vote up
@Bean
public AmazonCloudFormation amazonCloudFormationClient(final AWSCredentialsProvider awsCredentialsProvider,
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonCloudFormationClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
 
Example 15
Project: aem-orchestrator   File: AwsConfig.java   View source code 5 votes vote down vote up
@Bean
public AmazonS3 amazonS3Client(final AWSCredentialsProvider awsCredentialsProvider, 
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonS3ClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
 
Example 16
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 17
Project: apigateway-generic-java-sdk   File: GenericApiGatewayClient.java   View source code 5 votes vote down vote up
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;
    }
}
 
Example 18
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 19
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 20
Project: graylog-plugin-s3   File: S3SQSClient.java   View source code 5 votes vote down vote up
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;
}
 
Example 21
Project: graylog-plugin-s3   File: S3Reader.java   View source code 5 votes vote down vote up
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();
}
 
Example 22
Project: graylog-plugin-s3   File: S3Subscriber.java   View source code 5 votes vote down vote up
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());
}
 
Example 23
Project: soundwave   File: Ec2InstanceStore.java   View source code 5 votes vote down vote up
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;
}
 
Example 24
Project: soundwave   File: Ec2InstanceStore.java   View source code 5 votes vote down vote up
@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;
}
 
Example 25
Project: soundwave   File: Ec2InstanceStore.java   View source code 5 votes vote down vote up
@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;
  }
}
 
Example 26
Project: soundwave   File: Ec2InstanceStore.java   View source code 5 votes vote down vote up
/**
 * 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;
  }


}
 
Example 27
Project: soundwave   File: Ec2InstanceStore.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 28
Project: soundwave   File: EsInstanceStore.java   View source code 5 votes vote down vote up
@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;
}
 
Example 29
Project: soundwave   File: AwsInstanceStatusJob.java   View source code 5 votes vote down vote up
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;
}
 
Example 30
Project: soundwave   File: DailyInstanceCountPerTypeJob.java   View source code 5 votes vote down vote up
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;
}
 
Example 31
Project: soundwave   File: ReconcileWithAwsJob.java   View source code 5 votes vote down vote up
public ReconcileWithAwsJob(CloudInstanceStore cloudInstanceStore, CmdbInstanceStore cmdbStore,
                           Region region) {
  Preconditions.checkNotNull(cloudInstanceStore);
  Preconditions.checkNotNull(cmdbStore);
  this.cloudInstanceStore = cloudInstanceStore;
  this.cmdbStore = cmdbStore;
  this.region = region;
}
 
Example 32
Project: CloudPrime   File: DynamoEntry.java   View source code 5 votes vote down vote up
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;
	}
}
 
Example 33
Project: CloudPrime   File: InstTool.java   View source code 5 votes vote down vote up
@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();
	}
}
 
Example 34
Project: aws-codecommit-trigger-plugin   File: SQSTriggerQueue.java   View source code 5 votes vote down vote up
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;
}
 
Example 35
Project: strongbox   File: KMSEncryptor.java   View source code 5 votes vote down vote up
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();
}
 
Example 36
Project: ibm-cos-sdk-java   File: PartitionMetadataProvider.java   View source code 5 votes vote down vote up
@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);
}
 
Example 37
Project: ibm-cos-sdk-java   File: PartitionMetadataProvider.java   View source code 5 votes vote down vote up
private Region createNewRegion(String regionName) {
    for (Partition p : partitionMap.values()) {
        if (p.hasRegion(regionName)) {
            return cacheRegion(new PartitionRegionImpl(regionName, p));
        }
    }
    return null;
}
 
Example 38
Project: ibm-cos-sdk-java   File: PartitionMetadataProvider.java   View source code 5 votes vote down vote up
@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;
}
 
Example 39
Project: ibm-cos-sdk-java   File: DefaultServiceEndpointBuilder.java   View source code 5 votes vote down vote up
public DefaultServiceEndpointBuilder withRegion(Region region) {
    if (region == null) {
        throw new IllegalArgumentException("Region cannot be null");
    }
    this.region = region;
    return this;
}
 
Example 40
Project: ibm-cos-sdk-java   File: DualstackEndpointBuilder.java   View source code 5 votes vote down vote up
@Override
public DualstackEndpointBuilder withRegion(Region region) {
    if (region == null) {
        throw new IllegalArgumentException("Region cannot be null");
    }
    this.region = region;
    return this;
}