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:org.juneja.eventdemo.utils.AmazonSimpleQueueService.java

License:Open Source License

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

    /*//from   w  w  w. ja v  a 2 s.co  m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (~/.aws/credentials), and is in valid format.", e);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.DEFAULT_REGION);
    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("TestQueue_EventDriven_2");
        // String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

        GetQueueUrlResult queueResult = sqs.getQueueUrl("TestQueue_EventDriven_2");
        String myQueueUrl = queueResult.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 new text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();

        System.out.println("Number of messages : " + messages.size());

        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:org.mobicents.servlet.restcomm.amazonS3.S3AccessTool.java

License:Open Source License

public URI uploadFile(final String fileToUpload) {
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, securityKey);
    AmazonS3 s3client = new AmazonS3Client(credentials);
    try {//from  www .  ja v  a 2  s  .  c  o  m
        StringBuffer bucket = new StringBuffer();
        bucket.append(bucketName);
        if (folder != null && !folder.isEmpty())
            bucket.append("/").append(folder);
        URI fileUri = URI.create(fileToUpload);
        logger.info("File to upload to S3: " + fileUri.toString());
        File file = new File(fileUri);
        //            while (!file.exists()){}
        //            logger.info("File exist: "+file.exists());
        //First generate the Presigned URL, buy some time for the file to be written on the disk
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if (daysToRetainPublicUrl > 0) {
            cal.add(Calendar.DATE, daysToRetainPublicUrl);
        } else {
            //By default the Public URL will be valid for 180 days
            cal.add(Calendar.DATE, 180);
        }
        date = cal.getTime();
        GeneratePresignedUrlRequest generatePresignedUrlRequestGET = new GeneratePresignedUrlRequest(
                bucket.toString(), file.getName());
        generatePresignedUrlRequestGET.setMethod(HttpMethod.GET);
        generatePresignedUrlRequestGET.setExpiration(date);

        URL downloadUrl = s3client.generatePresignedUrl(generatePresignedUrlRequestGET);

        //Second upload the file to S3
        //            while (!file.exists()){}
        while (!FileUtils.waitFor(file, 30)) {
        }
        if (file.exists()) {
            PutObjectRequest putRequest = new PutObjectRequest(bucket.toString(), file.getName(), file);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(new MimetypesFileTypeMap().getContentType(file));
            putRequest.setMetadata(metadata);
            if (reducedRedundancy)
                putRequest.setStorageClass(StorageClass.ReducedRedundancy);
            s3client.putObject(putRequest);

            if (removeOriginalFile) {
                removeLocalFile(file);
            }
            return downloadUrl.toURI();
        } else {
            logger.error("Timeout waiting for the recording file: " + file.getAbsolutePath());
            return null;
        }
    } catch (AmazonServiceException ase) {
        logger.error("Caught an AmazonServiceException");
        logger.error("Error Message:    " + ase.getMessage());
        logger.error("HTTP Status Code: " + ase.getStatusCode());
        logger.error("AWS Error Code:   " + ase.getErrorCode());
        logger.error("Error Type:       " + ase.getErrorType());
        logger.error("Request ID:       " + ase.getRequestId());
        return null;
    } catch (AmazonClientException ace) {
        logger.error("Caught an AmazonClientException, which ");
        logger.error("Error Message: " + ace.getMessage());
        return null;
    } catch (URISyntaxException e) {
        logger.error("URISyntaxException: " + e.getMessage());
        return null;
    }
}

From source file:org.nuxeo.aws.elastictranscoder.GenericAWSClient.java

License:Open Source License

/**
 * Utility method returning formatted details about the error. It the error
 * is not AmazonServiceException or AmazonClientException, the method just
 * returns <code>e.getMessage()</code>
 *
 * @param e, an AmazonServiceException or AmazonClientException
 * @return/* w w w .  java  2  s. c o m*/
 *
 * @since 7.1
 */
public static String buildDetailedMessageFromAWSException(Exception e) {

    String message = "";

    if (e instanceof AmazonServiceException) {
        AmazonServiceException ase = (AmazonServiceException) e;
        message = "Caught an AmazonServiceException, which " + "means your request made it "
                + "to Amazon S3, but was rejected with an error response" + " for some reason.";
        message += "\nError Message:    " + ase.getMessage();
        message += "\nHTTP Status Code: " + ase.getStatusCode();
        message += "\nAWS Error Code:   " + ase.getErrorCode();
        message += "\nError Type:       " + ase.getErrorType();
        message += "\nRequest ID:       " + ase.getRequestId();

    } else if (e instanceof AmazonClientException) {
        AmazonClientException ace = (AmazonClientException) e;
        message = "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.";
        message += "\nError Message: " + ace.getMessage();

    } else {
        message = e.getMessage();
    }

    return message;
}

From source file:org.openflamingo.fs.s3.S3ObjectProvider.java

License:Apache License

@Override
public boolean copy(String from, String to) {
    //        Assert.hasLength(from, " ?? ?  'from'?  .");
    Assert.hasLength(from, "Please enter the source path.");
    //        Assert.hasLength(to, " ?  'to'  .");
    Assert.hasLength(to, "Please enter the destination path.");

    String fromBucket = S3Utils.getBucket(from);
    String toBucket = S3Utils.getBucket(to);
    String fromKey = StringUtils.remove(from, "/" + fromBucket + "/");
    String toKey = S3Utils.getObjectKey(to);
    String fileName = getFileName(fromKey);

    try {//from  www.  j a  va  2s .c  om
        CopyObjectRequest copyObjectRequest = new CopyObjectRequest(fromBucket, fromKey, toBucket,
                toKey + fileName);
        awsClient.copyObject(copyObjectRequest);
        return true;
    } 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());

        //            throw new FileSystemException("??    . ? ? ? .", ase);
        throw new FileSystemException("Cannot copy the file.", ase);
    } 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());
        //            throw new FileSystemException("??    . ? ? ? .", ace);
        throw new FileSystemException("Cannot copy the file.", ace);
    }
}

From source file:org.openflamingo.fs.s3.S3ObjectProvider.java

License:Apache License

public boolean save(InputStream is, long size, String path) {
    //        Assert.notNull(is, " ??   'is'?  .");
    Assert.notNull(is, "Please enter the input stream.");
    //        Assert.hasLength(path, "??  ? ??  'path'?  .");
    Assert.hasLength(path, "Please enter the path.");

    try {/*from ww w.  j a v a  2 s .co m*/
        String bucket = S3Utils.getBucket(path);
        String key = StringUtils.remove(path, "/" + bucket + "/");
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setHeader(Headers.CONTENT_LENGTH, size);
        awsClient.putObject(new PutObjectRequest(bucket, key, is, metadata));
        return true;
    } 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());

        //            throw new FileSystemException("??    . ? ? ? .", ase);
        throw new FileSystemException("Connot copy the file.", ase);
    } 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());

        //            throw new FileSystemException("??   . ? ? ?.", ace);
        throw new FileSystemException("Connot copy the file.", ace);
    }
}

From source file:org.openinfinity.cloud.service.administrator.EC2Wrapper.java

License:Apache License

public Reservation createInstance(String amiId, Integer amount, String keyName, String zone,
        String instanceType, List<String> securityGroups) {
    Reservation reservation = null;// ww  w .  j a va  2  s. c  om
    try {

        Integer minimumAmount = amount;
        Integer maximumAmount = amount;
        if (amiId == null) {
            return null;
        }
        String myAmiId = null;

        myAmiId = amiId;

        RunInstancesRequest runInstancesRequest = new RunInstancesRequest(myAmiId, minimumAmount,
                maximumAmount);
        runInstancesRequest.setKeyName(keyName);
        Placement placement = new Placement();
        placement.setAvailabilityZone(zone);
        runInstancesRequest.setPlacement(placement);
        runInstancesRequest.setSecurityGroups(securityGroups);
        if (instanceType != null) {
            runInstancesRequest.setInstanceType(instanceType);
        }
        RunInstancesResult result = ec2.runInstances(runInstancesRequest);
        reservation = result.getReservation();

    } catch (AmazonServiceException ase) {
        String message = ase.getMessage();
        LOG.error("Caught Exception: " + message);
        LOG.error("Response Status Code: " + ase.getStatusCode());
        LOG.error("Error Code: " + ase.getErrorCode());
        LOG.error("Request ID: " + ase.getRequestId());
        ExceptionUtil.throwSystemException(message, ase);
    } catch (AmazonClientException e) {

        e.printStackTrace();
        ExceptionUtil.throwSystemException(e.getMessage(), e);
    }

    return reservation;
}

From source file:org.p365.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*/*from  w  ww .j a v a2s  .  c  o m*/
     * 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 = "mynewbuket";
    String key = "Myobj/sd.jpg";

    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");
        if (!s3.doesBucketExist(bucketName)) {
            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");
        String pathname = "D:\\Program Files\\apache-tomcat-7.0.42\\webapps\\WorkerForP365\\src\\AAA_1465.jpg";
        File file = new File(pathname);
        s3.putObject(
                new PutObjectRequest(bucketName, key, file).withCannedAcl(CannedAccessControlList.PublicRead));

        /*
         * 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:org.restcomm.connect.commons.amazonS3.S3AccessTool.java

License:Open Source License

public URI uploadFile(final String fileToUpload) {
    if (s3client == null) {
        s3client = getS3client();/*from  w ww. j  av a 2s . co  m*/
    }
    if (logger.isInfoEnabled()) {
        logger.info("S3 Region: " + bucketRegion.toString());
    }
    try {
        if (testing && (!testingUrl.isEmpty() || !testingUrl.equals(""))) {
            //                s3client.setEndpoint(testingUrl);
            //                s3client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
            FileUtils.touch(new File(URI.create(fileToUpload)));
        }
        StringBuffer bucket = new StringBuffer();
        bucket.append(bucketName);
        if (folder != null && !folder.isEmpty())
            bucket.append("/").append(folder);
        URI fileUri = URI.create(fileToUpload);
        if (logger.isInfoEnabled()) {
            logger.info("File to upload to S3: " + fileUri.toString());
        }
        File file = new File(fileUri);

        while (!FileUtils.waitFor(file, 30)) {
        }
        if (file.exists()) {
            PutObjectRequest putRequest = new PutObjectRequest(bucket.toString(), file.getName(), file);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(new MimetypesFileTypeMap().getContentType(file));
            putRequest.setMetadata(metadata);
            if (reducedRedundancy)
                putRequest.setStorageClass(StorageClass.ReducedRedundancy);
            s3client.putObject(putRequest);

            if (removeOriginalFile) {
                removeLocalFile(file);
            }
            URI recordingS3Uri = s3client.getUrl(bucket.toString(), file.getName()).toURI();
            return recordingS3Uri;
            //                return downloadUrl.toURI();
        } else {
            logger.error("Timeout waiting for the recording file: " + file.getAbsolutePath());
            return null;
        }
    } catch (AmazonServiceException ase) {
        logger.error("Caught an AmazonServiceException");
        logger.error("Error Message:    " + ase.getMessage());
        logger.error("HTTP Status Code: " + ase.getStatusCode());
        logger.error("AWS Error Code:   " + ase.getErrorCode());
        logger.error("Error Type:       " + ase.getErrorType());
        logger.error("Request ID:       " + ase.getRequestId());
        return null;
    } catch (AmazonClientException ace) {
        logger.error("Caught an AmazonClientException ");
        logger.error("Error Message: " + ace.getMessage());
        return null;
    } catch (URISyntaxException e) {
        logger.error("URISyntaxException: " + e.getMessage());
        return null;
    } catch (IOException e) {
        logger.error("Problem while trying to touch recording file for testing", e);
        return null;
    }
}

From source file:org.selman.tweetamo.PersistentStore.java

License:Apache License

private void handleException(Exception e) throws Exception {
    if (e instanceof AmazonServiceException) {
        AmazonServiceException ase = (AmazonServiceException) e;
        LOG.error("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.", e);
        LOG.error("Error Message:    " + ase.getMessage());
        LOG.error("HTTP Status Code: " + ase.getStatusCode());
        LOG.error("AWS Error Code:   " + ase.getErrorCode());
        LOG.error("Error Type:       " + ase.getErrorType());
        LOG.error("Request ID:       " + ase.getRequestId());
    } else if (e instanceof AmazonClientException) {
        AmazonClientException ace = (AmazonClientException) e;
        LOG.error("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.", e);
        LOG.error("Error Message: " + ace.getMessage());
    }//from   w w  w  .  j  a  va  2s .co  m

    throw e;
}

From source file:org.symphonyoss.vb.util.AwsS3Client.java

License:Apache License

/**
 * Provide a list of objects from a given bucket w/prefix (folder).
 *
 * @param bucketName S3 bucket name/*  w ww.ja  va 2 s .c o  m*/
 * @param prefix     S3 folder within the bucket
 * @return List of {@link S3ObjectSummary} sorted by date
 */
public List<S3ObjectSummary> getAllObjects(String bucketName, String prefix) {

    try {
        logger.debug("Listing S3 objects for s3://{}/{}", bucketName, prefix);
        final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName)
                .withPrefix(prefix);
        ListObjectsV2Result result;
        List<S3ObjectSummary> allObjects = new ArrayList<>();

        do {
            result = s3Client.listObjectsV2(req);

            allObjects.addAll(result.getObjectSummaries());

            req.setContinuationToken(result.getNextContinuationToken());
        } while (result.isTruncated());

        allObjects.sort(Comparator.comparing(S3ObjectSummary::getLastModified));

        return allObjects;
    } catch (AmazonServiceException ase) {
        logger.error("Caught an AmazonServiceException, " + "which means your request made it "
                + "to Amazon S3, but was rejected with an error response " + "for some reason.");
        logger.error("Error Message:    " + ase.getMessage());
        logger.error("HTTP Status Code: " + ase.getStatusCode());
        logger.error("AWS Error Code:   " + ase.getErrorCode());
        logger.error("Error Type:       " + ase.getErrorType());
        logger.error("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        logger.error("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.");
        logger.error("Error Message: " + ace.getMessage());
    }

    return null;
}