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:InlineTaggingCodeSampleApp.java

License:Open Source License

public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================//
    //============================================================================================//

    /*/*from w w  w .  j a va 2s  . com*/
     * The ProfileCredentialsProvider will return your [haow2]
     * credential profile by reading from the credentials file located at
     * (/Users/Dawn/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("haow2").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/Dawn/.aws/credentials), and is in valid format.", e);
    }

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    ec2.setRegion(usWest2);

    // Initializes a Spot Instance Request
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();

    // Request 1 x t1.micro instance with a bid price of $0.03.
    requestRequest.setSpotPrice("0.03");
    requestRequest.setInstanceCount(Integer.valueOf(1));

    // Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
    // and the latest Amazon Linux AMI id available. Note, you should always use the latest
    // Amazon Linux AMI id or another of your choosing.
    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId("ami-8c1fece5");
    launchSpecification.setInstanceType("t1.micro");

    // Add the security group to the request.
    ArrayList<String> securityGroups = new ArrayList<String>();
    securityGroups.add("GettingStartedGroup");
    launchSpecification.setSecurityGroups(securityGroups);

    // Add the launch specifications to the request.
    requestRequest.setLaunchSpecification(launchSpecification);

    //============================================================================================//
    //=========================== Getting the Request ID from the Request ========================//
    //============================================================================================//

    // Call the RequestSpotInstance API.
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    // Setup an arraylist to collect all of the request ids we want to watch hit the running
    // state.
    ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

    // Add all of the request ids to the hashset, so we can determine when they hit the
    // active state.
    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }

    //============================================================================================//
    //====================================== Tag the Spot Requests ===============================//
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> requestTags = new ArrayList<Tag>();
    requestTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for requests.
    CreateTagsRequest createTagsRequest_requests = new CreateTagsRequest();
    createTagsRequest_requests.setResources(spotInstanceRequestIds);
    createTagsRequest_requests.setTags(requestTags);

    // Try to tag the Spot request submitted.
    try {
        ec2.createTags(createTagsRequest_requests);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=========================== Determining the State of the Spot Request ======================//
    //============================================================================================//

    // Create a variable that will track whether there are any requests still in the open state.
    boolean anyOpen;

    // Initialize variables.
    ArrayList<String> instanceIds = new ArrayList<String>();

    do {
        // Create the describeRequest with tall of the request id to monitor (e.g. that we started).
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

        // Initialize the anyOpen variable to false, which assumes there are no requests open unless
        // we find one that is still open.
        anyOpen = false;

        try {
            // Retrieve all of the requests we want to monitor.
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            // Look through each request and determine if they are all in the active state.
            for (SpotInstanceRequest describeResponse : describeResponses) {
                // If the state is open, it hasn't changed since we attempted to request it.
                // There is the potential for it to transition almost immediately to closed or
                // cancelled so we compare against open instead of active.
                if (describeResponse.getState().equals("open")) {
                    anyOpen = true;
                    break;
                }

                // Add the instance id to the list we will eventually terminate.
                instanceIds.add(describeResponse.getInstanceId());
            }
        } catch (AmazonServiceException e) {
            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
            anyOpen = true;
        }

        try {
            // Sleep for 60 seconds.
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            // Do nothing because it woke up early.
        }
    } while (anyOpen);

    //============================================================================================//
    //====================================== Tag the Spot Instances ===============================//
    //============================================================================================//

    // Create the list of tags we want to create
    ArrayList<Tag> instanceTags = new ArrayList<Tag>();
    instanceTags.add(new Tag("keyname1", "value1"));

    // Create a tag request for instances.
    CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest();
    createTagsRequest_instances.setResources(instanceIds);
    createTagsRequest_instances.setTags(instanceTags);

    // Try to tag the Spot instance started.
    try {
        ec2.createTags(createTagsRequest_instances);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //====================================== Canceling the Request ==============================//
    //============================================================================================//

    try {
        // Cancel requests.
        CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(
                spotInstanceRequestIds);
        ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error cancelling instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

    //============================================================================================//
    //=================================== Terminating any Instances ==============================//
    //============================================================================================//
    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}

From source file:SimpleQueueServiceMultiThread2.java

License:Open Source License

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

    /*/*from   w w  w .  java 2s . co 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,clientConfig);
    sqs = new AmazonSQSClient(credentials);

    Region apSouthEast1 = Region.getRegion(Regions.AP_SOUTHEAST_1);
    sqs.setRegion(apSouthEast1);

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

    //Define thread pool size
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);

    //create a list to hold the Future object associated with Callable
    List<Future<Long>> list = new ArrayList<Future<Long>>();

    //Create Callable instance
    Callable<Long> callable = new SimpleQueueServiceMultiThread2();

    for (int i = 0; i < threadSize; i++) {

        //submit Callable tasks to be executed by thread pool
        Future<Long> future = executor.submit(callable);

        //add Future to the list, we can get return value using Future
        list.add(future);

    }

    for (Future<Long> fut : list) {

        try {
            // Future.get() waits for task to get completed
            System.out.println("Time difference : " + fut.get());

            long timeDiff = fut.get().longValue();

            totalTime = Long.valueOf(totalTime + timeDiff);

            if (timeDiff >= maxTime) {
                maxTime = timeDiff;
            }

            if (minTime == 0L && timeDiff >= minTime) {
                minTime = timeDiff;
                //}else if (timeDiff <= minTime && timeDiff != 0L) {
            } else if (timeDiff <= minTime) {
                minTime = timeDiff;
            }

        } catch (InterruptedException | ExecutionException e) {

            e.printStackTrace();

        }
    }

    if (totalTime >= 0L) {

        averageTime = totalTime / threadSize;

    }

    System.out.println("Total Time : " + Long.valueOf(totalTime).toString());
    System.out.println("Max Time : " + Long.valueOf(maxTime).toString());
    System.out.println("Min Time : " + Long.valueOf(minTime).toString());
    System.out.println("Average Time : " + Long.valueOf(averageTime).toString());

    //shut down the executor service now
    executor.shutdown();

}

From source file:InstallYarn.java

License:Open Source License

public static void main(String[] args) throws JSchException, IOException, InterruptedException {

    /*/*from w ww  . ja  v  a  2s .  c  o m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (C:\\Users\\CH\\.aws\\credentials).
     */

    AWSCredentials credentials = null;
    try {
        credentials = new BasicAWSCredentials("Your Access Key ID", "Your Secret Access Key");

    } 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 (C:\\Users\\CH\\.aws\\credentials), and is in valid format.", e);
    }

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    ec2.setRegion(usWest2);

    /*
    // Create a new security group.
    try {
    CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(
            "GettingStartedGroup", "Getting Started Security Group");
    CreateSecurityGroupResult result = ec2
            .createSecurityGroup(securityGroupRequest);
    System.out.println(String.format("Security group created: [%s]",
            result.getGroupId()));
    } catch (AmazonServiceException ase) {
    // Likely this means that the group is already created, so ignore.
    System.out.println(ase.getMessage());
    }
            
    String ipAddr = "0.0.0.0/0";
            
    // Get the IP of the current host, so that we can limit the Security Group
    // by default to the ip range associated with your subnet.
    try {
    InetAddress addr = InetAddress.getLocalHost();
            
    // Get IP Address
    ipAddr = addr.getHostAddress()+"/10";
    } catch (UnknownHostException e) {
    }
            
    // Create a range that you would like to populate.
    List<String> ipRanges = Collections.singletonList(ipAddr);
            
    // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic).
    IpPermission ipPermission = new IpPermission()
        .withIpProtocol("tcp")
        .withFromPort(new Integer(22))
        .withToPort(new Integer(22))
        .withIpRanges(ipRanges);
            
    List<IpPermission> ipPermissions = Collections.singletonList(ipPermission);
            
    try {
    // Authorize the ports to the used.
    AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(
            "GettingStartedGroup", ipPermissions);
    ec2.authorizeSecurityGroupIngress(ingressRequest);
    System.out.println(String.format("Ingress port authroized: [%s]",
            ipPermissions.toString()));
    } catch (AmazonServiceException ase) {
    // Ignore because this likely means the zone has already been authorized.
    System.out.println(ase.getMessage());
    }
    */
    //CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
    //.withKeyName("CHENHAO");

    //CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);

    //KeyPair keyPair = new KeyPair();
    //keyPair = createKeyPairResult.getKeyPair();
    //String privateKey = keyPair.getKeyMaterial();

    int cluster_size = Integer
            .parseInt(JOptionPane.showInputDialog("Enter number of machines you want to set"));
    String ami_name = JOptionPane.showInputDialog("Enter your ami name");
    String key_name = JOptionPane.showInputDialog("Enter your key name");
    String s_group_name = JOptionPane.showInputDialog("Enter your security group name");

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
    runInstancesRequest.withImageId(ami_name).withInstanceType("t2.micro").withMinCount(cluster_size)
            .withMaxCount(cluster_size).withKeyName(key_name).withSecurityGroups(s_group_name);

    RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);

    Thread.sleep(10000);

    Vector<String> instanceId = new Vector<String>();
    for (Instance ins : runInstancesResult.getReservation().getInstances())
        instanceId.add(ins.getInstanceId());

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(instanceId);
    DescribeInstancesResult result = ec2.describeInstances(request);
    List<Reservation> reservations = result.getReservations();

    List<Instance> instances_list = new Vector<Instance>();
    for (int i = 0; i < reservations.size(); i++)
        instances_list.addAll(reservations.get(i).getInstances());

    System.out.println("Plan cluster size:" + cluster_size + " Real size:" + instances_list.size());

    JSch jsch = new JSch();
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Choose your privatekey");
    chooser.setFileHidingEnabled(false);
    int returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        System.out.println("You chose " + chooser.getSelectedFile().getAbsolutePath() + ".");
        jsch.addIdentity(chooser.getSelectedFile().getAbsolutePath());
    }

    Session session;
    UserInfo ui = new MyUserInfo();
    for (int i = 0; i < instances_list.size(); i++) {
        if (instances_list.get(i).getPublicIpAddress() == null)
            System.out.println("Error, public ip is null\n");

        System.out.println("Connect to:" + instances_list.get(i).getPublicIpAddress() + "\n");
        session = jsch.getSession("ubuntu", instances_list.get(i).getPublicIpAddress(), 22);
        session.setUserInfo(ui);
        session.connect();

        //
        //if(i==0)
        //{
        //  transfer_file_to("/home/ubuntu","C:/Users/CH/Downloads/ch.pem",session);
        // exec("chmod 400 /home/ubuntu/ch.pem",session);
        //}

        //slaves file
        for (int j = 0; j < instances_list.size(); j++) {
            if (j != 0)
                exec("echo " + instances_list.get(j).getPrivateIpAddress()
                        + "\n >> /usr/local/hadoop/etc/hadoop/slaves", session);
        }
        //core-site file
        String command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress()
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        //hdfs-size file
        command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress()
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        command = "sed -i 's#replication#" + Integer.toString(cluster_size - 1)
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        //yarn-size file
        command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress()
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        session.disconnect();
    }

    //username and passphrase will be given via UserInfo interface.

    //slaves file

}

From source file:CloudFormation.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*//w  w w  .  ja  v a  2  s.  c om
     * This credentials provider implementation loads your AWS credentials
     * from a properties file at the root of your classpath.
     * Important: Be sure to fill in your AWS access credentials in the
     *            AwsCredentials.properties file before you try to run this
     *            sample.
     * http://aws.amazon.com/security-credentials
     */
    AmazonCloudFormation stackbuilder = new AmazonCloudFormationClient(
            new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_EAST_1);
    stackbuilder.setRegion(usWest2);

    System.out.println("===========================================");
    System.out.println("Getting Started with AWS CloudFormation");
    System.out.println("===========================================\n");

    String stackName = "CloudFormationSampleStack";
    String logicalResourceName = "SampleNotificationTopic";

    try {
        // Create a stack
        CreateStackRequest createRequest = new CreateStackRequest();
        createRequest.setStackName(stackName);
        createRequest.setTemplateBody(
                convertStreamToString(CloudFormation.class.getResourceAsStream("CloudFormation.template")));
        System.out.println("Creating a stack called " + createRequest.getStackName() + ".");
        stackbuilder.createStack(createRequest);

        // Wait for stack to be created
        // Note that you could use SNS notifications on the CreateStack call to track the progress of the stack creation
        System.out.println("Stack creation completed, the stack " + stackName + " completed with "
                + waitForCompletion(stackbuilder, stackName));

        // Show all the stacks for this account along with the resources for each stack
        for (Stack stack : stackbuilder.describeStacks(new DescribeStacksRequest()).getStacks()) {
            System.out.println(
                    "Stack : " + stack.getStackName() + " [" + stack.getStackStatus().toString() + "]");

            DescribeStackResourcesRequest stackResourceRequest = new DescribeStackResourcesRequest();
            stackResourceRequest.setStackName(stack.getStackName());
            for (StackResource resource : stackbuilder.describeStackResources(stackResourceRequest)
                    .getStackResources()) {
                System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                        resource.getLogicalResourceId(), resource.getPhysicalResourceId());
            }
        }

        // Lookup a resource by its logical name
        DescribeStackResourcesRequest logicalNameResourceRequest = new DescribeStackResourcesRequest();
        logicalNameResourceRequest.setStackName(stackName);
        logicalNameResourceRequest.setLogicalResourceId(logicalResourceName);
        System.out.format("Looking up resource name %1$s from stack %2$s\n",
                logicalNameResourceRequest.getLogicalResourceId(), logicalNameResourceRequest.getStackName());
        for (StackResource resource : stackbuilder.describeStackResources(logicalNameResourceRequest)
                .getStackResources()) {
            System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                    resource.getLogicalResourceId(), resource.getPhysicalResourceId());
        }

        // Delete the stack
        DeleteStackRequest deleteRequest = new DeleteStackRequest();
        deleteRequest.setStackName(stackName);
        System.out.println("Deleting the stack called " + deleteRequest.getStackName() + ".");
        stackbuilder.deleteStack(deleteRequest);

        // Wait for stack to be deleted
        // Note that you could used SNS notifications on the original CreateStack call to track the progress of the stack deletion
        System.out.println("Stack creation completed, the stack " + stackName + " completed with "
                + waitForCompletion(stackbuilder, stackName));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS CloudFormation, 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 AWS CloudFormation, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:S3ClientSideEncryptionAsymmetricMasterKey.java

License:Apache License

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

    // 1. Load keys from files
    byte[] bytes = FileUtils.readFileToByteArray(new File(keyDir + "/private.key"));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes);
    PrivateKey pk = kf.generatePrivate(ks);

    bytes = FileUtils.readFileToByteArray(new File(keyDir + "/public.key"));
    PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));

    KeyPair loadedKeyPair = new KeyPair(publicKey, pk);

    // 2. Construct an instance of AmazonS3EncryptionClient.
    EncryptionMaterials encryptionMaterials = new EncryptionMaterials(loadedKeyPair);
    AWSCredentials credentials = new BasicAWSCredentials("Q3AM3UQ867SPQQA43P2F",
            "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
    AmazonS3EncryptionClient encryptionClient = new AmazonS3EncryptionClient(credentials,
            new StaticEncryptionMaterialsProvider(encryptionMaterials));
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    encryptionClient.setRegion(usEast1);
    encryptionClient.setEndpoint("https://play.minio.io:9000");

    final S3ClientOptions clientOptions = S3ClientOptions.builder().setPathStyleAccess(true).build();
    encryptionClient.setS3ClientOptions(clientOptions);

    // Create the bucket
    encryptionClient.createBucket(bucketName);
    // 3. Upload the object.
    byte[] plaintext = "Hello World, S3 Client-side Encryption Using Asymmetric Master Key!".getBytes();
    System.out.println("plaintext's length: " + plaintext.length);
    encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey, new ByteArrayInputStream(plaintext),
            new ObjectMetadata()));

    // 4. Download the object.
    S3Object downloadedObject = encryptionClient.getObject(bucketName, objectKey);
    byte[] decrypted = IOUtils.toByteArray(downloadedObject.getObjectContent());
    Assert.assertTrue(Arrays.equals(plaintext, decrypted));
    System.out.println("decrypted length: " + decrypted.length);
    //deleteBucketAndAllContents(encryptionClient);
}

From source file:S3TransferProgressSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*w  w w .j  a  v a  2  s  .  c o m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (/Users/zunzunwang/.aws/credentials).
     *
     * TransferManager manages a pool of threads, so we create a
     * single instance and share it throughout our application.
     */
    try {
        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/zunzunwang/.aws/credentials), and is in valid format.", e);
    }

    AmazonS3 s3 = new AmazonS3Client(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);
    tx = new TransferManager(s3);

    bucketName = "s3-upload-sdk-sample-" + credentials.getAWSAccessKeyId().toLowerCase();

    new S3TransferProgressSample();
}

From source file:AmazonS3Handler.java

License:Open Source License

public AmazonS3Handler() throws IOException {
    /*// w  w  w  .j a  v a  2  s. c om
     * This credentials provider implementation loads your AWS credentials
     * from a properties file at the root of your classpath.
     *
     * Important: Be sure to fill in your AWS access credentials in the
     *            AwsCredentials.properties file before you try to run this
     *            sample.
     * http://aws.amazon.com/security-credentials
     */
    s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

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

From source file:sqsAlertPersist.java

License:Open Source License

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

    // get credentials
    String user = "jreilly";
    AWSCredentials credentials = whgHelper.getCred(user);

    // use credentials to set access to SQS
    AmazonSQS sqs = whgHelper.setQueueAccess(credentials);

    // define queue that messages will be retrieved from
    String thisQueue = "alertPersist";
    String nextQueue = "alertCache";

    // set access to database with credentials
    dynamoDB = new AmazonDynamoDBClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    dynamoDB.setRegion(usEast1);/*  w w w.j a v  a2  s.c  o m*/

    // check for table, create one if missing
    String tableName = "alerts";
    whgHelper.setTable(dynamoDB, tableName);

    while (1 > 0) {

        // pull list of current messages (up to 10) in the queue
        List<Message> messages = whgHelper.getMessagesFromQueue(thisQueue, sqs);
        System.out.println("Count of messages in " + thisQueue + ": " + messages.size());

        try {

            for (Message message : messages) {

                whgHelper.printMessage(message);
                for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                    whgHelper.printMessageEntry(entry);
                }

                // Add an item to DynamoDB table
                Map<String, AttributeValue> item = whgHelper.newAlert(message.getBody());
                PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
                PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
                System.out.println();
                System.out.println("Result: " + putItemResult);

                // then send message to cache queue
                System.out.println("Sending messages to next queue.");
                sqs.sendMessage(new SendMessageRequest(nextQueue, message.getBody()));

                // delete message after sending to persist queue
                System.out.println("Deleting message from this queue.\n");
                String messageRecieptHandle = message.getReceiptHandle();
                sqs.deleteMessage(new DeleteMessageRequest(thisQueue, messageRecieptHandle));

            }
            Thread.sleep(20000); // do nothing for 2000 miliseconds (2 second)

        } catch (AmazonServiceException ase) {
            whgHelper.errorMessagesAse(ase);
        } catch (AmazonClientException ace) {
            whgHelper.errorMessagesAce(ace);
        }
    }
}

From source file:SQS.java

License:Open Source License

public SQS(PropertiesCredentials p) {
    AWSCredentials credentials = p;//from  w  ww .j av  a  2  s .  c om
    sqs = new AmazonSQSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usEast1);
    //System.out.println("Finish initializing sqs service");
}

From source file:SimpleQueueServiceMultiThread3.java

License:Open Source License

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

    /*/*w w w .  j av a  2s. c om*/
     * 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,clientConfig);
    sqs = new AmazonSQSClient(credentials);

    Region apSouthEast1 = Region.getRegion(Regions.AP_SOUTHEAST_1);
    sqs.setRegion(apSouthEast1);

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

    //Define thread pool size
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);

    //create a list to hold the Future object associated with Callable
    List<Future<Long>> list = new ArrayList<Future<Long>>();

    //Create Callable instance
    Callable<Long> callable = new SimpleQueueServiceMultiThread3();

    for (int i = 0; i < threadSize; i++) {

        //submit Callable tasks to be executed by thread pool
        Future<Long> future = executor.submit(callable);

        //add Future to the list, we can get return value using Future
        list.add(future);

    }

    for (Future<Long> fut : list) {

        try {
            // Future.get() waits for task to get completed
            System.out.println("Time difference : " + fut.get());

            long timeDiff = fut.get().longValue();

            totalTime = Long.valueOf(totalTime + timeDiff);

            if (timeDiff >= maxTime) {
                maxTime = timeDiff;
            }

            if (minTime == 0L && timeDiff >= minTime) {
                minTime = timeDiff;
                //}else if (timeDiff <= minTime && timeDiff != 0L) {
            } else if (timeDiff <= minTime) {
                minTime = timeDiff;
            }

        } catch (InterruptedException | ExecutionException e) {

            e.printStackTrace();

        }
    }

    if (totalTime >= 0L) {

        averageTime = totalTime / threadSize;

    }

    System.out.println("Total Time : " + Long.valueOf(totalTime).toString());
    System.out.println("Max Time : " + Long.valueOf(maxTime).toString());
    System.out.println("Min Time : " + Long.valueOf(minTime).toString());
    System.out.println("Average Time : " + Long.valueOf(averageTime).toString());

    //shut down the executor service now
    executor.shutdown();

}