Java Code Examples for software.amazon.awssdk.regions.Region#of()

The following examples show how to use software.amazon.awssdk.regions.Region#of() . 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: KinesisVerticle.java    From reactive-refarch-cloudformation with Apache License 2.0 6 votes vote down vote up
private KinesisAsyncClient createClient() {

        ClientAsyncConfiguration clientConfiguration = ClientAsyncConfiguration.builder().build();

        // Reading credentials from ENV-variables
        AwsCredentialsProvider awsCredentialsProvider = DefaultCredentialsProvider.builder().build();

        // Configuring Kinesis-client with configuration
        String tmp = System.getenv("REGION");

        Region myRegion;
        if (tmp == null || tmp.trim().length() == 0) {
            myRegion = Region.US_EAST_1;
            LOGGER.info("Using default region");
        } else {
            myRegion = Region.of(tmp);
        }

        LOGGER.info("Deploying in Region " + myRegion.toString());

        return KinesisAsyncClient.builder()
                .asyncConfiguration(clientConfiguration)
                .credentialsProvider(awsCredentialsProvider)
                .region(myRegion)
                .build();
    }
 
Example 2
Source File: Synch.java    From pegasus with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the log.
 *
 * @param properties properties with pegasus prefix stripped.
 * @param level
 * @param jsonFileMap
 * @throws IOException
 */
public void initialze(
        Properties properties, Level level, EnumMap<BATCH_ENTITY_TYPE, String> jsonFileMap)
        throws IOException {
    // "405596411149";
    mLogger = Logger.getLogger(Synch.class.getName());
    mLogger.setLevel(level);
    mAWSAccountID = getProperty(properties, Synch.AWS_PROPERTY_PREFIX, "account");
    mAWSRegion =
            Region.of(
                    getProperty(
                            properties, Synch.AWS_PROPERTY_PREFIX, "region")); // "us-west-2"
    mPrefix = getProperty(properties, Synch.AWS_BATCH_PROPERTY_PREFIX, "prefix");
    mDeleteOnExit = new EnumMap<>(BATCH_ENTITY_TYPE.class);
    mCommonFilesToS3 = new LinkedList<String>();
    mS3BucketKeyPrefix = "";

    mJobstateWriter = new AWSJobstateWriter();
    mJobstateWriter.initialze(new File("."), mPrefix, mLogger);

    mJobMap = new HashMap();
    mExecutorService = Executors.newFixedThreadPool(2);
    mBatchClient = BatchClient.builder().region(mAWSRegion).build();
    mDoneWithJobSubmits = false;
    mExitCode = 0;
}
 
Example 3
Source File: S3BundlePersistenceProvider.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
private Region getRegion(final ProviderConfigurationContext configurationContext) {
    final String regionValue = configurationContext.getProperties().get(REGION_PROP);
    if (StringUtils.isBlank(regionValue)) {
        throw new ProviderCreationException("The property '" + REGION_PROP + "' must be provided");
    }

    Region region = null;
    for (Region r : Region.regions()) {
        if (r.id().equals(regionValue)) {
            region = r;
            break;
        }
    }

    if (region == null) {
        LOGGER.warn("The provided region was not found in the list of known regions. This may indicate an invalid region, " +
                "or may indicate a region that is newer than the known list of regions");
        region = Region.of(regionValue);
    }

    LOGGER.debug("Using region {}", new Object[] {region.id()});
    return region;
}
 
Example 4
Source File: InstanceProfileRegionProvider.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public Region getRegion() throws SdkClientException {
    if (SdkSystemSetting.AWS_EC2_METADATA_DISABLED.getBooleanValueOrThrow()) {
        throw SdkClientException.builder()
                                .message("EC2 Metadata is disabled. Unable to retrieve region information from " +
                                         "EC2 Metadata service.")
                                .build();
    }

    if (region == null) {
        synchronized (this) {
            if (region == null) {
                this.region = tryDetectRegion();
            }
        }
    }

    if (region == null) {
        throw SdkClientException.builder()
                                .message("Unable to retrieve region information from EC2 Metadata service. "
                                     + "Please make sure the application is running on EC2.")
                                .build();
    }

    return Region.of(region);
}
 
Example 5
Source File: GeneratePreSignUrlInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private URI createEndpoint(String regionName, String serviceName) {

        Region region = Region.of(regionName);

        if (region == null) {
            throw SdkClientException.builder()
                                    .message("{" + serviceName + ", " + regionName + "} was not "
                                             + "found in region metadata. Update to latest version of SDK and try again.")
                                    .build();
        }

        URI endpoint = Ec2Client.serviceMetadata().endpointFor(region);
        if (endpoint.getScheme() == null) {
            return URI.create("https://" + endpoint);
        }
        return endpoint;
    }
 
Example 6
Source File: RdsPresignInterceptor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private URI createEndpoint(String regionName, String serviceName) {
    Region region = Region.of(regionName);

    if (region == null) {
        throw SdkClientException.builder()
                                .message("{" + serviceName + ", " + regionName + "} was not "
                                        + "found in region metadata. Update to latest version of SDK and try again.")
                                .build();
    }

    return new DefaultServiceEndpointBuilder(SERVICE_NAME, Protocol.HTTPS.toString())
            .withRegion(region)
            .getServiceEndpoint();
}
 
Example 7
Source File: PresignRequestHandlerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testParsesDestinationRegionfromRequestEndpoint() throws URISyntaxException {
    CopyDbSnapshotRequest request = CopyDbSnapshotRequest.builder()
            .sourceRegion("us-east-1")
            .build();
    Region destination = Region.of("us-west-2");
    SdkHttpFullRequest marshalled = marshallRequest(request);

    final SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshalled);

    final URI presignedUrl = new URI(presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0));
    assertTrue(presignedUrl.toString().contains("DestinationRegion=" + destination.id()));
}
 
Example 8
Source File: AwsRegionProviderChainTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void firstProviderInChainGivesRegionInformation_DoesNotConsultOtherProviders() {
    AwsRegionProvider providerOne = mock(AwsRegionProvider.class);
    AwsRegionProvider providerTwo = mock(AwsRegionProvider.class);
    AwsRegionProvider providerThree = mock(AwsRegionProvider.class);
    AwsRegionProviderChain chain = new AwsRegionProviderChain(providerOne, providerTwo,
                                                              providerThree);
    final Region expectedRegion = Region.of("some-region-string");
    when(providerOne.getRegion()).thenReturn(expectedRegion);
    assertEquals(expectedRegion, chain.getRegion());

    verify(providerTwo, never()).getRegion();
    verify(providerThree, never()).getRegion();
}
 
Example 9
Source File: AwsRegionProviderChainTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void lastProviderInChainGivesRegionInformation() {
    final Region expectedRegion = Region.of("some-region-string");
    AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(),
                                                              new NeverAwsRegionProvider(),
                                                              new StaticAwsRegionProvider(
                                                                      expectedRegion));
    assertEquals(expectedRegion, chain.getRegion());
}
 
Example 10
Source File: AwsRegionProviderChainTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void providerThrowsException_ContinuesToNextInChain() {
    final Region expectedRegion = Region.of("some-region-string");
    AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(),
                                                              new FaultyAwsRegionProvider(),
                                                              new StaticAwsRegionProvider(
                                                                      expectedRegion));
    assertEquals(expectedRegion, chain.getRegion());
}
 
Example 11
Source File: AwsRegionProviderChainTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Only Exceptions should be caught and continued, Errors should propagate to caller and short
 * circuit the chain.
 */
@Test(expected = Error.class)
public void providerThrowsError_DoesNotContinueChain() {
    final Region expectedRegion = Region.of("some-region-string");
    AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(),
                                                              new FatalAwsRegionProvider(),
                                                              new StaticAwsRegionProvider(
                                                                      expectedRegion));
    assertEquals(expectedRegion, chain.getRegion());
}
 
Example 12
Source File: RedisUpdate.java    From reactive-refarch-cloudformation with Apache License 2.0 5 votes vote down vote up
private static KinesisAsyncClient createClient() {

        ClientAsyncConfiguration clientConfiguration = ClientAsyncConfiguration.builder().build();

        // Reading credentials from ENV-variables
        AwsCredentialsProvider awsCredentialsProvider = DefaultCredentialsProvider.builder().build();

        // Configuring Kinesis-client with configuration
        String tmp = System.getenv("REGION");

        Region myRegion = null;
        if (tmp == null || tmp.trim().length() == 0) {
            myRegion = Region.US_EAST_1;
            System.out.println("Using default region");
        } else {
            myRegion = Region.of(tmp);
        }

        System.out.println("Deploying in Region " + myRegion.toString());

        KinesisAsyncClient kinesisClient = KinesisAsyncClient.builder()
                .asyncConfiguration(clientConfiguration)
                .credentialsProvider(awsCredentialsProvider)
                .region(myRegion)
                .build();

        return kinesisClient;
    }
 
Example 13
Source File: BaseKinesisAppender.java    From kinesis-logback-appender with Apache License 2.0 5 votes vote down vote up
/**
 * Determine region. If not specified tries to determine region from where the
 * application is running or fall back to the default.
 * 
 * @return Region to configure the client
 */
private Region findRegion() {
  boolean regionProvided = !Validator.isBlank(this.region);
  if(!regionProvided) {
    // Determine region from where application is running, or fall back to default region
    return Region.of(AppenderConstants.DEFAULT_REGION);
  }
  return Region.of(this.region);
}
 
Example 14
Source File: StreamMonitor.java    From amazon-kinesis-scaling-utils with Apache License 2.0 5 votes vote down vote up
public StreamMonitor(AutoscalingConfiguration config) throws Exception {
	this.config = config;
	Region setRegion = Region.of(this.config.getRegion());

	// setup credential refresh
	this.credentials = DefaultCredentialsProvider.builder().asyncCredentialUpdateEnabled(true).build();

	// create scaler class and clients
	this.cloudWatchClient = CloudWatchClient.builder().credentialsProvider(this.credentials).region(setRegion).build();
	this.kinesisClient = KinesisClient.builder().credentialsProvider(this.credentials).region(setRegion).build();
	this.snsClient = SnsClient.builder().credentialsProvider(this.credentials).region(setRegion).build();
	
	this.scaler = new StreamScaler(this.kinesisClient);
}
 
Example 15
Source File: S3Manager.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
public S3Manager() {
    clientRegion = Region.of(S3_CONFIG.getProperty(S3ConfigKey.S3_REGION.getName(), S3ConfigKey.S3_REGION.getValue().toString()));
    endpoint = S3_CONFIG.getProperty(S3ConfigKey.S3_ENDPOINT.getName(), S3ConfigKey.S3_REGION.getValue().toString());
    accessKey = S3_CONFIG.getProperty(S3ConfigKey.S3_ACCESS_KEY.getName(), S3ConfigKey.S3_ACCESS_KEY.getValue().toString());
    secretKey = S3_CONFIG.getProperty(S3ConfigKey.S3_SECRET_KEY.getName(), S3ConfigKey.S3_SECRET_KEY.getValue().toString());
    bucketName = S3_CONFIG.getProperty(S3ConfigKey.S3_BUCKET_NAME.getName(), S3ConfigKey.S3_BUCKET_NAME.getValue().toString());
    logger.info(String.format("S3 config, client region: %s, endpoint: %s, access key: %s, secret key: %s, bucket name: %s ",
            clientRegion, endpoint, accessKey, secretKey, bucketName));
}
 
Example 16
Source File: s3-service-metadata.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public Region signingRegion(Region region) {
    return Region.of(SIGNING_REGION_OVERRIDES.getOrDefault(region.id(), region.id()));
}
 
Example 17
Source File: sts-service-metadata.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public Region signingRegion(Region region) {
    return Region.of(SIGNING_REGION_OVERRIDES.getOrDefault(region.id(), region.id()));
}
 
Example 18
Source File: BaseKinesisConfig.java    From pulsar with Apache License 2.0 4 votes vote down vote up
protected Region regionAsV2Region() {
    return Region.of(this.getAwsRegion());
}
 
Example 19
Source File: DynamoDBSourceConfig.java    From pulsar with Apache License 2.0 4 votes vote down vote up
protected Region regionAsV2Region() {
    return Region.of(this.getAwsRegion());
}
 
Example 20
Source File: ScalingClient.java    From amazon-kinesis-scaling-utils with Apache License 2.0 4 votes vote down vote up
private void loadParams() throws Exception {
	if (System.getProperty(STREAM_PARAM) == null) {
		throw new Exception("You must provide a Stream Name");
	} else {
		this.streamName = System.getProperty(STREAM_PARAM);
	}

	this.shardId = System.getProperty(SHARD_ID_PARAM);

	if (System.getProperty(ACTION_PARAM) == null) {
		throw new Exception("You must provide a Scaling Action");
	} else {
		this.scalingAction = ScalingAction.valueOf(System.getProperty(ACTION_PARAM));

		// ensure the action is one of the supported types for shards
		if (this.shardId != null && !(this.scalingAction.equals(StreamScaler.ScalingAction.split)
				|| this.scalingAction.equals(StreamScaler.ScalingAction.merge))) {
			throw new Exception("Can only Split or Merge Shards");
		}
	}

	if (System.getProperty(REGION_PARAM) != null) {
		this.region = Region.of(System.getProperty(REGION_PARAM));
	}

	if (System.getProperty(WAIT_FOR_COMPLETION) != null) {
		this.doWait = Boolean.parseBoolean(System.getProperty(WAIT_FOR_COMPLETION));
	}

	if (this.scalingAction != ScalingAction.report) {
		if (System.getProperty(SCALE_COUNT_PARAM) == null && System.getProperty(SCALE_PCT_PARAM) == null)
			throw new Exception("You must provide either a scaling Count or Percentage");

		if (System.getProperty(SCALE_COUNT_PARAM) != null && System.getProperty(SCALE_PCT_PARAM) != null)
			throw new Exception("You must provide either a scaling Count or Percentage but not both");

		if (this.shardId != null && System.getProperty(SCALE_COUNT_PARAM) == null) {
			throw new Exception("Shards must be scaled by an absolute number only");
		}

		if (System.getProperty(SCALE_COUNT_PARAM) != null) {
			this.scaleCount = Integer.parseInt(System.getProperty(SCALE_COUNT_PARAM));
			this.scaleBy = StreamScaler.ScaleBy.count;
		}

		if (System.getProperty(SCALE_PCT_PARAM) != null) {
			this.scalePct = Double.parseDouble(System.getProperty(SCALE_PCT_PARAM));
			this.scaleBy = StreamScaler.ScaleBy.pct;
		}

		if (System.getProperty(MIN_SHARDS_PARAM) != null) {
			this.minShards = Integer.parseInt(System.getProperty(MIN_SHARDS_PARAM));
		}

		if (System.getProperty(MAX_SHARDS_PARAM) != null) {
			this.maxShards = Integer.parseInt(System.getProperty(MAX_SHARDS_PARAM));
		}
	}

	scaler = new StreamScaler(this.region);
}