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:services.SQSQueue.java

License:Open Source License

public String isExists(String QueueName) {
    try {//from w  w w . j a va 2  s .  c om
        System.out.println("connecting to existing SQS queue called " + QueueName + "\n");
        GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QueueName);
        this.queueUrl = this.sqs.getQueueUrl(getQueueUrlRequest).getQueueUrl();
    }

    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());
        this.queueUrl = null;
    }

    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());
        this.queueUrl = null;
    }

    return this.queueUrl;
}

From source file:services.SQSQueue.java

License:Open Source License

/**
 * This function sends message to queue.
 * @param msg the message to send/*from  w w  w . ja  v  a2s.c  o  m*/
 */
public int sendMsg(String msg) {
    try {
        System.out.println("Sending a message to " + QueueName + ".\n");
        sqs.sendMessage(new SendMessageRequest(queueUrl, msg));
        this.numberOfMsg++;
    }

    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("Org message" + this.QueueName + " m is " + msg);
        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());
        numberOfMsg--;
        return -1;
    }

    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());
        numberOfMsg--;
        return -1;
    }

    return 0;
}

From source file:services.SQSQueue.java

License:Open Source License

/**
 * This function delete the queue/*w ww  .  j a  va2s. c  om*/
 */
public void deleteQueue() {
    try {
        System.out.println("Deleting the test queue.\n");
        sqs.deleteQueue(new DeleteQueueRequest(queueUrl));
        this.queueUrl = "";
        this.numberOfMsg = 0;
    }

    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:servlet.FileUploadServlet.java

private void putInBucket(String fileName, String id) throws IOException {

    AWSCredentials awsCreds = new PropertiesCredentials(
            new File("/Users/paulamontojo/Desktop/AwsCredentials.properties"));
    AmazonS3 s3client = new AmazonS3Client(awsCreds);

    try {/*from   w  ww. j  a  va2 s .co  m*/
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFileName);
        s3client.putObject(new PutObjectRequest(bucketName, fileName, file));

        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName,
                fileName);
        generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.

        URL s = s3client.generatePresignedUrl(generatePresignedUrlRequest);
        insertUrl(s.toString(), id);
        System.out.println(s);

    } 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:servlet.FileUploadServlet.java

public void sqs(String msg) throws Exception {
    AWSCredentials awsCreds = new PropertiesCredentials(
            new File("/Users/paulamontojo/Desktop/AwsCredentials.properties"));

    AmazonSQS sqs = new AmazonSQSClient(awsCreds);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    sqs.setRegion(usWest2);/*from   w w w .  ja  v a  2 s. c o  m*/

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

    try {

        String myQueueUrl = "https://sqs.us-west-2.amazonaws.com/711690152696/MyQueue";

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

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

    } 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:sqs_examples.SimpleQueueServiceSample.java

License:Open Source License

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

    /*/* w  w  w. j  a v a2  s.  c o m*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (/Users/pmacharl/.aws/credentials).
     */
    AWSCredentials credentials = null;
    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/pmacharl/.aws/credentials), and is in valid format.", e);
    }

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

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

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called MyQueue.\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest("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 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 messageReceiptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));

        // 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:squash.booking.lambdas.core.OptimisticPersister.java

License:Apache License

@Override
public int put(String itemName, Optional<Integer> version, ReplaceableAttribute attribute) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The optimistic persister has not been initialised");
    }/*from   w  ww.j a  v a  2 s.  c om*/

    logger.log("About to add attrbutes to simpledb item: " + itemName);

    AmazonSimpleDB client = getSimpleDBClient();

    // Check the put will not take us over the maximum number of attributes:
    // N.B. if (replace == true) then this check could be over-eager, but not
    // worth refining it, since this effectively just alters the limit by one.
    ImmutablePair<Optional<Integer>, Set<Attribute>> versionedAttributes = get(itemName);

    if (versionedAttributes.left.isPresent()) {
        logger.log("Retrieved versioned attributes(Count: " + versionedAttributes.right.size()
                + ")  have version number: " + versionedAttributes.left.get());
    } else {
        // There should be no attributes in this case.
        logger.log("Retrieved versioned attributes(Count: " + versionedAttributes.right.size()
                + ") have no version number");
    }

    Boolean tooManyAttributes = versionedAttributes.right.size() >= maxNumberOfAttributes;
    if (tooManyAttributes && !attribute.getValue().startsWith("Inactive")) {
        // We allow puts to inactivate attributes even when on the limit -
        // otherwise we could never delete when we're on the limit.
        logger.log("Cannot create attribute - the maximum number of attributes already exists ("
                + maxNumberOfAttributes
                + ") so throwing a 'Database put failed - too many attributes' exception");
        throw new Exception("Database put failed - too many attributes");
    }

    // Do a conditional put - so we don't overwrite someone else's attributes
    UpdateCondition updateCondition = new UpdateCondition();
    updateCondition.setName(versionAttributeName);
    ReplaceableAttribute versionAttribute = new ReplaceableAttribute();
    versionAttribute.setName(versionAttributeName);
    versionAttribute.setReplace(true);
    // Update will proceed unless the version number has changed
    if (version.isPresent()) {
        // A version number attribute exists - so it should be unchanged
        updateCondition.setValue(Integer.toString(version.get()));
        // Bump up our version number attribute
        versionAttribute.setValue(Integer.toString(version.get() + 1));
    } else {
        // A version number attribute did not exist - so it still should not
        updateCondition.setExists(false);
        // Set initial value for our version number attribute
        versionAttribute.setValue("0");
    }

    List<ReplaceableAttribute> replaceableAttributes = new ArrayList<>();
    replaceableAttributes.add(versionAttribute);

    // Add the new attribute
    replaceableAttributes.add(attribute);

    PutAttributesRequest simpleDBPutRequest = new PutAttributesRequest(simpleDbDomainName, itemName,
            replaceableAttributes, updateCondition);

    try {
        client.putAttributes(simpleDBPutRequest);
    } catch (AmazonServiceException ase) {
        if (ase.getErrorCode().contains("ConditionalCheckFailed")) {
            // Someone else has mutated an attribute since we read them. This is
            // likely to be rare, and a retry should almost always succeed. However,
            // we leave it to clients of this class to retry the call if they wish,
            // as the new mutation may mean they no longer want to do the put.
            logger.log("Caught AmazonServiceException for ConditionalCheckFailed whilst creating"
                    + " attribute(s) so throwing as 'Database put failed' instead");
            throw new Exception("Database put failed - conditional check failed");
        }
        throw ase;
    }

    logger.log("Created attribute(s) in simpledb");

    return Integer.parseInt(versionAttribute.getValue());
}

From source file:squash.booking.lambdas.core.OptimisticPersister.java

License:Apache License

@Override
public void delete(String itemName, Attribute attribute) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The optimistic persister has not been initialised");
    }//from  w w  w .  j  a  v  a 2s.  c om

    logger.log("About to delete attribute from simpledb item: " + itemName);

    AmazonSimpleDB client = getSimpleDBClient();

    // We retry the delete if necessary if we get a
    // ConditionalCheckFailed exception, i.e. if someone else modifies the
    // database between us reading and writing it.
    RetryHelper.DoWithRetries(() -> {
        try {
            // Get existing attributes (and version number), via consistent
            // read:
            ImmutablePair<Optional<Integer>, Set<Attribute>> versionedAttributes = get(itemName);

            if (!versionedAttributes.left.isPresent()) {
                logger.log(
                        "A version number attribute did not exist - this means no attributes exist, so we have nothing to delete.");
                return null;
            }
            if (!versionedAttributes.right.contains(attribute)) {
                logger.log("The attribute did not exist - so we have nothing to delete.");
                return null;
            }

            // Since it seems impossible to update the version number while
            // deleting an attribute, we first mark the attribute as inactive,
            // and then delete it.
            ReplaceableAttribute inactiveAttribute = new ReplaceableAttribute();
            inactiveAttribute.setName(attribute.getName());
            inactiveAttribute.setValue("Inactive" + attribute.getValue());
            inactiveAttribute.setReplace(true);
            put(itemName, versionedAttributes.left, inactiveAttribute);

            // Now we can safely delete the attribute, as other readers will now
            // ignore it.
            UpdateCondition updateCondition = new UpdateCondition();
            updateCondition.setName(inactiveAttribute.getName());
            updateCondition.setValue(inactiveAttribute.getValue());
            // Update will proceed unless the attribute no longer exists
            updateCondition.setExists(true);

            Attribute attributeToDelete = new Attribute();
            attributeToDelete.setName(inactiveAttribute.getName());
            attributeToDelete.setValue(inactiveAttribute.getValue());
            List<Attribute> attributesToDelete = new ArrayList<>();
            attributesToDelete.add(attributeToDelete);
            DeleteAttributesRequest simpleDBDeleteRequest = new DeleteAttributesRequest(simpleDbDomainName,
                    itemName, attributesToDelete, updateCondition);
            client.deleteAttributes(simpleDBDeleteRequest);
            logger.log("Deleted attribute from simpledb");
            return null;
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().contains("AttributeDoesNotExist")) {
                // Case of trying to delete an attribute that no longer exists -
                // that's ok - it probably just means more than one person was
                // trying to delete the attribute at once. So swallow this
                // exception
                logger.log(
                        "Caught AmazonServiceException for AttributeDoesNotExist whilst deleting attribute so"
                                + " swallowing and continuing");
                return null;
            } else {
                throw ase;
            }
        }
    }, Exception.class, Optional.of("Database put failed - conditional check failed"), logger);
}

From source file:squash.deployment.lambdas.utils.ExceptionUtils.java

License:Apache License

/**
 *  Logs an AmazonServiceException to a lambda logger.
 *//*from  w w  w .j a v a2  s .  c  om*/
public static void logAmazonServiceException(AmazonServiceException ase, LambdaLogger logger) {
    logger.log("Caught an AmazonServiceException, which " + "means the request made it "
            + "to AWS, but was rejected with an error response " + "for some reason.");
    logger.log("Error Message:    " + ase.getMessage());
    logger.log("HTTP Status Code: " + ase.getStatusCode());
    logger.log("AWS Error Code:   " + ase.getErrorCode());
    logger.log("Error Type:       " + ase.getErrorType());
    logger.log("Request ID:       " + ase.getRequestId());
}

From source file:test1.SimpleQueueServiceSample.java

License:Open Source License

public static void getMessage(String msg, AmazonSQS sqs, String myQueueUrl) {
    try {/*from w  w  w . ja  va 2 s. c om*/
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, msg));

    } 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());
    }
}