Java Code Examples for com.amazonaws.regions.Regions#fromName()

The following examples show how to use com.amazonaws.regions.Regions#fromName() . These examples are extracted from open source projects. 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
public static AmazonS3 getS3Client(final String region, final String roleArn) {
    final Regions awsRegion = StringUtils.isNullOrEmpty(region) ? Regions.US_EAST_1 : Regions.fromName(region);

    if (StringUtils.isNullOrEmpty(roleArn)) {
        return AmazonS3ClientBuilder.standard().withRegion(awsRegion).build();
    } else {
        final AssumeRoleRequest assumeRole = new AssumeRoleRequest().withRoleArn(roleArn).withRoleSessionName("io-klerch-mp3-converter");

        final AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder.standard().withRegion(awsRegion).build();
        final Credentials credentials = sts.assumeRole(assumeRole).getCredentials();

        final BasicSessionCredentials sessionCredentials = new BasicSessionCredentials(
                credentials.getAccessKeyId(),
                credentials.getSecretAccessKey(),
                credentials.getSessionToken());

        return AmazonS3ClientBuilder.standard().withRegion(awsRegion).withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build();
    }
}
 
Example 2
Source Project: digdag   File: Aws.java    License: Apache License 2.0 6 votes vote down vote up
static void configureServiceClient(AmazonWebServiceClient client, Optional<String> endpoint, Optional<String> regionName)
{
    // Configure endpoint or region. Endpoint takes precedence over region.
    if (endpoint.isPresent()) {
        client.setEndpoint(endpoint.get());
    }
    else if (regionName.isPresent()) {
        Regions region;
        try {
            region = Regions.fromName(regionName.get());
        }
        catch (IllegalArgumentException e) {
            throw new ConfigException("Illegal AWS region: " + regionName.get());
        }
        client.setRegion(Region.getRegion(region));
    }
}
 
Example 3
/**
 * Builds a new S3 client based on the information from the
 * {@link AmazonS3Exception}. Extracts from the exception's additional details the
 * region and endpoint of the bucket to be redirected to.
 *
 * Extracting the region from the exception is needed because the US S3 buckets
 * don't always return an endpoint that includes the region and
 * {@link AmazonS3ClientFactory} will default to us-west-2 if the hostname of the
 * endpoint is "s3.amazonaws.com". The us-east-1 bucket is quite likely to return
 * the "s3.amazonaws.com" endpoint.
 */
private AmazonS3 buildAmazonS3ForRedirectLocation(AmazonS3 prototype,
		AmazonS3Exception e) {
	try {
		Regions redirectRegion;
		try {
			redirectRegion = Regions.fromName(
					e.getAdditionalDetails().get("x-amz-bucket-region"));
		}
		catch (IllegalArgumentException iae) {
			redirectRegion = null;
		}

		return this.amazonS3ClientFactory.createClientForEndpointUrl(prototype,
				"https://" + e.getAdditionalDetails().get("Endpoint"),
				redirectRegion);
	}
	catch (Exception ex) {
		LOGGER.error("Error getting new Amazon S3 for redirect", ex);
		throw new RuntimeException(e);
	}
}
 
Example 4
Source Project: Flink-CEPplus   File: AWSUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether or not a region ID is valid.
 *
 * @param region The AWS region ID to check
 * @return true if the supplied region ID is valid, false otherwise
 */
public static boolean isValidRegion(String region) {
	try {
		Regions.fromName(region.toLowerCase());
	} catch (IllegalArgumentException e) {
		return false;
	}
	return true;
}
 
Example 5
Source Project: hypergraphql   File: S3Service.java    License: Apache License 2.0 5 votes vote down vote up
Regions extractRegion(final URI uri) {

        final String regionString = uri.getHost().split("\\.")[0];
        switch(regionString.toUpperCase()) {

            case ("S3"):
                return Regions.US_EAST_1;
            default:
                final String regionPart = regionString.substring(regionString.indexOf("-") + 1);
                return Regions.fromName(regionPart);
        }
    }
 
Example 6
/**
 * Get region name and check the validity of it.
 * @param regionName region name provided in config
 * @param endpoint endpoint provided in config
 * @return region name
 */
protected static String getRegionName(String regionName, String endpoint) {
  if (isNullOrEmpty(regionName)) {
    String[] splits = endpoint.split("\\.");
    int count = splits.length;
    if ((count < 5) || (!"com".equals(splits[count - 1])) || (!"amazonaws".equals(splits[count - 2])) || (!"es".equals(splits[count - 3]))) {
      throw new IllegalArgumentException("Failure creating Amazon Elasticsearch Service connection. " +
        "You must provide hostname like *.[region name].es.amazonaws.com");
    }
    regionName = splits[count - 4];
  }
  final Regions region = Regions.fromName(regionName);
  return regionName;
}
 
Example 7
Source Project: cerberus   File: AwsStsHttpHeader.java    License: Apache License 2.0 5 votes vote down vote up
public String getRegion() {
  Pattern pattern = Pattern.compile(".*Credential=.*?/\\d+/(?<region>.*?)/.*");
  Matcher matcher = pattern.matcher(authorization);
  boolean didMatch = matcher.matches();

  if (!didMatch) {
    throw ApiException.newBuilder()
        .withApiErrors(DefaultApiError.GENERIC_BAD_REQUEST)
        .withExceptionMessage(
            String.format("Failed to determine region from header %s.", authorization))
        .build();
  }

  String region = matcher.group("region");

  try {
    //noinspection ResultOfMethodCallIgnored
    Regions.fromName(region);
  } catch (IllegalArgumentException e) {
    throw ApiException.newBuilder()
        .withApiErrors(DefaultApiError.GENERIC_BAD_REQUEST)
        .withExceptionMessage(String.format("Invalid region supplied %s.", region))
        .build();
  }

  return region;
}
 
Example 8
ConnectorConfig(ConfigDef config, Map<String, String> parsedConfig) {
    super(config, parsedConfig);
    region = Regions.fromName(getString(Keys.REGION));
    accessKeyId = getPassword(Keys.ACCESS_KEY_ID);
    secretKey = getPassword(Keys.SECRET_KEY);
    tableFormat = getString(Keys.TABLE_FORMAT);
    batchSize = getInt(Keys.BATCH_SIZE);
    kafkaCoordinateNames = kafkaCoordinateNamesFromConfig(getList(Keys.KAFKA_ATTRIBUTES));
    ignoreRecordKey = getBoolean(Keys.IGNORE_RECORD_KEY);
    ignoreRecordValue = getBoolean(Keys.IGNORE_RECORD_VALUE);
    topKeyAttribute = getString(Keys.TOP_KEY_ATTRIBUTE);
    topValueAttribute = getString(Keys.TOP_VALUE_ATTRIBUTE);
    maxRetries = getInt(Keys.MAX_RETRIES);
    retryBackoffMs = getInt(Keys.RETRY_BACKOFF_MS);
}
 
Example 9
TaskConfig(Map<String, String> props) {
    this.props = props;

    region = Regions.fromName(getValue(Keys.REGION));
    accessKeyId = getValue(Keys.ACCESS_KEY_ID, "");
    secretKey = getValue(Keys.SECRET_KEY, "");
    topicFormat = getValue(Keys.TOPIC_FORMAT);
    shards = Arrays.stream(getValue(Keys.SHARDS).split(",")).filter(shardId -> !shardId.isEmpty()).collect(Collectors.toList());
}
 
Example 10
Source Project: genie   File: BucketProperties.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set the AWS region from a string name representation e.g. us-east-1.
 *
 * @param region The name of the region to use
 * @see Regions#fromName(String)
 */
public void setRegion(@Nullable final String region) {
    if (region != null) {
        this.region = Regions.fromName(region);
    } else {
        this.region = null;
    }
}
 
Example 11
Source Project: components   File: KinesisClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Regions computeAwsRegion(String region, String unknownRegion) {
    Regions awsRegion = Regions.DEFAULT_REGION;
    if (KinesisRegion.OTHER.getValue().equals(region)) {
        try {
            awsRegion = Regions.fromName(unknownRegion);
        } catch (IllegalArgumentException e) {
            logger.warn("The region '" + unknownRegion + "' doesn't exist. Fallback to the default region ('" + Regions.DEFAULT_REGION.getName() + "')");
        }
    } else awsRegion = Regions.fromName(region);

    return awsRegion;
}
 
Example 12
Source Project: genie   File: AwsAutoConfiguration.java    License: 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 13
Source Project: Doradus   File: DynamoDBService.java    License: Apache License 2.0 5 votes vote down vote up
private void setRegionOrEndPoint() {
    String regionName = getParamString("ddb_region");
    if (regionName != null) {
        Regions regionEnum = Regions.fromName(regionName);
        Utils.require(regionEnum != null, "Unknown 'ddb_region': " + regionName);
        m_logger.info("Using region: {}", regionName);
        m_ddbClient.setRegion(Region.getRegion(regionEnum));
    } else {
        String ddbEndpoint = getParamString("ddb_endpoint");
        Utils.require(ddbEndpoint != null,
                      "Either 'ddb_region' or 'ddb_endpoint' must be defined for tenant: " + m_tenant.getName());
        m_logger.info("Using endpoint: {}", ddbEndpoint);
        m_ddbClient.setEndpoint(ddbEndpoint);
    }
}
 
Example 14
Source Project: geowave   File: DynamoDBOptions.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Regions convert(final String regionName) {
  if (regionName == null || regionName.isEmpty()) {
    return null;
  }
  return Regions.fromName(regionName.toLowerCase().replaceAll("_", "-"));
}
 
Example 15
Source Project: usergrid   File: SNSQueueManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the region
 */
private Region getRegion() {
    String regionName = fig.getPrimaryRegion();
    try {
        Regions regions = Regions.fromName(regionName);
        return Region.getRegion(regions);
    }
    catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("INVALID PRIMARY REGION FROM CONFIGURATION " + LegacyQueueFig.USERGRID_QUEUE_REGION_LOCAL + ": " + regionName, e);
    }
}
 
Example 16
/**
 * The Constructor.
 * 
 * @param s3Client
 *          the s3 client
 * @param partitioner
 *          the partitioner
 * @param config
 *          the configuration
 */
@Inject
public S3SinkStreamWriter(AmazonS3 s3Client, SinkPartitioner partitioner, S3SinkConfig config) {
  logger = LogManager.getLogger(S3SinkStream.class);
  this.partitioner = partitioner;
  this.bucketName = config.getBucketName();
  this.prefix = config.getPrefix();
  this.localTmpDir = config.getLocalTmpDir();
  this.buffer = new S3SinkBuffer(this.partitioner, config);
  this.s3Client = s3Client;
  this.regionName = Regions.fromName(config.getRegionName());
  Region region = Region.getRegion(regionName);
  this.s3Client.setRegion(region);
}
 
Example 17
Source Project: genie   File: S3ClientFactory.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Constructor.
 *
 * @param awsCredentialsProvider The base AWS credentials provider to use for the generated S3 clients
 * @param regionProvider         How this factory should determine the default {@link Regions}
 * @param environment            The Spring application {@link Environment}
 */
public S3ClientFactory(
    final AWSCredentialsProvider awsCredentialsProvider,
    final AwsRegionProvider regionProvider,
    final Environment environment
) {
    this.awsCredentialsProvider = awsCredentialsProvider;

    /*
     * Use the Spring property binder to dynamically map properties under a common root into a map of key to object.
     *
     * In this case we're trying to get bucketName -> BucketProperties
     *
     * So if there were properties like:
     * genie.aws.s3.buckets.someBucket1.roleARN = blah
     * genie.aws.s3.buckets.someBucket2.region = us-east-1
     * genie.aws.s3.buckets.someBucket2.roleARN = blah
     *
     * The result of this should be two entries in the map "bucket1" and "bucket2" mapping to property binding
     * object instances of BucketProperties with the correct property set or null if option wasn't specified.
     */
    this.bucketProperties = Binder
        .get(environment)
        .bind(
            BUCKET_PROPERTIES_ROOT_KEY,
            Bindable.mapOf(String.class, BucketProperties.class)
        )
        .orElse(Collections.emptyMap());

    // Set the initial size to the number of special cases defined in properties + 1 for the default client
    // NOTE: Should we proactively create all necessary clients or be lazy about it? For now, lazy.
    final int initialCapacity = this.bucketProperties.size() + 1;
    this.clientCache = new ConcurrentHashMap<>(initialCapacity);
    this.transferManagerCache = new ConcurrentHashMap<>(initialCapacity);

    String tmpRegion;
    try {
        tmpRegion = regionProvider.getRegion();
    } catch (final SdkClientException e) {
        tmpRegion = Regions.getCurrentRegion() != null
            ? Regions.getCurrentRegion().getName()
            : Regions.US_EAST_1.getName();
        log.warn(
            "Couldn't determine the AWS region from the provider ({}) supplied. Defaulting to {}",
            regionProvider.toString(),
            tmpRegion
        );
    }
    this.defaultRegion = Regions.fromName(tmpRegion);

    // Create a token service client to use if we ever need to assume a role
    // TODO: Perhaps this should be just set to null if the bucket properties are empty as we'll never need it?
    this.stsClient = AWSSecurityTokenServiceClientBuilder
        .standard()
        .withRegion(this.defaultRegion)
        .withCredentials(this.awsCredentialsProvider)
        .build();

    this.bucketToClientKey = new ConcurrentHashMap<>();
}
 
Example 18
private static CloudFormationFacade getCfnFacade(CustomResourceRequest request, AWSCredentialsProvider launchRoleCredentials) {
    String stackId = request.getStackId();
    Regions stackRegion = Regions.fromName(Splitter.on(':').splitToList(stackId).get(3));
    return new CloudFormationFacade(stackRegion, launchRoleCredentials);
}
 
Example 19
Source Project: strongbox   File: RegionDeserializer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Regions deserialize(JsonParser parser, DeserializationContext context)
        throws IOException {
    return Regions.fromName(parser.getValueAsString());
}
 
Example 20
Source Project: genie   File: AwsCredentialsProperties.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Set the static value for the region this instance is running in.
 *
 * @param newStatic The new static region value
 * @throws IllegalArgumentException When {@literal newStatic} can't be parsed by
 *                                  {@link Regions#fromName(String)}
 */
public void setStatic(final String newStatic) {
    this.region = Regions.fromName(newStatic);
}