com.amazonaws.regions.DefaultAwsRegionProviderChain Java Examples

The following examples show how to use com.amazonaws.regions.DefaultAwsRegionProviderChain. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZipkinElasticsearchAwsStorageModule.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
@Bean String region(@Value("${zipkin.storage.elasticsearch.hosts:}") String hosts,
    ZipkinElasticsearchAwsStorageProperties aws) {
  hosts = emptyToNull(hosts);
  String domain = aws.getDomain();
  if (hosts != null && domain != null) {
    log.warning(format(
        "Expected exactly one of hosts or domain: instead saw hosts '%s' and domain '%s'."
            + " Ignoring hosts and proceeding to look for domain. Either unset ES_HOSTS or "
            + "ES_AWS_DOMAIN to suppress this message.",
        hosts, domain));
  }

  if (aws.getRegion() != null) {
    return aws.getRegion();
  } else if (domain != null) {
    return new DefaultAwsRegionProviderChain().getRegion();
  } else if (hosts != null) {
    String awsRegion = regionFromAwsUrls(hosts);
    if (awsRegion == null) throw new IllegalArgumentException("Couldn't find region in " + hosts);
    return awsRegion;
  }
  throw new AssertionError(AwsMagic.class.getName() + " should ensure this line isn't reached");
}
 
Example #2
Source File: PutObject.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static PutObjectResult putObject(String containerName, String filePath, InputStream body) throws IOException {
    final String endpoint = getContainerEndpoint(containerName);
    if (endpoint == null || endpoint.isEmpty()) {
        System.err.println("Could not determine container endpoint!");
        System.exit(1);
    }
    final String region = new DefaultAwsRegionProviderChain().getRegion();
    final EndpointConfiguration endpointConfig = new EndpointConfiguration(endpoint, region);

    final AWSMediaStoreData mediastoredata = AWSMediaStoreDataClientBuilder
        .standard()
        .withEndpointConfiguration(endpointConfig)
        .build();
    final PutObjectRequest request = new PutObjectRequest()
        .withContentType("application/octet-stream")
        .withBody(body)
        .withPath(filePath);

    try {
        return mediastoredata.putObject(request);
    } catch (AWSMediaStoreException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }
    return null;
}
 
Example #3
Source File: CustomRegionProviderChain.java    From strongbox with Apache License 2.0 5 votes vote down vote up
private Optional<Region> getRegionFromMetadata() {
    try {
        Region resolvedRegion = null;
        if (EC2MetadataUtils.getInstanceInfo() != null) {
            if (EC2MetadataUtils.getInstanceInfo().getRegion() != null) {
                resolvedRegion = Region.fromName(EC2MetadataUtils.getInstanceInfo().getRegion());
            } else { // fallback to provider chain if region is not exposed
                resolvedRegion = Region.fromName(new DefaultAwsRegionProviderChain().getRegion());
            }
        }
        return Optional.ofNullable(resolvedRegion);
    } catch (SdkClientException e) {
        return Optional.empty();
    }
}
 
Example #4
Source File: AmazonS3Factory.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private String defaultRegion() {
  try {
    return new DefaultAwsRegionProviderChain().getRegion();
  }
  catch (SdkClientException e) {
    String region = Regions.DEFAULT_REGION.getName();
    log.warn("Default AWS region not configured, using {}", region, e);
    return region;
  }
}
 
Example #5
Source File: AwsAutoConfiguration.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Get an AWS region provider instance. The rules for this basically follow what Spring Cloud AWS does but uses
 * the interface from the AWS SDK instead and provides a sensible default.
 * <p>
 * See: <a href="https://tinyurl.com/y9edl6yr">Spring Cloud AWS Region Documentation</a>
 *
 * @param awsRegionProperties The cloud.aws.region.* properties
 * @return A region provider based on whether static was set by user, else auto, else default of us-east-1
 */
@Bean
@ConditionalOnMissingBean(AwsRegionProvider.class)
public AwsRegionProvider awsRegionProvider(final AwsRegionProperties awsRegionProperties) {
    final String staticRegion = awsRegionProperties.getStatic();
    if (StringUtils.isNotBlank(staticRegion)) {
        // Make sure we have a valid region. Will throw runtime exception if not.
        final Regions region = Regions.fromName(staticRegion);
        return new AwsRegionProvider() {
            /**
             * Always return the static configured region.
             *
             * {@inheritDoc}
             */
            @Override
            public String getRegion() throws SdkClientException {
                return region.getName();
            }
        };
    } else if (awsRegionProperties.isAuto()) {
        return new DefaultAwsRegionProviderChain();
    } else {
        // Sensible default
        return new AwsRegionProvider() {
            /**
             * Always default to us-east-1.
             *
             * {@inheritDoc}
             */
            @Override
            public String getRegion() throws SdkClientException {
                return Regions.US_EAST_1.getName();
            }
        };
    }
}
 
Example #6
Source File: Sqs.java    From sqs-exporter with Apache License 2.0 4 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
	List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();

	try {

		if (sqs == null) {
			String region = new DefaultAwsRegionProviderChain().getRegion();
			sqs = AmazonSQSClientBuilder
							.standard()
							.withRegion(region)
						.build();
			logger.info("AmazonSQS client is connected to region: ({})", region);
		}

		List<String> queueUrls;

		// check for manually-specified queue name filters
		String queueUrlsFromEnv = System.getenv("SQS_QUEUE_URLS");
		String queueNames = System.getenv("SQS_QUEUE_NAMES");
		String queueNamePrefix = System.getenv("SQS_QUEUE_NAME_PREFIX");
		if (queueUrlsFromEnv != null) {
			String[] urls = queueUrlsFromEnv.split(",");
			queueUrls = new ArrayList<String>();
			for(String url : urls) {
				queueUrls.add(url);
			}
		} else if (queueNames != null) {
		    // find the URLs for the named queues
		    String[] names = queueNames.split(",");
		    queueUrls = new ArrayList<String>();
		    for(String name : names) {
			queueUrls.add(sqs.getQueueUrl(name).getQueueUrl());
		    }
		} else {
		    // get URLs for all queues visible to this account (with prefix if specified)
		    ListQueuesResult queues = sqs.listQueues(queueNamePrefix); //If null is passed in the whole unfiltered list is returned
		    queueUrls = queues.getQueueUrls();
		}

		for (String qUrl : queueUrls) {
			String[] tokens = qUrl.split("\\/");
			String queueName = tokens[tokens.length - 1];

			GetQueueAttributesResult attr = sqs.getQueueAttributes(qUrl, attributeNames);
			Map<String, String> qAttributes = attr.getAttributes();

			for (String key : qAttributes.keySet()) {
				GaugeMetricFamily labeledGauge = new GaugeMetricFamily(
						String.format("sqs_%s", key.toLowerCase().trim()),
						attributeDescriptions.get(key),
						Arrays.asList("queue"));
				
				labeledGauge.addMetric(Arrays.asList(queueName),
						Double.valueOf(qAttributes.get(key)));
				
				mfs.add(labeledGauge);
			}
		}

	} catch (AmazonClientException e) {
		logger.error(e.getMessage());
		if (sqs != null)
			sqs.shutdown();
		sqs = null; // force reconnect
	}

	return mfs;
}
 
Example #7
Source File: AAWSTest.java    From aws-s3-virusscan with Apache License 2.0 4 votes vote down vote up
protected final String getRegion() {
    return new DefaultAwsRegionProviderChain().getRegion();
}
 
Example #8
Source File: ListItems.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args)
{
    final String USAGE = "\n" +
        "To run this example, supply the name of a container and an optional path!\n" +
        "\n" +
        "Ex: ListItems <container-name> [path]\n";

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

    final String containerName = args[0];
    String path = "";
    if (args.length > 1) {
        path = args[1];
    }

    System.out.format("Objects in MediaStore container %s, path '%s':\n", containerName, path);

    final String endpoint = getContainerEndpoint(containerName);
    if (endpoint == null || endpoint.isEmpty()) {
        System.err.println("Could not determine container endpoint!");
        System.exit(1);
    }

    final String region = new DefaultAwsRegionProviderChain().getRegion();
    final EndpointConfiguration endpointConfig = new EndpointConfiguration(endpoint, region);

    final AWSMediaStoreData mediastoredata = AWSMediaStoreDataClientBuilder
        .standard()
        .withEndpointConfiguration(endpointConfig)
        .build();
    final ListItemsRequest request = new ListItemsRequest()
        .withPath(path);

    ListItemsResult result = mediastoredata.listItems(request);
    List<Item> items = result.getItems();
    for (Item i: items) {
        System.out.printf("* (%s)\t%s\n", i.getType(), i.getName());
    }
}
 
Example #9
Source File: AAWSTest.java    From aws-cf-templates with Apache License 2.0 4 votes vote down vote up
protected final String getRegion() {
    return new DefaultAwsRegionProviderChain().getRegion();
}