Example usage for com.amazonaws AmazonServiceException getErrorCode

List of usage examples for com.amazonaws AmazonServiceException getErrorCode

Introduction

In this page you can find the example usage for com.amazonaws AmazonServiceException getErrorCode.

Prototype

public String getErrorCode() 

Source Link

Document

Returns the AWS error code represented by this exception.

Usage

From source file:AmazonDynamoDBPopulator.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//from  w  w  w .  j  a v a  2s .c  om

    try {
        //The methods below are commented but any of them will be used to refresh the AmazonDynamo DB database when the data changes.
        //New Data sets will be added in the same fashion.
        //populateDataVersions();
        //populateBloodBanks();
        //populateAutoFare();
        //populateTaxiFare();
        //populateHelplines();

        // SAMPLE SCAN FUNCTION - Scan items for bloodbanks in a particular area
        /*HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
        Condition condition = new Condition()
        .withComparisonOperator(ComparisonOperator.EQ.toString())
        .withAttributeValueList(new AttributeValue().withS("Parel"));
        scanFilter.put("AREA", condition);
        ScanRequest scanRequest = new ScanRequest(BLOODBANK_TABLENAME).withScanFilter(scanFilter);
        ScanResult scanResult = dynamoDB.scan(scanRequest);
        System.out.println("Result: " + scanResult);*/

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

From source file:SimpleDBSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*/*from w  w w  .  j a  v a2  s.  c o m*/
     * 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
     */
    AmazonSimpleDB sdb = new AmazonSimpleDBClient(
            new PropertiesCredentials(SimpleDBSample.class.getResourceAsStream("AwsCredentials.properties")));

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

    try {
        // Create a domain
        String myDomain = "MyStore";
        System.out.println("Creating domain called " + myDomain + ".\n");
        sdb.createDomain(new CreateDomainRequest(myDomain));

        // List domains
        System.out.println("Listing all domains in your account:\n");
        for (String domainName : sdb.listDomains().getDomainNames()) {
            System.out.println("  " + domainName);
        }
        System.out.println();

        // Put data into a domain
        System.out.println("Putting data into " + myDomain + " domain.\n");
        sdb.batchPutAttributes(new BatchPutAttributesRequest(myDomain, createSampleData()));

        // Select data from a domain
        // Notice the use of backticks around the domain name in our select expression.
        String selectExpression = "select * from `" + myDomain + "` where Category = 'Clothes'";
        System.out.println("Selecting: " + selectExpression + "\n");
        SelectRequest selectRequest = new SelectRequest(selectExpression);
        for (Item item : sdb.select(selectRequest).getItems()) {
            System.out.println("  Item");
            System.out.println("    Name: " + item.getName());
            for (Attribute attribute : item.getAttributes()) {
                System.out.println("      Attribute");
                System.out.println("        Name:  " + attribute.getName());
                System.out.println("        Value: " + attribute.getValue());
            }
        }
        System.out.println();

        // Delete values from an attribute
        System.out.println("Deleting Blue attributes in Item_O3.\n");
        Attribute deleteValueAttribute = new Attribute("Color", "Blue");
        sdb.deleteAttributes(
                new DeleteAttributesRequest(myDomain, "Item_03").withAttributes(deleteValueAttribute));

        // Delete an attribute and all of its values
        System.out.println("Deleting attribute Year in Item_O3.\n");
        sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03")
                .withAttributes(new Attribute().withName("Year")));

        // Replace an attribute
        System.out.println("Replacing Size of Item_03 with Medium.\n");
        List<ReplaceableAttribute> replaceableAttributes = new ArrayList<ReplaceableAttribute>();
        replaceableAttributes.add(new ReplaceableAttribute("Size", "Medium", true));
        sdb.putAttributes(new PutAttributesRequest(myDomain, "Item_03", replaceableAttributes));

        // Delete an item and all of its attributes
        System.out.println("Deleting Item_03.\n");
        sdb.deleteAttributes(new DeleteAttributesRequest(myDomain, "Item_03"));

        // Delete a domain
        System.out.println("Deleting " + myDomain + " domain.\n");
        sdb.deleteDomain(new DeleteDomainRequest(myDomain));
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SimpleDB, 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 SimpleDB, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:AwsSample.java

License:Open Source License

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

    BasicAWSCredentials credentials = new BasicAWSCredentials("", "");

    /*********************************************
     * //www  . j av  a 2 s . c  om
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);

    try {

        /*********************************************
         * 
          *  #2 Describe Availability Zones.
          *  
          *********************************************/
        System.out.println("#2 Describe Availability Zones.");
        DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
        System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                + " Availability Zones.");

        /*********************************************
         * 
         *  #3 Describe Available Images
         *  
         *********************************************/
        System.out.println("#3 Describe Available Images");
        DescribeImagesResult dir = ec2.describeImages();
        List<Image> images = dir.getImages();
        System.out.println("You have " + images.size() + " Amazon images");

        /*********************************************
         *                 
         *  #4 Describe Key Pair
         *                 
         *********************************************/
        System.out.println("#9 Describe Key Pair");
        DescribeKeyPairsResult dkr = ec2.describeKeyPairs();
        System.out.println(dkr.toString());

        /*********************************************
         * 
         *  #5 Describe Current Instances
         *  
         *********************************************/
        System.out.println("#4 Describe Current Instances");
        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        Set<Instance> instances = new HashSet<Instance>();
        // add all instances to a Set.
        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s).");
        for (Instance ins : instances) {

            // instance id
            String instanceId = ins.getInstanceId();

            // instance state
            InstanceState is = ins.getState();
            System.out.println(instanceId + " " + is.getName());
        }
        ///////////////////////////////////////

        String Temp_Group = "Testgroup1"; //name of the group
        CreateSecurityGroupRequest r1 = new CreateSecurityGroupRequest(Temp_Group, "temporal group");
        ec2.createSecurityGroup(r1);
        AuthorizeSecurityGroupIngressRequest r2 = new AuthorizeSecurityGroupIngressRequest();
        r2.setGroupName(Temp_Group);

        /*************the property of http*****************/
        IpPermission permission = new IpPermission();
        permission.setIpProtocol("tcp");
        permission.setFromPort(80);
        permission.setToPort(80);
        List<String> ipRanges = new ArrayList<String>();
        ipRanges.add("0.0.0.0/0");
        permission.setIpRanges(ipRanges);

        /*************the property of SSH**********************/
        IpPermission permission1 = new IpPermission();
        permission1.setIpProtocol("tcp");
        permission1.setFromPort(22);
        permission1.setToPort(22);
        List<String> ipRanges1 = new ArrayList<String>();
        ipRanges1.add("0.0.0.0/22");
        permission1.setIpRanges(ipRanges1);

        /*************the property of https**********************/
        IpPermission permission2 = new IpPermission();
        permission2.setIpProtocol("tcp");
        permission2.setFromPort(443);
        permission2.setToPort(443);
        List<String> ipRanges2 = new ArrayList<String>();
        ipRanges2.add("0.0.0.0/0");
        permission2.setIpRanges(ipRanges2);

        /*************the property of tcp**********************/
        IpPermission permission3 = new IpPermission();
        permission3.setIpProtocol("tcp");
        permission3.setFromPort(0);
        permission3.setToPort(65535);
        List<String> ipRanges3 = new ArrayList<String>();
        ipRanges3.add("0.0.0.0/0");
        permission3.setIpRanges(ipRanges3);

        /**********************add rules to the group*********************/
        List<IpPermission> permissions = new ArrayList<IpPermission>();
        permissions.add(permission);
        permissions.add(permission1);
        permissions.add(permission2);
        permissions.add(permission3);
        r2.setIpPermissions(permissions);

        ec2.authorizeSecurityGroupIngress(r2);
        List<String> groupName = new ArrayList<String>();
        groupName.add(Temp_Group);//wait to out our instance into this group

        /*********************************************
        *
        *  #6.2 Create a New Key Pair
        * 
        *********************************************/

        CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest();
        newKeyRequest.setKeyName("Test_Key2");
        CreateKeyPairResult keyresult = ec2.createKeyPair(newKeyRequest);

        /************************print the properties of this key*****************/
        KeyPair kp = new KeyPair();

        kp = keyresult.getKeyPair();
        System.out.println("The key we created is = " + kp.getKeyName() + "\nIts fingerprint is="
                + kp.getKeyFingerprint() + "\nIts material is= \n" + kp.getKeyMaterial());

        String fileName = "C:/Users/Akhil/workspace/Test_Key2.pem";
        File distFile = new File(fileName);
        BufferedReader bufferedReader = new BufferedReader(new StringReader(kp.getKeyMaterial()));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(distFile));
        char buf[] = new char[1024];
        int len;
        while ((len = bufferedReader.read(buf)) != -1) {
            bufferedWriter.write(buf, 0, len);
        }
        bufferedWriter.flush();
        bufferedReader.close();
        bufferedWriter.close();
        //String myinstance; 
        /*********************************************
          * 
          *  #6 Create an Instance
          *  
          *********************************************/
        System.out.println("#5 Create an Instance");
        String imageId = "ami-76f0061f"; //Basic 32-bit Amazon Linux AMI
        int minInstanceCount = 1; // create 1 instance
        int maxInstanceCount = 1;
        RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        rir.setKeyName("Test_Key2");
        rir.withSecurityGroups("Testgroup1");

        RunInstancesResult result = ec2.runInstances(rir);

        //get instanceId from the result
        List<Instance> resultInstance = result.getReservation().getInstances();
        String createdInstanceId = null;
        String myAvailabilityZone = null;
        for (Instance ins : resultInstance) {
            createdInstanceId = ins.getInstanceId();
            System.out.println("New instance has been created: " + ins.getInstanceId());
            //myinstance = ins.getInstanceId();

        }

        Thread.currentThread().sleep(60000);

        /*********************************************
         * 
         * 
         * Create a New Volume and attach it
         * 
         ***********************************************/

        List<Instance> resultInstance2 = result.getReservation().getInstances();

        createdInstanceId = null;
        for (Instance ins : resultInstance2) {

            createdInstanceId = ins.getInstanceId();
            System.out.println("New instance has been created: " + ins.getInstanceId());//print the instance ID

            /*********************************************
              * 
              *  #6.4 Create an Instance
              *  
              *********************************************/

            CreateVolumeRequest newVol = new CreateVolumeRequest(1, "us-east-1a");

            CreateVolumeResult volresult = ec2.createVolume(newVol);
            Volume vol1 = volresult.getVolume();
            String volId = vol1.getVolumeId();
            Thread.currentThread().sleep(30000);

            AttachVolumeRequest attachRequest = new AttachVolumeRequest().withInstanceId(createdInstanceId)
                    .withVolumeId(volId);
            attachRequest.withDevice("/dev/sda5");
            ec2.attachVolume(attachRequest);

            System.out.println("EBS volume has been attached and the volume ID is: " + volId);
        }
        /*********************************************
         * 
         *  #7 Create a 'tag' for the new instance.
         *  
         *********************************************/
        System.out.println("#6 Create a 'tag' for the new instance.");
        List<String> resources = new LinkedList<String>();
        List<Tag> tags = new LinkedList<Tag>();
        Tag nameTag = new Tag("Akhil", "MyFirstInstance");

        resources.add(createdInstanceId);
        tags.add(nameTag);

        CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
        ec2.createTags(ctr);

        /*********************************************
         * 
         *  #8 Stop/Start an Instance
         *  
         *********************************************/
        System.out.println("#7 Stop the Instance");
        List<String> instanceIds = new LinkedList<String>();
        instanceIds.add(createdInstanceId);

        //stop
        StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
        ec2.stopInstances(stopIR);

        //start
        StartInstancesRequest startIR = new StartInstancesRequest(instanceIds);
        ec2.startInstances(startIR);

        System.out.println("#8 Getting DNS, IP.");

        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setInstanceIds(instanceIds);

        DescribeInstancesResult result1 = ec2.describeInstances(request);
        List<Reservation> reservations1 = result1.getReservations();

        List<Instance> instances1;
        for (Reservation res : reservations1) {
            instances1 = res.getInstances();
            for (Instance ins1 : instances1) {
                System.out
                        .println("The public DNS is: " + ins1.getPublicDnsName() + "\n" + ins1.getRamdiskId());
                System.out.println("The private IP is: " + ins1.getPrivateIpAddress());
                System.out.println("The public IP is: " + ins1.getPublicIpAddress());

            }

            /*********************************************
                     
                    
              *  #10 Terminate an Instance
              *  
              *********************************************/
            System.out.println("#8 Terminate the Instance");
            TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);
            //ec2.terminateInstances(tir);

            /*********************************************
             *  
             *  #11 shutdown client object
             *  
             *********************************************/
            ec2.shutdown();

        }
    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}

From source file:AwsConsoleApp.java

License:Open Source License

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

    System.out.println("===========================================");
    System.out.println("Welcome to the AWS Java SDK!");
    System.out.println("===========================================");

    init();/* ww w.ja  va  2s .  c  om*/

    /*
     * Amazon EC2
     *
     * The AWS EC2 client allows you to create, delete, and administer
     * instances programmatically.
     *
     * In this sample, we use an EC2 client to get a list of all the
     * availability zones, and all instances sorted by reservation id.
     */
    try {
        DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
        System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                + " Availability Zones.");

        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        Set<Instance> instances = new HashSet<Instance>();

        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

    /*
     * Amazon SimpleDB
     *
     * The AWS SimpleDB client allows you to query and manage your data
     * stored in SimpleDB domains (similar to tables in a relational DB).
     *
     * In this sample, we use a SimpleDB client to iterate over all the
     * domains owned by the current user, and add up the number of items
     * (similar to rows of data in a relational DB) in each domain.
     */
    try {
        ListDomainsRequest sdbRequest = new ListDomainsRequest().withMaxNumberOfDomains(100);
        ListDomainsResult sdbResult = sdb.listDomains(sdbRequest);

        int totalItems = 0;
        for (String domainName : sdbResult.getDomainNames()) {
            DomainMetadataRequest metadataRequest = new DomainMetadataRequest().withDomainName(domainName);
            DomainMetadataResult domainMetadata = sdb.domainMetadata(metadataRequest);
            totalItems += domainMetadata.getItemCount();
        }

        System.out.println("You have " + sdbResult.getDomainNames().size() + " Amazon SimpleDB domain(s)"
                + "containing a total of " + totalItems + " items.");
    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

    /*
     * Amazon S3
     *
     * The AWS S3 client allows you to manage buckets and programmatically
     * put and get objects to those buckets.
     *
     * In this sample, we use an S3 client to iterate over all the buckets
     * owned by the current user, and all the object metadata in each
     * bucket, to obtain a total object and space usage count. This is done
     * without ever actually downloading a single object -- the requests
     * work with object metadata only.
     */
    try {
        List<Bucket> buckets = s3.listBuckets();

        long totalSize = 0;
        int totalItems = 0;
        for (Bucket bucket : buckets) {
            /*
             * In order to save bandwidth, an S3 object listing does not
             * contain every object in the bucket; after a certain point the
             * S3ObjectListing is truncated, and further pages must be
             * obtained with the AmazonS3Client.listNextBatchOfObjects()
             * method.
             */
            ObjectListing objects = s3.listObjects(bucket.getName());
            do {
                for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                    totalSize += objectSummary.getSize();
                    totalItems++;
                }
                objects = s3.listNextBatchOfObjects(objects);
            } while (objects.isTruncated());
        }

        System.out.println("You have " + buckets.size() + " Amazon S3 bucket(s), " + "containing " + totalItems
                + " objects with a total size of " + totalSize + " bytes.");
    } catch (AmazonServiceException ase) {
        /*
         * AmazonServiceExceptions represent an error response from an AWS
         * services, i.e. your request made it to AWS, but the AWS service
         * either found it invalid or encountered an error trying to execute
         * it.
         */
        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) {
        /*
         * AmazonClientExceptions represent an error that occurred inside
         * the client on the local host, either while trying to send the
         * request to AWS or interpret the response. For example, if no
         * network connection is available, the client won't be able to
         * connect to AWS to execute a request and will throw an
         * AmazonClientException.
         */
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*// w w  w.ja v  a 2  s  . co m
     * 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
     */
    AmazonS3 s3 = new AmazonS3Client(
            new PropertiesCredentials(S3Sample.class.getResourceAsStream("AwsCredentials.properties")));

    String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    String key = "MyObjectKey";

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

    try {
        /*
         * Create a new S3 bucket - Amazon S3 bucket names are globally unique,
         * so once a bucket name has been taken by any user, you can't create
         * another bucket with that same name.
         *
         * You can optionally specify a location for your bucket if you want to
         * keep your data closer to your applications or users.
         */
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        /*
         * Upload an object to your bucket - You can easily upload a file to
         * S3, or upload directly an InputStream if you know the length of
         * the data in the stream. You can also specify your own metadata
         * when uploading to S3, which allows you set a variety of options
         * like content-type and content-encoding, plus additional metadata
         * specific to your applications.
         */
        System.out.println("Uploading a new object to S3 from a file\n");
        s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        /*
         * Download an object - When you download an object, you get all of
         * the object's metadata and a stream from which to read the contents.
         * It's important to read the contents of the stream as quickly as
         * possibly since the data is streamed directly from Amazon S3 and your
         * network connection will remain open until you read all the data or
         * close the input stream.
         *
         * GetObjectRequest also supports several other options, including
         * conditional downloading of objects based on modification times,
         * ETags, and selectively downloading a range of an object.
         */
        System.out.println("Downloading an object");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        /*
         * List objects in your bucket by prefix - There are many options for
         * listing the objects in your bucket.  Keep in mind that buckets with
         * many objects might truncate their results when listing their objects,
         * so be sure to check if the returned object listing is truncated, and
         * use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
         * additional results.
         */
        System.out.println("Listing objects");
        ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();

        /*
         * Delete an object - Unless versioning has been turned on for your bucket,
         * there is no way to undelete an object, so use caution when deleting objects.
         */
        System.out.println("Deleting an object\n");
        s3.deleteObject(bucketName, key);

        /*
         * Delete a bucket - A bucket must be completely empty before it can be
         * deleted, so remember to delete any objects from your buckets before
         * you try to delete them.
         */
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon S3, 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 S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:AmazonKinesisFirehoseToS3Sample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();/*from   ww w  .ja v a2s. c  o m*/

    try {
        // Create S3 bucket for deliveryStream to deliver data
        createS3Bucket();

        // Create the DeliveryStream
        createDeliveryStream();

        // Print the list of delivery streams
        printDeliveryStreams();

        // Put records into deliveryStream
        LOG.info("Putting records in deliveryStream : " + deliveryStreamName + " via Put Record method.");
        putRecordIntoDeliveryStream();

        // Batch Put records into deliveryStream
        LOG.info("Putting records in deliveryStream : " + deliveryStreamName
                + " via Put Record Batch method. Now you can check your S3 bucket " + s3BucketName
                + " for the data delivered by deliveryStream.");
        putRecordBatchIntoDeliveryStream();

        // Wait for some interval for the firehose to write data to the S3 bucket
        int waitTimeSecs = s3DestinationIntervalInSeconds == null ? DEFAULT_WAIT_INTERVAL_FOR_DATA_DELIVERY_SECS
                : s3DestinationIntervalInSeconds;
        waitForDataDelivery(waitTimeSecs);

        // Update the deliveryStream and Put records into updated deliveryStream, only if the flag is set
        if (enableUpdateDestination) {
            // Update the deliveryStream
            updateDeliveryStream();

            // Wait for some interval to propagate the updated configuration options before ingesting data
            LOG.info("Waiting for few seconds to propagate the updated configuration options.");
            TimeUnit.SECONDS.sleep(60);

            // Put records into updated deliveryStream. Records will be delivered to new S3 prefix location
            LOG.info("Putting records in updated deliveryStream : " + deliveryStreamName
                    + " via Put Record method.");
            putRecordIntoDeliveryStream();

            // Batch Put records into updated deliveryStream. Records will be delivered to new S3 prefix location
            LOG.info("Putting records in updated deliveryStream : " + deliveryStreamName
                    + " via Put Record Batch method.");
            putRecordBatchIntoDeliveryStream();

            // Wait for some interval for the deliveryStream to write data to new prefix location in S3 bucket
            waitTimeSecs = updateIntervalInSeconds == null ? waitTimeSecs : updateIntervalInSeconds;
            waitForDataDelivery(waitTimeSecs);
        }
    } catch (AmazonServiceException ase) {
        LOG.error("Caught Amazon Service Exception");
        LOG.error("Status Code " + ase.getErrorCode());
        LOG.error("Message: " + ase.getErrorMessage(), ase);
    } catch (AmazonClientException ace) {
        LOG.error("Caught Amazon Client Exception");
        LOG.error("Exception Message " + ace.getMessage(), ace);
    }
}

From source file:HW1.java

License:Open Source License

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

    AWSCredentials credentials = new PropertiesCredentials(
            HW1.class.getResourceAsStream("AwsCredentials.properties"));

    /*********************************************
     * //from ww w . java  2 s. co m
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);
    ec2.setEndpoint("https://us-east-1.ec2.amazonaws.com");

    System.out.println("Please enter required group name and key name... (consider them to be the same)");
    Scanner scan = new Scanner(System.in);
    final String keyGroupName = scan.nextLine();

    /* create security group */
    CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest();
    createSecurityGroupRequest.withGroupName(keyGroupName).withDescription("My Java Security Group");
    CreateSecurityGroupResult createSecurityGroupResult = ec2.createSecurityGroup(createSecurityGroupRequest);

    /* set ip settings */
    IpPermission ipPermission = new IpPermission();
    /* authorize tcp, ssh 22 */
    ipPermission.withIpRanges("0.0.0.0/0").withIpProtocol("tcp").withFromPort(22)
            /* authorize http 80 */
            .withToPort(80);

    AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();
    authorizeSecurityGroupIngressRequest.withGroupName(keyGroupName).withIpPermissions(ipPermission);
    ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    /* create key pair */
    CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();
    createKeyPairRequest.withKeyName(keyGroupName);
    CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);
    KeyPair keyPair = new KeyPair();
    keyPair = createKeyPairResult.getKeyPair();
    String privateKey = keyPair.getKeyMaterial();
    PrintWriter file = new PrintWriter("/Users/will/.ssh/" + keyGroupName + ".pem");
    file.print(privateKey);
    file.close();
    Runtime.getRuntime().exec("chmod 400 /Users/will/.ssh/" + keyGroupName + ".pem");

    try {

        /*********************************************
         * 
         *  #2 Create two Instances
         *  
         *********************************************/
        System.out.println();
        System.out.println("#2 Create two new Instances");
        int ready_num = 0;
        String insDNS1 = new String();
        String insDNS2 = new String();
        String insId1 = new String();
        String insId2 = new String();
        String insZone1 = new String();
        String insZone2 = new String();

        String imageId = "ami-76f0061f"; //Basic 32-bit Amazon Linux AMI
        int minInstanceCount = 2; // create 2 instance
        int maxInstanceCount = 2;

        /* create instances */
        RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        rir.withKeyName(keyGroupName).withSecurityGroups(keyGroupName);
        ec2.runInstances(rir);

        /* waiting for instance to start */
        System.out.println("Created instance, wait for pending...");

        DescribeInstancesResult describeInstancesRequest;
        List<Reservation> reservations;
        List<Instance> allInstances = new ArrayList<Instance>();

        while (ready_num < 2) {
            describeInstancesRequest = ec2.describeInstances();
            reservations = describeInstancesRequest.getReservations();
            for (Reservation reservation : reservations) {
                for (Instance ins : reservation.getInstances()) {
                    if (ins.getState().getName().compareTo("running") == 0
                            && ins.getPublicIpAddress() != null) {
                        if (allInstances.size() == 0 || (allInstances.size() > 0
                                && allInstances.get(0).getInstanceId().compareTo(ins.getInstanceId()) != 0)) {
                            ready_num++;
                            allInstances.add(ins);
                        }
                    }
                }
            }
        }

        System.out.println("You have " + allInstances.size() + " Amazon EC2 instance(s).");
        insId1 = allInstances.get(0).getInstanceId();
        insId2 = allInstances.get(1).getInstanceId();
        insDNS1 = allInstances.get(0).getPublicIpAddress();
        insDNS2 = allInstances.get(1).getPublicIpAddress();
        insZone1 = allInstances.get(0).getPlacement().getAvailabilityZone();
        insZone2 = allInstances.get(1).getPlacement().getAvailabilityZone();

        for (Instance ins : allInstances) {
            System.out.println("New instance has been created: " + ins.getInstanceId());
        }

        System.out.println("Both instances are running now:");
        System.out.println("Instance id1: " + insId1);
        System.out.println("IP: " + insDNS1);
        System.out.println("Zone: " + insZone1);
        System.out.println("Instance id1: " + insId2);
        System.out.println("IP: " + insDNS2);
        System.out.println("Zone: " + insZone2);
        System.out.println();

        /*********************************************
         *  #3 Check OR Create two volumes
         *********************************************/
        System.out.println();
        System.out.println("#3 Create volumes");
        String volume_name1 = createVolume(insZone1, null);
        String volume_name2 = createVolume(insZone2, null);

        /*********************************************
         *  #4 Attach the volume to the instance
         *********************************************/
        System.out.println();
        System.out.println("#4 Attach the volume to the instance");
        System.out.println("Wait for volumes to be available...");
        Thread.sleep(20000);

        /* attach instances to existing volume */
        attachVolume(insId1, volume_name1);
        attachVolume(insId2, volume_name2);

        /************************************************
        *  #5 S3 bucket and object
        ***************************************************/
        System.out.println();
        System.out.println("#5 S3 bucket and object");
        s3 = new AmazonS3Client(credentials);

        /* create bucket */
        String bucketName = "cloud-hw1-bucket";
        s3.createBucket(bucketName);

        /* set key */
        String key = "object-hw1.txt";

        /* set value */
        File new_file = File.createTempFile("temp", ".txt");
        new_file.deleteOnExit();
        Writer writer = new OutputStreamWriter(new FileOutputStream(new_file));
        writer.write("This is the file stored on the S3 storage on the first day!!!.");
        writer.close();

        /* put object - bucket, key, value(file) */
        s3.putObject(new PutObjectRequest(bucketName, key, new_file));
        System.out.println("Successfully put file temp.txt to S3, we will read it tomorrow...");
        System.out.println();

        /***********************************
        *   #3 Monitoring (CloudWatch)
        *********************************/
        System.out.println();
        System.out.println("#6 set up cloudwatch");
        try {
            /* create CloudWatch client */
            AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(credentials);
            /* create request message1 */
            GetMetricStatisticsRequest statRequest1 = new GetMetricStatisticsRequest();
            GetMetricStatisticsRequest statRequest2 = new GetMetricStatisticsRequest();
            /* set up request message */
            statRequest1.setNamespace("AWS/EC2"); //namespace
            statRequest2.setNamespace("AWS/EC2"); //namespace
            statRequest1.setPeriod(60); //period of data
            statRequest2.setPeriod(60); //period of data
            ArrayList<String> stats = new ArrayList<String>();
            /* Use one of these strings: Average, Maximum, Minimum, SampleCount, Sum */
            stats.add("Average");
            stats.add("Sum");
            statRequest1.setStatistics(stats);
            statRequest2.setStatistics(stats);
            /* Use one of these strings: CPUUtilization, NetworkIn, NetworkOut, DiskReadBytes, DiskWriteBytes, DiskReadOperations  */
            statRequest1.setMetricName("CPUUtilization");
            statRequest2.setMetricName("CPUUtilization");
            /* set time */
            GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // 1 second ago
            Date endTime = calendar.getTime();
            calendar.add(GregorianCalendar.MINUTE, -10); // 10 minutes ago
            Date startTime = calendar.getTime();
            statRequest1.setStartTime(startTime);
            statRequest1.setEndTime(endTime);
            statRequest2.setStartTime(startTime);
            statRequest2.setEndTime(endTime);
            /* specify an instance */
            ArrayList<Dimension> dimensions1 = new ArrayList<Dimension>();
            dimensions1.add(new Dimension().withName("InstanceId").withValue(insId1));
            ArrayList<Dimension> dimensions2 = new ArrayList<Dimension>();
            dimensions2.add(new Dimension().withName("InstanceId").withValue(insId2));
            statRequest1.setDimensions(dimensions1);
            statRequest2.setDimensions(dimensions2);
            System.out.println("Set up cloud watch for instance: " + insId1 + " and instance: " + insId2);

            /* !!!!!!!!!!!!here set for 10 loops for now */
            /* get statistics */
            for (int i = 0; i < 10; i++) {
                GetMetricStatisticsResult statResult1 = cloudWatch.getMetricStatistics(statRequest1);
                GetMetricStatisticsResult statResult2 = cloudWatch.getMetricStatistics(statRequest2);
                /* display */
                System.out.println("Instance 1: " + statResult1.toString());
                List<Datapoint> dataList = statResult1.getDatapoints();
                Double averageCPU = null;
                Date timeStamp = null;
                for (Datapoint d : dataList) {
                    averageCPU = d.getAverage();
                    timeStamp = d.getTimestamp();
                    System.out
                            .println("Instance 1 average CPU utlilization for last 10 minutes: " + averageCPU);
                    System.out.println("Instance 1 total CPU utlilization for last 10 minutes: " + d.getSum());
                }
                System.out.println();
                System.out.println("Instance 2: " + statResult1.toString());
                dataList = statResult2.getDatapoints();
                for (Datapoint d : dataList) {
                    averageCPU = d.getAverage();
                    timeStamp = d.getTimestamp();
                    System.out
                            .println("Instance 2 average CPU utlilization for last 10 minutes: " + averageCPU);
                    System.out.println("Instance 2 total CPU utlilization for last 10 minutes: " + d.getSum());
                }
            }

        } catch (AmazonServiceException ase) {
            System.out.println("Caught Exception: " + ase.getMessage());
            System.out.println("Reponse Status Code: " + ase.getStatusCode());
            System.out.println("Error Code: " + ase.getErrorCode());
            System.out.println("Request ID: " + ase.getRequestId());
        }

        /***********************************
        *   # Copy script to 
        *       instance and run
        *********************************/
        System.out.println();
        System.out.println("Waiting for init and automatically SSH...");
        /* call runtime exec to run scp */
        execCmdRuby(insDNS1, keyGroupName);

        /***********************************
        *   # Save instances to image
        *********************************/
        System.out.println();
        System.out.println("******* Approaching 5:00 pm, create ami for instances *********");
        String imageId1;
        String imageId2;
        String snapshot1;
        String snapshot2;

        imageId1 = createAmiFromInstance(insId1, "image1", true);
        imageId2 = createAmiFromInstance(insId2, "image2", true);
        System.out.println("Created first image id: " + imageId1);
        System.out.println("Created second image id: " + imageId2);

        snapshot1 = createSnapShotFromVolume(volume_name1);
        snapshot2 = createSnapShotFromVolume(volume_name2);
        System.out.println("Created first snapshot id: " + snapshot1);
        System.out.println("Created second snapshot id: " + snapshot2);

        /*********************************************
         * 
         *  # Stop Instances
         *  
         *********************************************/
        System.out.println();
        System.out.println("#7 Stop & terminate the Instance");
        List<String> instanceIds = new LinkedList<String>();
        instanceIds.add(insId1);
        instanceIds.add(insId2);
        /* stop instances */
        StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
        ec2.stopInstances(stopIR);
        TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);
        ec2.terminateInstances(tir);

        /*********************************************
         * 
         *  # Detach volumes
         *  
         *********************************************/
        System.out.println();
        System.out.println("Detach the volumes from the instances...");
        deatchVolume(insId1, volume_name1);
        deatchVolume(insId2, volume_name2);

        /*********************************************
          * 
          *  # Delete Volumes
          *  
          *********************************************/
        System.out.println();

        while (true) {
            if (getVolumeState(volume_name1).compareTo("available") == 0
                    && getVolumeState(volume_name2).compareTo("available") == 0)
                break;
        }
        System.out.println("Delete volumes...");
        Thread.sleep(10000);
        deleteVolume(volume_name1);
        deleteVolume(volume_name2);

        /*********************************************
          * 
          *  # Second day restore instances and volumes
          *  
          *********************************************/
        System.out.println();
        System.out.println("#8 Second day start up instances from stored amis...");
        String newInsId1 = "";
        String newInsId2 = "";
        String newInsIP1 = "";
        String newInsIP2 = "";
        String newInsZone1 = "";
        String newInsZone2 = "";

        newInsId1 = createInstanceFromImageId(imageId1, keyGroupName);
        newInsId2 = createInstanceFromImageId(imageId2, keyGroupName);
        System.out.println("Second day first instance has been restored with id: " + newInsId1);
        System.out.println("Second day second instance has been restored with id: " + newInsId2);
        newInsZone1 = getInstanceZone(newInsId1);
        newInsZone2 = getInstanceZone(newInsId2);
        System.out.println("New instance 1 zone: " + newInsZone1);
        System.out.println("New instance 2 zone: " + newInsZone2);
        newInsIP1 = getInstanceIP(newInsId1);
        newInsIP2 = getInstanceIP(newInsId2);
        System.out.println("New instance 1 IP: " + newInsIP1);
        System.out.println("New instance 2 IP: " + newInsIP2);

        Thread.sleep(120000);
        /* exec read */
        System.out.println();
        System.out.println("Now start to read the file stored yesterday...");
        execCmdRead(newInsIP1, keyGroupName);

        /*********************************************
         *  
         *  #9 Read data from S3
         *  
         *********************************************/

        /* get the object from the first day */
        System.out.println();
        System.out.println("#9 Reading data from S3 stored on the first day");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent()));
        String data = null;
        while ((data = reader.readLine()) != null) {
            System.out.println(data);
        }

        /*********************************************
         *  
         *  #10 shutdown client object
         *  
         *********************************************/
        System.out.println("#10 shutdown client objects");
        ec2.shutdown();
        s3.shutdown();

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}

From source file:AmazonDynamoDBSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//  w  w  w.  j  av  a  2  s.  c o m

    try {
        String tableName = "storyTable";

        // Create table if it does not exist yet
        if (Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is already ACTIVE");
        } else {
            // Create a table with a primary hash key named 'name', which holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                    .withKeySchema(
                            new KeySchemaElement().withAttributeName("storyID").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("storyID")
                            .withAttributeType(ScalarAttributeType.N))
                    .withProvisionedThroughput(
                            new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
            TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest)
                    .getTableDescription();
            System.out.println("Created Table: " + createdTableDescription);

            // Wait for it to become active
            System.out.println("Waiting for " + tableName + " to become ACTIVE...");
            Tables.awaitTableToBecomeActive(dynamoDB, tableName);
        }

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);
        Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
        System.out.println(currentTimestamp);
        ByteBuffer b = createBody();
        int id1 = 1;
        int id2 = 2;
        double d1 = 0;
        double d2 = 1;
        Timestamp inputTimestamp = currentTimestamp;
        // Add an item
        Map<String, AttributeValue> item = newItem(id1, "JAM", "This is JAM", b, inputTimestamp, inputTimestamp,
                d1, d2);
        System.out.println("here");

        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        System.out.println("here2");
        System.out.println(item);
        System.out.println(putItemRequest);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("here3");
        System.out.println("Result: " + putItemResult);

        // Add another item
        item = newItem(id2, "JAM2", "This is JAM2", b, inputTimestamp, inputTimestamp, d1, d2);
        putItemRequest = new PutItemRequest(tableName, item);
        putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Scan items for movies with a year attribute greater than 1985
        //            HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
        //            Condition condition = new Condition()
        //                .withComparisonOperator(ComparisonOperator.GT)
        //                .withAttributeValueList(new AttributeValue());
        //            scanFilter.put("year", condition);
        //            ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
        //            ScanResult scanResult = dynamoDB.scan(scanRequest);
        //            System.out.println("Result: " + scanResult);

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

From source file:TweetSQS.java

License:Open Source License

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

    /*//from 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
     * ().
     */
    AWSCredentials credentials = null;
    try {
        credentials = new PropertiesCredentials(
                TweetSQS.class.getResourceAsStream("AwsCredentials.properties"));
    } 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/aohong/.aws/credentials), and is in valid format.", e);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    sqs.setRegion(usEast1);

    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("MyQueue");
        String myQueueUrl = sqs.createQueue(createQueueRequest).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 first message text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        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:virtualIT.java

License:Open Source License

public static void main(String[] args) throws Exception {
    AWSCredentials credentials = new PropertiesCredentials(
            virtualIT.class.getResourceAsStream("AwsCredentials.properties"));
    int intialCounter = 0;
    int s;// w  ww. j  a  v  a2s .co  m
    virtualIT vIT = new virtualIT();
    /*********************************************
     * 
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);
    db = new AmazonDynamoDBClient(credentials);
    cloudWatch = new AmazonCloudWatchClient(credentials);
    autoScaleClient = new AmazonAutoScalingClient(credentials);
    vIT.deleteAutoScalingGroup(12345);
    try {
        System.out.println("Starting Virtual System Admin \n");
        System.out.println("Enter no of users want to login\n");
        Scanner getInput = new Scanner(System.in);
        s = getInput.nextInt();
        if (s != 0) {
            for (int j = 0; j < s; j++) {
                System.out.println("Enter UserId:\n");
                int getUserId = getInput.nextInt();
                if (getUserId != 0) {
                    vIT.userIds.add(getUserId);
                    vIT.StartUpGroup(getUserId);
                    vIT.cloudWatchMonitor(getUserId);
                }
            }

            Calendar cal = Calendar.getInstance();
            Date time = cal.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

            vIT.currentHour = (sdf.format(Calendar.HOUR));
            System.out.println(sdf.format(Calendar.HOUR));
            /****
             * Entering Continuous Loop
             */
            for (int i = 0; i < vIT.userIds.size(); i++) {

                int userId = vIT.userIds.get(i);
                double cpu = vIT.mapUserCpu.get(userId);
                tempMin = cal.getTime();

                while (vIT.currentHour.equals(stopTime) || cpu < 5)
                    ;
                {

                    vIT.cloudWatchMonitor(userId);

                    /****************
                     * Entering Time end Group Keeps on looping 
                     */
                    vIT.TimeEndGroup();
                }
            }

        }
        /*********************************************
         * 
          *  #2 Describe Availability Zones.
          *  
          *********************************************/
        /*System.out.println("#2 Describe Availability Zones.");
         DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
         System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() +
                 " Availability Zones.");*/

        /*********************************************
         * 
         *  #3 Describe Available Images
         *  
         *********************************************/
        /*System.out.println("#3 Describe Available Images");
        DescribeImagesResult dir = ec2.describeImages();
        List<Image> images = dir.getImages();
        System.out.println("You have " + images.size() + " Amazon images");*/

        /*********************************************
         *                 
         *  #4 Describe Key Pair
         *                 
         *********************************************/
        /* System.out.println("#9 Describe Key Pair");
         DescribeKeyPairsResult dkr = ec2.describeKeyPairs();
         System.out.println(dkr.toString());*/

        /*********************************************
         * 
         *  #5 Describe Current Instances
         *  
         *********************************************/
        /* System.out.println("#4 Describe Current Instances");
         DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
         List<Reservation> reservations = describeInstancesRequest.getReservations();
         Set<Instance> instances = new HashSet<Instance>();
         // add all instances to a Set.
         for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
         }
                 
         System.out.println("You have " + instances.size() + " Amazon EC2 instance(s).");
         for (Instance ins : instances){
                    
            // instance id
            String instanceId = ins.getInstanceId();
                    
            // instance state
            InstanceState is = ins.getState();
            System.out.println(instanceId+" "+is.getName());
        //    System.out.println("Key for the instance  "+keyName);
         }*/

        // Thread.currentThread().sleep(100000);

        //get instanceId from the result

        /*  List<Instance> resultInstance = result.getReservation().getInstances();
          String createdInstanceId = null;
          for (Instance ins : resultInstance){   
             createdInstanceId = ins.getInstanceId();
             System.out.println("New instance has been created: "+ins.getInstanceId());
          }
          describeInstancesRequest = ec2.describeInstances();
          reservations = describeInstancesRequest.getReservations();
          int k = reservations.size();
          Reservation totalReservations = reservations.get(k-1);
          Instance getFirstInstance = totalReservations.getInstances().get(0);
                 
          System.out.println("The private IP is: "+getFirstInstance.getPrivateIpAddress());
          System.out.println("The public IP is: "+getFirstInstance.getPublicIpAddress());*/

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}