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:ics.uci.edu.amazons3.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*//from w w w . ja  v  a  2s.com
     * 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
     */
    final AmazonS3 s3 = new AmazonS3Client(
            new BasicAWSCredentials("AKIAJTW5BOY6EXOGV2YQ", "PDcnFYIf9Hdo9GsKTEjLXretZ3yEg4mRCDQKjxu6"));

    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:ie.peternagy.jcrypto.module.config.S3ConfigHandler.java

License:Open Source License

@Override
public void validateConfig(Map config) {
    AWSCredentials credentials = new BasicAWSCredentials((String) config.get("access-key"),
            (String) config.get("secret-key"));
    AmazonS3 s3client = new AmazonS3Client(credentials);
    try {/* ww w . ja  v a  2  s  .c o  m*/
        System.out.println("S3 config validation...\n");
        s3client.doesBucketExist((String) config.get("bucket-name"));

        System.out.println("Valid configuration!\n");
    } 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:iit.edu.supadyay.s3.S3upload.java

public static boolean upload(String bucketName, String uploadFileName, String keyName)
        throws IOException, InterruptedException {

    //access = "AKIAJ2YSLRUZR5B3F5HQ";
    //secret = "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";
    //AWSCredentials credentials = new BasicAWSCredentials(access, secret);
    //AmazonS3 s3client = new AmazonS3Client(getCredentials());
    AmazonS3 s3client = new AmazonS3Client(new InstanceProfileCredentialsProvider());
    try {/*from w ww .  j ava 2  s  .c om*/
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFileName);
        System.out.println("I am before here\n");
        s3client.createBucket(bucketName);
        System.out.println("I am here\n");

        s3client.putObject(new PutObjectRequest(bucketName, keyName, file));
        s3client.setObjectAcl(bucketName, keyName, CannedAccessControlList.PublicReadWrite);

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

From source file:io.druid.storage.s3.S3TaskLogs.java

License:Apache License

@Override
public Optional<ByteSource> streamTaskLog(final String taskid, final long offset) throws IOException {
    final String taskKey = getTaskLogKey(taskid);

    try {//from  www  . j  av  a 2s  .c om
        final ObjectMetadata objectMetadata = service.getObjectMetadata(config.getS3Bucket(), taskKey);

        return Optional.of(new ByteSource() {
            @Override
            public InputStream openStream() throws IOException {
                try {
                    final long start;
                    final long end = objectMetadata.getContentLength() - 1;

                    if (offset > 0 && offset < objectMetadata.getContentLength()) {
                        start = offset;
                    } else if (offset < 0 && (-1 * offset) < objectMetadata.getContentLength()) {
                        start = objectMetadata.getContentLength() + offset;
                    } else {
                        start = 0;
                    }

                    final GetObjectRequest request = new GetObjectRequest(config.getS3Bucket(), taskKey)
                            .withMatchingETagConstraint(objectMetadata.getETag()).withRange(start, end);

                    return service.getObject(request).getObjectContent();
                } catch (AmazonServiceException e) {
                    throw new IOException(e);
                }
            }
        });
    } catch (AmazonS3Exception e) {
        if (404 == e.getStatusCode() || "NoSuchKey".equals(e.getErrorCode())
                || "NoSuchBucket".equals(e.getErrorCode())) {
            return Optional.absent();
        } else {
            throw new IOE(e, "Failed to stream logs from: %s", taskKey);
        }
    }
}

From source file:io.druid.storage.s3.S3Utils.java

License:Apache License

static boolean isServiceExceptionRecoverable(AmazonServiceException ex) {
    final boolean isIOException = ex.getCause() instanceof IOException;
    final boolean isTimeout = "RequestTimeout".equals(ex.getErrorCode());
    return isIOException || isTimeout;
}

From source file:io.fineo.client.auth.CognitoCredentialsProvider.java

License:Open Source License

/**
 * Starts a new session by getting short lived session credentials.
 *//*from w ww .  jav  a 2s  .  c om*/
protected void startSession() {

    // make sure we have an identityId. In the case of cognito identity,
    // the try catch will handle a deleted or corrupted id.
    // Developer authenticated won't throw amazon exceptions,
    // and for 2hop, it will be handled below, as the getId call
    // won't fail since it is set.
    try {
        token = identityProvider.refresh();
    } catch (ResourceNotFoundException rnfe) {
        // If the identity id or identity pool is non-existant, this is
        // thrown
        token = retryRefresh();
    } catch (AmazonServiceException ase) {
        // If it's a corrupt id, then a validation exception is thrown
        if (ase.getErrorCode().equals("ValidationException")) {
            token = retryRefresh();
        } else {
            throw ase;
        }
    }

    if (useEnhancedFlow) {
        populateCredentialsWithCognito(token);
    } else {
        populateCredentialsWithSts(token);
    }

}

From source file:io.fineo.client.auth.CognitoCredentialsProvider.java

License:Open Source License

/**
 * Gets the session credentials from Amazon Cognito.
 *//*from  ww  w.  ja  va  2  s  .c o  m*/
private void populateCredentialsWithCognito(String token) {

    // For Cognito-authenticated identities token will always be null, but
    // for developer-authenticated identities, refresh() may return a token
    // that the the developer backend has received from Cognito and we have
    // to send back in our request.
    Map<String, String> logins;
    if (token != null && !token.isEmpty()) {
        logins = new HashMap<String, String>();
        logins.put("cognito-identity.amazonaws.com", token);
    } else {
        logins = getLogins();
    }

    GetCredentialsForIdentityRequest request = new GetCredentialsForIdentityRequest()
            .withIdentityId(getIdentityId()).withLogins(logins).withCustomRoleArn(customRoleArn);

    GetCredentialsForIdentityResult result = null;

    try {
        result = cib.getCredentialsForIdentity(request);
    } catch (ResourceNotFoundException rnfe) {
        // If the identity id or identity pool is non-existant, this is
        // thrown
        result = retryGetCredentialsForIdentity();
    } catch (AmazonServiceException ase) {
        // If it's a corrupt id, then a validation exception is thrown
        if (ase.getErrorCode().equals("ValidationException")) {
            result = retryGetCredentialsForIdentity();
        } else {
            throw ase;
        }
    }

    com.amazonaws.services.cognitoidentity.model.Credentials credentials = result.getCredentials();
    sessionCredentials = new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretKey(),
            credentials.getSessionToken());
    sessionCredentialsExpiration = credentials.getExpiration();

    if (!result.getIdentityId().equals(getIdentityId())) {
        setIdentityId(result.getIdentityId());
    }

}

From source file:io.relution.jenkins.awssqs.util.ErrorType.java

License:Apache License

/**
 * Returns a value indicating whether the specified service exception has the specified error
 * code and HTTP status./*ww w. ja v  a 2 s.  c  o  m*/
 * @param e The {@link AmazonServiceException} to test.
 * @param errorCode The error code to match, can be {@code null}.
 * @param httpStatus The HTTP status to match. Use {@code -1} to match any HTTP status.
 * @return {@code true} if the specified exception has the specified error code and HTTP status;
 * otherwise, {@code false}.
 */
public static boolean is(final AmazonServiceException e, final String errorCode, final int httpStatus) {
    if (e == null) {
        return false;
    }

    if (errorCode != null && !StringUtils.equals(errorCode, e.getErrorCode())) {
        return false;
    }

    if (httpStatus != -1 && e.getStatusCode() != httpStatus) {
        return false;
    }

    return true;
}

From source file:io.robrose.hop.watermap.aws.DynamoGeoClient.java

License:Open Source License

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

    try {
        String tableName = "water-safe-locations-table";
        config = new GeoDataManagerConfiguration(dynamoDB, tableName);
        geoDataManager = new GeoDataManager(config);
        // 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();
             */
            //AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

            CreateTableRequest createTableRequest = GeoTableUtil.getCreateTableRequest(config);
            CreateTableResult createTableResult = dynamoDB.createTable(createTableRequest);
            System.out.println("Created Table: " + tableName);

            // 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);

        Map<String, String> m = new HashMap<>();
        m.put("lat", "51.5034070");
        m.put("lng", "-0.1275920");
        m.put("violationCode", "47");

        // request = new JSONObject(m);
        //try {
        //    putPoint(request);
        //}catch(JSONException f){
        //    System.out.println("Bad JSON");
        //}
        // Scan items for movies with a year attribute greater than 1985
        HashMap<String, Condition> scanFilter = new HashMap<>();
        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:io.starter.messaging.SNSMobilePush.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*/*from w w w .  j  av  a  2  s  . c  o  m*/
     * TODO: 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
     */

    String awsAccessKey = System.getProperty("AWS_ACCESS_KEY_ID"); // "YOUR_AWS_ACCESS_KEY";
    String awsSecretKey = System.getProperty("AWS_SECRET_KEY"); // "YOUR_AWS_SECRET_KEY";

    if (awsAccessKey == null)
        awsAccessKey = AWS_ACCESS_KEY;
    if (awsSecretKey == null)
        awsSecretKey = AWS_SECRET_KEY;

    AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);

    AmazonSNS sns = new AmazonSNSClient(
            new PropertiesCredentials(SNSMobilePush.class.getResourceAsStream("AwsCredentials.properties")));

    // AmazonSNS sns = new AmazonSNSClient(credentials);

    sns.setEndpoint("https://sns.us-west-2.amazonaws.com");
    System.out.println("===========================================\n");
    System.out.println("Initializing Communication with Amazon SNS");
    System.out.println("===========================================\n");
    try {
        SNSMobilePush sample = new SNSMobilePush(sns);
        /* TODO: Uncomment the services you wish to use. */
        // sample.starterAndroidAppNotification();
        // sample.starterKindleAppNotification();
        sample.starterAppleAppNotification();
        // sample.starterAppleSandboxAppNotification();
        // sample.starterBaiduAppNotification();
        // sample.starterWNSAppNotification();
        // sample.starterMPNSAppNotification();
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SNS, 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 SNS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}