Example usage for com.amazonaws AmazonServiceException getRequestId

List of usage examples for com.amazonaws AmazonServiceException getRequestId

Introduction

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

Prototype

public String getRequestId() 

Source Link

Document

Returns the AWS request ID that uniquely identifies the service request the caller made.

Usage

From source file:edu.utn.frba.grupo5303.serverenviolibre.services.NotificacionesPushService.java

@Override
public void enviarNotificacion(NotificacionPush notificacion) {
    try {/* w ww .j  a  v  a 2s . c o m*/
        logger.log(Level.INFO, "Enviando notificacion al snsId: {0}", notificacion.getGcmIdDestino());
        logger.log(Level.INFO, "Enviando notificacion de tipo: {0}", notificacion.getCodigo());
        PublishRequest publishRequest = new PublishRequest();
        Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes(
                attributesMap.get(plataforma));
        if (notificationAttributes != null && !notificationAttributes.isEmpty()) {
            publishRequest.setMessageAttributes(notificationAttributes);
        }
        publishRequest.setMessageStructure("json");
        // If the message attributes are not set in the requisite method,
        // notification is sent with default attributes
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put(plataforma.name(), notificacion.getMensajeDeNotificacion());
        String message = SampleMessageGenerator.jsonify(messageMap);

        // Create Platform Application. This corresponds to an app on a
        // platform.
        CreatePlatformApplicationResult platformApplicationResult = createPlatformApplication();

        // The Platform Application Arn can be used to uniquely identify the
        // Platform Application.
        String platformApplicationArn = platformApplicationResult.getPlatformApplicationArn();

        // Create an Endpoint. This corresponds to an app on a device.
        CreatePlatformEndpointResult platformEndpointResult = createPlatformEndpoint("CustomData",
                notificacion.getGcmIdDestino(), platformApplicationArn);

        // For direct publish to mobile end points, topicArn is not relevant.
        publishRequest.setTargetArn(platformEndpointResult.getEndpointArn());

        publishRequest.setMessage(message);
        snsClient.publish(publishRequest);
    } catch (AmazonServiceException ase) {
        logger.log(Level.SEVERE, "Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SNS, but was rejected with an error response for some reason.");
        logger.log(Level.SEVERE, "Error Message:    {0}", ase.getMessage());
        logger.log(Level.SEVERE, "HTTP Status Code: {0}", ase.getStatusCode());
        logger.log(Level.SEVERE, "AWS Error Code:   {0}", ase.getErrorCode());
        logger.log(Level.SEVERE, "Error Type:       {0}", ase.getErrorType());
        logger.log(Level.SEVERE, "Request ID:       {0}", ase.getRequestId());
    } catch (AmazonClientException ace) {
        logger.log(Level.SEVERE,
                "Caught an AmazonClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with SNS, such as not "
                        + "being able to access the network.");
        logger.log(Level.SEVERE, "Error Message: {0}", ace.getMessage());
    }
}

From source file:example.uploads3.UploadS3.java

License:Apache License

public static void main(String[] args) throws Exception {
    String uploadFileName = args[0];
    String bucketName = "haos3";
    String keyName = "test/byspark.txt";
    // Create a Java Spark Context.
    SparkConf conf = new SparkConf().setAppName("UploadS3");
    JavaSparkContext sc = new JavaSparkContext(conf);

    AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
    try {/* ww  w . j a v  a 2s  . c o m*/
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFileName);
        PutObjectRequest putRequest = new PutObjectRequest(bucketName, keyName, file);

        // Request server-side encryption.
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setServerSideEncryption("AES256");
        putRequest.setMetadata(objectMetadata);

        s3client.putObject(putRequest);

    } 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:exemplos.S3Sample.java

License:Open Source License

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

    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:fsi_admin.JAwsS3Conn.java

License:Open Source License

@SuppressWarnings("rawtypes")
private boolean subirArchivo(StringBuffer msj, AmazonS3 s3, String S3BUKT, String nombre, Vector archivos) {
    //System.out.println("AwsConn SubirArchivo:" + nombre + ":nombre");

    if (!archivos.isEmpty()) {
        FileItem actual = null;//from w  ww . ja  va 2  s  . c o m

        try {
            for (int i = 0; i < archivos.size(); i++) {
                InputStream inputStream = null;
                try {
                    actual = (FileItem) archivos.elementAt(i);
                    /////////////////////////////////////////////////////////
                    //Obtain the Content length of the Input stream for S3 header
                    InputStream is = actual.getInputStream();
                    byte[] contentBytes = IOUtils.toByteArray(is);

                    Long contentLength = Long.valueOf(contentBytes.length);

                    ObjectMetadata metadata = new ObjectMetadata();
                    metadata.setContentLength(contentLength);

                    //Reobtain the tmp uploaded file as input stream
                    inputStream = actual.getInputStream();

                    //Put the object in S3
                    //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-'));
                    //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-'));
                    s3.putObject(new PutObjectRequest(S3BUKT, nombre, inputStream, metadata));
                } finally {
                    if (inputStream != null)
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }
                ////////////////////////////////////////////////////////////
            }
            return true;
        } catch (AmazonServiceException ase) {
            ase.printStackTrace();
            msj.append("Error de AmazonServiceException al subir archivo a S3.<br>");
            msj.append("Mensaje: " + ase.getMessage() + "<br>");
            msj.append("Cdigo de Estatus HTTP: " + ase.getStatusCode() + "<br>");
            msj.append("Cdigo de Error AWS:   " + ase.getErrorCode() + "<br>");
            msj.append("Tipo de Error:       " + ase.getErrorType() + "<br>");
            msj.append("Request ID:       " + ase.getRequestId());
            return false;
        } catch (AmazonClientException ace) {
            ace.printStackTrace();
            msj.append("Error de AmazonClientException al subir archivo a S3.<br>");
            msj.append("Mensaje: " + ace.getMessage());
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            msj.append("Error de Entrada/Salida al subir archivo a S3: " + e.getMessage());
            return false;
        }

    } else {
        msj.append("Error al subir archivo a la nube: No se envi ningun archivo");
        return false;
    }
}

From source file:fsi_admin.JAwsS3Conn.java

License:Open Source License

private boolean eliminarArchivo(StringBuffer msj, AmazonS3 s3, String S3BUKT, String nombre) {
    //System.out.println("AwsConn EliminarArchivo:" + nombre + ":nombre");

    try {/*from w  w w  . j a  v  a2  s  .  com*/
        //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-'));
        //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-'));
        s3.deleteObject(S3BUKT, nombre);
        return true;
    } catch (AmazonServiceException ase) {
        ase.printStackTrace();
        msj.append("Error de AmazonServiceException al eliminar archivo de S3.<br>");
        msj.append("Mensaje: " + ase.getMessage() + "<br>");
        msj.append("Cdigo de Estatus HTTP: " + ase.getStatusCode() + "<br>");
        msj.append("Cdigo de Error AWS:   " + ase.getErrorCode() + "<br>");
        msj.append("Tipo de Error:       " + ase.getErrorType() + "<br>");
        msj.append("Request ID:       " + ase.getRequestId());
        return false;
    } catch (AmazonClientException ace) {
        ace.printStackTrace();
        msj.append("Error de AmazonClientException al eliminar archivo de S3.<br>");
        msj.append("Mensaje: " + ace.getMessage());
        return false;
    }

}

From source file:fsi_admin.JAwsS3Conn.java

License:Open Source License

private boolean descargarArchivo(HttpServletResponse response, StringBuffer msj, AmazonS3 s3, String S3BUKT,
        String nombre, String destino) {
    //System.out.println("AwsConn DescargarArchivo:" + nombre + ":nombre");

    try {//  w w  w. j a v a2  s.  co  m
        System.out.println("DESCARGA BUCKET: " + S3BUKT + " OBJETO: " + nombre);
        S3Object object = s3.getObject(new GetObjectRequest(S3BUKT, nombre));
        //out.println("Content-Type: "  + object.getObjectMetadata().getContentType());
        //System.out.println("Content-Type: "  + object.getObjectMetadata().getContentType());
        byte[] byteArray = IOUtils.toByteArray(object.getObjectContent());
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
        JBajarArchivo fd = new JBajarArchivo();
        fd.doDownload(response, getServletConfig().getServletContext(), bais,
                object.getObjectMetadata().getContentType(), byteArray.length, destino);
        System.out.println("Content-Length: " + object.getObjectMetadata().getContentLength() + " BA: "
                + byteArray.length);
        return true;
    } catch (AmazonServiceException ase) {
        ase.printStackTrace();
        msj.append("Error de AmazonServiceException al descargar archivo de S3.<br>");
        msj.append("Mensaje: " + ase.getMessage() + "<br>");
        msj.append("Cdigo de Estatus HTTP: " + ase.getStatusCode() + "<br>");
        msj.append("Cdigo de Error AWS:   " + ase.getErrorCode() + "<br>");
        msj.append("Tipo de Error:       " + ase.getErrorType() + "<br>");
        msj.append("Request ID:       " + ase.getRequestId());
        return false;
    } catch (AmazonClientException ace) {
        ace.printStackTrace();
        msj.append("Error de AmazonClientException al descargar archivo de S3.<br>");
        msj.append("Mensaje: " + ace.getMessage());
        return false;
    } catch (IOException ace) {
        ace.printStackTrace();
        msj.append("Error de IOException al descargar archivo de S3.<br>");
        msj.append("Mensaje: " + ace.getMessage());
        return false;
    }

}

From source file:getting_started.GettingStartedApp.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("===========================================");

    /*/*from w w  w .  ja  v a  2 s .c o m*/
     * Amazon EC2
     *
     * The AWS EC2 client allows you to create, delete, and administer
     * instances programmatically.
     *
     * In this sample, we use an EC2 client to submit a Spot request,
     * wait for it to reach the active state, and then cancel and terminate
     * the associated instance.
     */
    try {
        // Setup the helper object that will perform all of the API calls.
        Requests requests = new Requests();

        // Submit all of the requests.
        requests.submitRequests();

        // Loop through all of the requests until all bids are in the active state 
        // (or at least not in the open state).
        do {
            // Sleep for 60 seconds.
            Thread.sleep(SLEEP_CYCLE);
        } while (requests.areAnyOpen());

        // Cancel all requests and terminate all running instances.
        requests.cleanup();

    } catch (AmazonServiceException ase) {
        // Write out any exceptions that may have occurred.
        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:getting_started.InlineGettingStartedCodeSampleApp.java

License:Open Source License

/**
 * @param args/*ww w . ja v  a  2 s .  c o m*/
 */
public static void main(String[] args) {
    //============================================================================================//
    //=============================== Submitting a Request =======================================// 
    //============================================================================================//

    // Retrieves the credentials from an AWSCredentials.properties file.
    AWSCredentials credentials = null;
    try {
        credentials = new PropertiesCredentials(
                InlineGettingStartedCodeSampleApp.class.getResourceAsStream("AwsCredentials.properties"));
    } catch (IOException e1) {
        System.out.println("Credentials were not properly entered into AwsCredentials.properties.");
        System.out.println(e1.getMessage());
        System.exit(-1);
    }

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}

From source file:getting_started.SimpleQueueServiceSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*//from ww w  . jav a  2  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
     */
    AmazonSQS sqs = new AmazonSQSClient(new PropertiesCredentials(
            SimpleQueueServiceSample.class.getResourceAsStream("AwsCredentials.properties")));

    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 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:hu.cloud.edu.SimpleQueueServiceSample.java

License:Open Source License

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

    /*/*from w  ww  .  ja v  a  2s  .  c om*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (C:\\Users\\Isaac\\.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 (C:\\Users\\Isaac\\.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 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());
    }
}