Example usage for com.amazonaws.regions Region getRegion

List of usage examples for com.amazonaws.regions Region getRegion

Introduction

In this page you can find the example usage for com.amazonaws.regions Region getRegion.

Prototype

public static Region getRegion(Regions region) 

Source Link

Document

Returns the region with the id given, or null if it cannot be found in the current regions.xml file.

Usage

From source file:org.juneja.eventdemo.utils.AmazonSimpleQueueService.java

License:Open Source License

public static void main(String[] args) throws Exception {

    /*/*from  w w w .  jav  a  2  s . c  o  m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (~/.aws/credentials), and is in valid format.", e);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.DEFAULT_REGION);
    sqs.setRegion(usWest2);

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon SQS");
    System.out.println("===========================================\n");

    try {
        // Create a queue
        // System.out.println("Creating a new SQS queue called MyQueue.\n");
        // CreateQueueRequest createQueueRequest = new CreateQueueRequest("TestQueue_EventDriven_2");
        // String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

        GetQueueUrlResult queueResult = sqs.getQueueUrl("TestQueue_EventDriven_2");
        String myQueueUrl = queueResult.getQueueUrl();

        // List queues
        System.out.println("Listing all queues in your account.\n");
        for (String queueUrl : sqs.listQueues().getQueueUrls()) {
            System.out.println("  QueueUrl: " + queueUrl);
        }
        System.out.println();

        // Send a message
        //System.out.println("Sending a message to MyQueue.\n");
        //sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my new text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();

        System.out.println("Number of messages : " + messages.size());

        for (Message message : messages) {
            System.out.println("  Message");
            System.out.println("    MessageId:     " + message.getMessageId());
            System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
            System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
            System.out.println("    Body:          " + message.getBody());
            for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
        }
        System.out.println();

        // Delete a message
        //System.out.println("Deleting a message.\n");
        //String messageRecieptHandle = messages.get(0).getReceiptHandle();
        //sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

        // Delete a queue
        /**
        System.out.println("Deleting the test queue.\n");
        sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));
        **/
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:org.kmbmicro.chatwebsocket.DbString.java

public static void init() {
    try {//from w  ww  .  j a v  a 2 s.  c  o m
        credentials = new ProfileCredentialsProvider("default").getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (/Users/sandiwibowo/.aws/credentials), and is in valid format.", e);
    }
    AmazonDynamoDBClient dynamoDBAWS = new AmazonDynamoDBClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    dynamoDBAWS.setRegion(usWest2);
    dynamoDB = new DynamoDB(dynamoDBAWS);
}

From source file:org.lendingclub.mercator.aws.ArnGenerator.java

License:Apache License

public static ArnGenerator newInstance(String account, String region) {
    region = region.toUpperCase().replace("-", "_");
    return newInstance(account, Region.getRegion(Regions.valueOf(region)));
}

From source file:org.lendingclub.mercator.aws.ArnGenerator.java

License:Apache License

public static ArnGenerator newInstance(String account, Regions region) {
    return newInstance(account, Region.getRegion(region));
}

From source file:org.lendingclub.mercator.aws.AWSScanner.java

License:Apache License

public AWSScanner(AWSScannerBuilder builder, Class<? extends AmazonWebServiceClient> clientType, String label) {
    super(builder, Maps.newHashMap());
    if (builder.getRegion() == null) {
        builder.withRegion(Region.getRegion(Regions.US_EAST_1));
    }//from w  w  w. j  av  a  2s.co m
    this.neo4jLabel = label;
    this.clientType = clientType;

    Preconditions.checkNotNull(builder);
    Preconditions.checkNotNull(builder.getRegion());
    Preconditions.checkNotNull(builder.getProjector());

    this.builder = builder;
    this.region = builder.getRegion();
    this.projector = builder.getProjector();

    this.shadowRemover = new ShadowAttributeRemover(getNeoRxClient());

}

From source file:org.lendingclub.mercator.aws.AWSScannerBuilder.java

License:Apache License

public AWSScannerBuilder withRegion(Regions r) {

    Preconditions.checkState(this.region == null, "region already set");
    this.region = Region.getRegion(r);
    return this;
}

From source file:org.lendingclub.mercator.aws.JsonConverter.java

License:Apache License

public static JsonConverter newInstance(String account, Regions region) {
    return newInstance(account, Region.getRegion(region));
}

From source file:org.nuxeo.ecm.core.storage.sql.S3BinaryManager.java

License:Apache License

@Override
protected void setupCloudClient() throws IOException {
    // Get settings from the configuration
    bucketName = getProperty(BUCKET_NAME_PROPERTY);
    bucketNamePrefix = MoreObjects.firstNonNull(getProperty(BUCKET_PREFIX_PROPERTY), StringUtils.EMPTY);
    String bucketRegion = getProperty(BUCKET_REGION_PROPERTY);
    if (isBlank(bucketRegion)) {
        bucketRegion = DEFAULT_BUCKET_REGION;
    }/*  w w w . java 2 s .  co  m*/
    String awsID = getProperty(AWS_ID_PROPERTY);
    String awsSecret = getProperty(AWS_SECRET_PROPERTY);

    String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST);
    String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT);
    String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN);
    String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD);

    int maxConnections = getIntProperty(CONNECTION_MAX_PROPERTY);
    int maxErrorRetry = getIntProperty(CONNECTION_RETRY_PROPERTY);
    int connectionTimeout = getIntProperty(CONNECTION_TIMEOUT_PROPERTY);
    int socketTimeout = getIntProperty(SOCKET_TIMEOUT_PROPERTY);

    String keystoreFile = getProperty(KEYSTORE_FILE_PROPERTY);
    String keystorePass = getProperty(KEYSTORE_PASS_PROPERTY);
    String privkeyAlias = getProperty(PRIVKEY_ALIAS_PROPERTY);
    String privkeyPass = getProperty(PRIVKEY_PASS_PROPERTY);
    String endpoint = getProperty(ENDPOINT_PROPERTY);
    String sseprop = getProperty(SERVERSIDE_ENCRYPTION_PROPERTY);
    if (isNotBlank(sseprop)) {
        userServerSideEncryption = Boolean.parseBoolean(sseprop);
    }

    // Fallback on default env keys for ID and secret
    if (isBlank(awsID)) {
        awsID = System.getenv(AWS_ID_ENV);
    }
    if (isBlank(awsSecret)) {
        awsSecret = System.getenv(AWS_SECRET_ENV);
    }

    if (isBlank(bucketName)) {
        throw new RuntimeException("Missing conf: " + BUCKET_NAME_PROPERTY);
    }

    if (!isBlank(bucketNamePrefix) && !bucketNamePrefix.endsWith("/")) {
        log.warn(String.format("%s %s S3 bucket prefix should end by '/' " + ": added automatically.",
                BUCKET_PREFIX_PROPERTY, bucketNamePrefix));
        bucketNamePrefix += "/";
    }
    // set up credentials
    if (isBlank(awsID) || isBlank(awsSecret)) {
        awsCredentialsProvider = new InstanceProfileCredentialsProvider();
        try {
            awsCredentialsProvider.getCredentials();
        } catch (AmazonClientException e) {
            throw new RuntimeException("Missing AWS credentials and no instance role found");
        }
    } else {
        awsCredentialsProvider = new BasicAWSCredentialsProvider(awsID, awsSecret);
    }

    // set up client configuration
    clientConfiguration = new ClientConfiguration();
    if (isNotBlank(proxyHost)) {
        clientConfiguration.setProxyHost(proxyHost);
    }
    if (isNotBlank(proxyPort)) {
        clientConfiguration.setProxyPort(Integer.parseInt(proxyPort));
    }
    if (isNotBlank(proxyLogin)) {
        clientConfiguration.setProxyUsername(proxyLogin);
    }
    if (proxyPassword != null) { // could be blank
        clientConfiguration.setProxyPassword(proxyPassword);
    }
    if (maxConnections > 0) {
        clientConfiguration.setMaxConnections(maxConnections);
    }
    if (maxErrorRetry >= 0) { // 0 is allowed
        clientConfiguration.setMaxErrorRetry(maxErrorRetry);
    }
    if (connectionTimeout >= 0) { // 0 is allowed
        clientConfiguration.setConnectionTimeout(connectionTimeout);
    }
    if (socketTimeout >= 0) { // 0 is allowed
        clientConfiguration.setSocketTimeout(socketTimeout);
    }

    // set up encryption
    encryptionMaterials = null;
    if (isNotBlank(keystoreFile)) {
        boolean confok = true;
        if (keystorePass == null) { // could be blank
            log.error("Keystore password missing");
            confok = false;
        }
        if (isBlank(privkeyAlias)) {
            log.error("Key alias missing");
            confok = false;
        }
        if (privkeyPass == null) { // could be blank
            log.error("Key password missing");
            confok = false;
        }
        if (!confok) {
            throw new RuntimeException("S3 Crypto configuration incomplete");
        }
        try {
            // Open keystore
            File ksFile = new File(keystoreFile);
            FileInputStream ksStream = new FileInputStream(ksFile);
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(ksStream, keystorePass.toCharArray());
            ksStream.close();
            // Get keypair for alias
            if (!keystore.isKeyEntry(privkeyAlias)) {
                throw new RuntimeException("Alias " + privkeyAlias + " is missing or not a key alias");
            }
            PrivateKey privKey = (PrivateKey) keystore.getKey(privkeyAlias, privkeyPass.toCharArray());
            Certificate cert = keystore.getCertificate(privkeyAlias);
            PublicKey pubKey = cert.getPublicKey();
            KeyPair keypair = new KeyPair(pubKey, privKey);
            // Get encryptionMaterials from keypair
            encryptionMaterials = new EncryptionMaterials(keypair);
            cryptoConfiguration = new CryptoConfiguration();
        } catch (IOException | GeneralSecurityException e) {
            throw new RuntimeException("Could not read keystore: " + keystoreFile + ", alias: " + privkeyAlias,
                    e);
        }
    }
    isEncrypted = encryptionMaterials != null;

    // Try to create bucket if it doesn't exist
    if (!isEncrypted) {
        amazonS3 = new AmazonS3Client(awsCredentialsProvider, clientConfiguration);
    } else {
        amazonS3 = new AmazonS3EncryptionClient(awsCredentialsProvider,
                new StaticEncryptionMaterialsProvider(encryptionMaterials), clientConfiguration,
                cryptoConfiguration);
    }
    if (isNotBlank(endpoint)) {
        amazonS3.setEndpoint(endpoint);
    }

    // Set region explicitely for regions that reguire Version 4 signature
    ArrayList<String> V4_ONLY_REGIONS = new ArrayList<String>();
    V4_ONLY_REGIONS.add("eu-central-1");
    V4_ONLY_REGIONS.add("ap-northeast-2");
    if (V4_ONLY_REGIONS.contains(bucketRegion)) {
        amazonS3.setRegion(Region.getRegion(Regions.fromName(bucketRegion)));
    }

    try {
        if (!amazonS3.doesBucketExist(bucketName)) {
            amazonS3.createBucket(bucketName, bucketRegion);
            amazonS3.setBucketAcl(bucketName, CannedAccessControlList.Private);
        }
    } catch (AmazonClientException e) {
        throw new IOException(e);
    }

    // compat for NXP-17895, using "downloadfroms3", to be removed
    // these two fields have already been initialized by the base class initialize()
    // using standard property "directdownload"
    String dd = getProperty(DIRECTDOWNLOAD_PROPERTY_COMPAT);
    if (dd != null) {
        directDownload = Boolean.parseBoolean(dd);
    }
    int dde = getIntProperty(DIRECTDOWNLOAD_EXPIRE_PROPERTY_COMPAT);
    if (dde >= 0) {
        directDownloadExpire = dde;
    }

    transferManager = new TransferManager(amazonS3);
    abortOldUploads();
}

From source file:org.nuxeo.liveconnect.importer.aws.LiveconnectS3Blobprovider.java

License:Apache License

@Override
public void initialize(String blobProviderId, Map<String, String> properties) throws IOException {
    super.initialize(blobProviderId, properties);
    bucketName = properties.get(BUCKET_NAME_PROPERTY);
    String bucketRegion = properties.get(BUCKET_REGION_PROPERTY);
    String awsID = properties.get(AWS_ID_PROPERTY);
    String awsSecret = properties.get(AWS_SECRET_PROPERTY);
    amazonS3 = new AmazonS3Client(new BasicAWSCredentials(awsID, awsSecret), new ClientConfiguration());
    amazonS3.setRegion(Region.getRegion(Regions.fromName(bucketRegion)));
}

From source file:org.openchain.certification.utility.EmailUtility.java

License:Apache License

private static AmazonSimpleEmailServiceClient getEmailClient(ServletConfig config) throws EmailUtilException {
    String regionName = config.getServletContext().getInitParameter("email_ses_region");
    if (regionName == null || regionName.isEmpty()) {
        logger.error("Missing email_ses_region parameter in the web.xml file");
        throw (new EmailUtilException(
                "The region name for the email facility has not been set.  Pleaese contact the OpenChain team with this error."));
    }//  ww  w .j a va  2  s .  c  om
    String secretKey = null;
    String accessKey = System.getenv(ACCESS_KEY_VAR);
    if (accessKey == null) {
        accessKey = System.getProperty(ACCESS_KEY_VAR);
        if (accessKey != null) {
            secretKey = System.getProperty(SECRET_KEY_VAR);
        }
    } else {
        secretKey = System.getenv(SECRET_KEY_VAR);
    }
    AmazonSimpleEmailServiceClient retval = null;
    if (accessKey != null) {
        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        retval = new AmazonSimpleEmailServiceClient(credentials);
    } else {
        retval = new AmazonSimpleEmailServiceClient();
    }
    Region region = Region.getRegion(Regions.fromName(regionName));
    retval.setRegion(region);
    return retval;
}