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:cs.iit.edu.ckmr.worker.TableCreator.java

License:Open Source License

public void initializeTable(long readCapacity, long writeCapacity) {

    try {/*from  ww  w.j  ava2 s  . co m*/
        String tableName = "messages";

        ListTablesResult listTableResult = new ListTablesResult();
        listTableResult = dynamoDB.listTables();
        List<String> tableNames = listTableResult.getTableNames();
        if (!tableNames.contains(tableName)) {
            createTable(readCapacity, writeCapacity, tableName);
        }

    } 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:cs.iit.edu.ckmr.worker.TableCreator.java

License:Open Source License

private void waitForTableToBecomeAvailable(String tableName) {
    System.out.println("Waiting for " + tableName + " to become ACTIVE...");

    long startTime = System.currentTimeMillis();
    long endTime = startTime + (10 * 60 * 1000);
    while (System.currentTimeMillis() < endTime) {
        try {//from w ww.  j a v a  2s.co m
            Thread.sleep(1000 * 20);
        } catch (Exception e) {
        }
        try {
            DescribeTableRequest request = new DescribeTableRequest().withTableName(tableName);
            TableDescription tableDescription = dynamoDB.describeTable(request).getTable();
            String tableStatus = tableDescription.getTableStatus();
            System.out.println("  - current state: " + tableStatus);
            if (tableStatus.equals(TableStatus.ACTIVE.toString()))
                return;
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().equalsIgnoreCase("ResourceNotFoundException") == false)
                throw ase;
        }
    }

    throw new RuntimeException("Table " + tableName + " never went active");
}

From source file:cs.iit.edu.ckmr.worker.TableCreator.java

License:Open Source License

private void waitForTableToDelete(String tableName) {
    System.out.println("Waiting for " + tableName + " to become ACTIVE...");

    long startTime = System.currentTimeMillis();
    long endTime = startTime + (10 * 60 * 1000);
    while (System.currentTimeMillis() < endTime) {
        try {//from www.j ava2s. co m
            Thread.sleep(1000 * 20);
        } catch (Exception e) {
        }
        try {
            DescribeTableRequest request = new DescribeTableRequest().withTableName(tableName);
            TableDescription tableDescription = dynamoDB.describeTable(request).getTable();
            String tableStatus = tableDescription.getTableStatus();
            System.out.println("  - current state: " + tableStatus);
            if (tableStatus.equals(TableStatus.ACTIVE.toString()))
                return;
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().equalsIgnoreCase("ResourceNotFoundException") == false)
                throw ase;
        }
    }

    throw new RuntimeException("Table " + tableName + " never went active");
}

From source file:Database.CustomerData.java

License:Open Source License

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

    try {

        // 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 Idd 'Id', which holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                    .withKeySchema(new KeySchemaElement().withAttributeName("Id").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("Id")
                            .withAttributeType(ScalarAttributeType.S))
                    .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.waitForTableToBecomeActive(dynamoDB, tableName);

            // Describe our new table
            DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
            TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
            System.out.println("Table Description: " + tableDescription);

            // Add an item
            Map<String, AttributeValue> item = newItem("Nine Creatives on Creativity", "SQ_NS001", 2014,
                    "Squashouse", "Video");
            PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
            PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);

        }

    } 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:Database.ProductData.java

License:Open Source License

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

    try {
        String tableName = "CustomerData";

        // 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("name").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name")
                            .withAttributeType(ScalarAttributeType.S))
                    .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.waitForTableToBecomeActive(dynamoDB, tableName);
        }

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);

        // Add an item
        Map<String, AttributeValue> item = newItem("Nine Creatives on Creativity", "SQ_NS001", 2014,
                "Squashouse", "Video");
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        //            System.out.println("Result: " + putItemResult);

        uploadSampleProducts(tableName);

        //            System.out.println("Result: " +         aQueryResult.withItems(item));

        // 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.toString())
                .withAttributeValueList(new AttributeValue().withN("1985"));
        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:dataMappers.PictureDataMapper.java

public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request)
        throws FileUploadException, IOException, SQLException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        System.out.println("Invalid upload request");
        return;//from  ww  w  .  j  av a 2s .co  m
    }

    // Define limits for disk item
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);

    // Define limit for servlet upload
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    FileItem itemFile = null;
    int reportID = 0;

    // Get list of items in request (parameters, files etc.)
    List formItems = upload.parseRequest(request);
    Iterator iter = formItems.iterator();

    // Loop items
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            itemFile = item; // If not form field, must be item
        } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field
            try {
                System.out.println(item.getString());
                reportID = Integer.parseInt(item.getString());
            } catch (NumberFormatException e) {
                reportID = 0;
            }
        }
    }

    // This will be null if no fields were declared as image/upload.
    // Also, reportID must be > 0
    if (itemFile != null || reportID == 0) {

        try {

            // Create credentials from final vars
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);

            // Create client with credentials
            AmazonS3 s3client = new AmazonS3Client(awsCredentials);
            // Set region
            s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));

            // Set content length (size) of file
            ObjectMetadata om = new ObjectMetadata();
            om.setContentLength(itemFile.getSize());

            // Get extension for file
            String ext = FilenameUtils.getExtension(itemFile.getName());
            // Generate random filename
            String keyName = UUID.randomUUID().toString() + '.' + ext;

            // This is the actual upload command
            s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om));

            // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report.
            PreparedStatement stmt = dbconnector.getCon()
                    .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)");

            stmt.setInt(1, reportID);
            stmt.setString(2, keyName);

            stmt.executeUpdate();

            stmt.close();

        } 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 "
                    + "an internal error 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:dbs.Getfroms3.java

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

    AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.AP_SOUTH_1)
            .withCredentials(new AWSStaticCredentialsProvider(credentials)).build();
    //AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider("inhack2hire28"));
    try {/*from www  .j  a v  a 2 s.c o  m*/
        System.out.println("Downloading an object");
        S3Object s3object = s3Client.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + s3object.getObjectMetadata().getContentType());
        displayTextInputStream(s3object.getObjectContent());

        // Get a range of bytes from an object.

        GetObjectRequest rangeObjectRequest = new GetObjectRequest(bucketName, key);
        rangeObjectRequest.setRange(0, 10);
        S3Object objectPortion = s3Client.getObject(rangeObjectRequest);

        System.out.println("Printing bytes retrieved.");
        displayTextInputStream(objectPortion.getObjectContent());

    } 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 "
                + "an internal error 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:de.fischer.thotti.ec2.clients.EC2InternalClient.java

License:Apache License

/**
 * Handles an {@link AmazonServiceException} by logging the information
 * provided by Amazon AWS and turning the caught exception into
 * an {@link de.fischer.thotti.awscommon.AWSRemoteServiceException}.
 *///from  w w  w.j  av a  2 s. c  o  m
protected void handleAmazonServiceException(AmazonServiceException exception) throws AWSRemoteServiceException {
    if (logger.isErrorEnabled()) {
        String message = exception.getMessage();
        String code = exception.getErrorCode();
        AmazonServiceException.ErrorType type = exception.getErrorType();
        String requestId = exception.getRequestId();
        String service = exception.getServiceName();

        logger.error("Amazon AWS was not able to fullfil the last operation. "
                + "Error message = {}, error code = {}, error type = {}, " + "service = {}, requestID = {}",
                new Object[] { message, code, type, requestId, service });
    }

    throw new AWSRemoteServiceException(exception.getMessage());
}

From source file:DynamicProvisioning.Requests.java

License:Open Source License

public String waitUntilActiveandRunning(String request) throws InterruptedException {

    boolean isActive = false;
    boolean isRunning = false;
    List<Reservation> reservation = new ArrayList<Reservation>();
    List<Instance> ins = new ArrayList<Instance>();
    String instanceid = null;/*from  w w  w.  j a  v  a  2s.c  om*/
    String ipaddress = null;
    while (!isActive) {
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
        try {
            // Retrieve all of the requests we want to monitor.
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            for (SpotInstanceRequest describeResponse : describeResponses) {
                if (describeResponse.getSpotInstanceRequestId().equalsIgnoreCase(request)) {
                    if (describeResponse.getState().equals("active")) {
                        System.out.println(describeResponse.getSpotInstanceRequestId() + " is active");
                        isActive = true;
                        instanceid = describeResponse.getInstanceId();
                        DescribeInstancesRequest req = new DescribeInstancesRequest()
                                .withInstanceIds(instanceid);
                        DescribeInstancesResult k = ec2.describeInstances(req);
                        reservation = k.getReservations();
                        for (Reservation i : reservation) {
                            ins = i.getInstances();
                            for (Instance in : ins) {

                                if ((in.getInstanceId()).equals(instanceid)) {
                                    ipaddress = in.getPublicIpAddress();
                                    while (ipaddress == null) {
                                        Thread.currentThread().sleep(1000);
                                        ipaddress = in.getPublicIpAddress();

                                    }

                                }
                            }
                        }
                    }
                }

                else {
                    Thread.currentThread().sleep(1000);
                }

            }
        } catch (AmazonServiceException e) {
            // Print out the error.
            System.out.println("Error when calling describeSpotInstances");
            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());

            // 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.
        }
    }
    return ipaddress;
}

From source file:ecplugins.s3.S3Util.java

License:Apache License

public static void UploadObject(String bucketName, String key)
        throws AmazonClientException, AmazonServiceException, Exception {
    Properties props = TestUtils.getProperties();
    File file = new File(createFile());
    BasicAWSCredentials credentials = new BasicAWSCredentials(props.getProperty(StringConstants.ACCESS_ID),
            props.getProperty(StringConstants.SECRET_ACCESS_ID));

    // Create TransferManager
    TransferManager tx = new TransferManager(credentials);

    // Get S3 Client
    AmazonS3 s3 = tx.getAmazonS3Client();

    try {//from  w ww. j  ava  2s  .c o m
        System.out.println("Uploading a new object to S3 from a file\n");

        s3.putObject(new PutObjectRequest(bucketName, key, file));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException");
        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  an internal error while trying to such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }

}