Example usage for com.amazonaws AmazonServiceException getMessage

List of usage examples for com.amazonaws AmazonServiceException getMessage

Introduction

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

Prototype

@Override
    public String getMessage() 

Source Link

Usage

From source file:org.cto.VVS3Box.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*/*from  w  ww  .  j  a va2  s. 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 = "lior.test-" + 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:org.dspace.globus.S3Client.java

License:Open Source License

public String createObject(String metadata) {
    UUID key = UUID.randomUUID();
    try {//from w w w  . j a va 2 s . c o  m
        byte[] metadataBytes = metadata.getBytes("UTF-8");
        InputStream stream = new ByteArrayInputStream(metadataBytes);
        ObjectMetadata s3ObjectMeta = new ObjectMetadata();
        s3ObjectMeta.setContentLength(metadataBytes.length);
        s3Client.putObject(new PutObjectRequest(bucketName, key.toString(), stream, s3ObjectMeta));
        return key.toString();
    } catch (AmazonServiceException ase) {
        logger.error("AmazonServiceException: " + ase.getMessage());
    } catch (AmazonClientException ace) {
        logger.error("AmazonClientException: " + ace.getMessage());
    } catch (Exception e) {
        logger.error("Exception: " + e.getMessage());
    }
    return null;
}

From source file:org.dspace.globus.S3Client.java

License:Open Source License

public void deleteObject(String key) {
    try {//ww w  . j  a  v a2s  .  co m
        s3Client.deleteObject(bucketName, key);
    } catch (AmazonServiceException ase) {
        logger.error("AmazonServiceException: " + ase.getMessage());
    } catch (AmazonClientException ace) {
        logger.error("AmazonClientException: " + ace.getMessage());
    }
}

From source file:org.duracloud.common.queue.aws.SQSTaskQueue.java

License:Apache License

@Override
public void deleteTasks(Set<Task> tasks) throws TaskException {
    if (tasks.size() > 10) {
        throw new IllegalArgumentException("task set must contain 10 or fewer tasks");
    }//from   w  w  w .  ja  v a  2s .c  o m

    try {

        List<DeleteMessageBatchRequestEntry> entries = new ArrayList<>(tasks.size());

        for (Task task : tasks) {
            DeleteMessageBatchRequestEntry entry = new DeleteMessageBatchRequestEntry()
                    .withId(task.getProperty(MsgProp.MSG_ID.name()))
                    .withReceiptHandle(task.getProperty(MsgProp.RECEIPT_HANDLE.name()));
            entries.add(entry);
        }

        DeleteMessageBatchRequest request = new DeleteMessageBatchRequest().withQueueUrl(queueUrl)
                .withEntries(entries);
        DeleteMessageBatchResult result = sqsClient.deleteMessageBatch(request);
        List<BatchResultErrorEntry> failed = result.getFailed();
        if (failed != null && failed.size() > 0) {
            for (BatchResultErrorEntry error : failed) {
                log.info("failed to delete message: " + error);
            }
        }

        for (DeleteMessageBatchResultEntry entry : result.getSuccessful()) {
            log.info("successfully deleted {}", entry);
        }

    } catch (AmazonServiceException se) {
        log.error("failed to batch delete tasks " + tasks + ": " + se.getMessage(), se);

        throw new TaskException(se);
    }

}

From source file:org.duracloud.integration.durastore.storage.probe.ProbedS3StorageProvider.java

License:Apache License

public ProbedS3StorageProvider(String accessKey, String secretKey) throws StorageException {
    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
    try {/*w w w  .  ja  va 2  s  .c om*/
        probedCore = new ProbedRestS3Client(awsCredentials);
    } catch (AmazonServiceException e) {
        String err = "Could not create connection to S3 due to error: " + e.getMessage();
        throw new StorageException(err, e);
    }
    storageProvider = new S3StorageProvider(probedCore.s3Client, accessKey, null);
}

From source file:org.duracloud.s3storage.S3ProviderUtil.java

License:Apache License

private static AmazonS3 newS3Client(String accessKey, String secretKey, Region region) {
    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
    try {//w w w .  j a va2 s. c o m
        String awsRegion = null;
        if (region != null) {
            awsRegion = region.getName();
        } else {
            awsRegion = System.getProperty(AWS_REGION.name());
        }
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).withRegion(awsRegion)
                .build();
        return s3Client;
    } catch (AmazonServiceException e) {
        String err = "Could not create connection to Amazon S3 due " + "to error: " + e.getMessage();
        throw new StorageException(err, e, RETRY);
    }
}

From source file:org.duracloud.s3storage.S3ProviderUtil.java

License:Apache License

private static AmazonCloudFrontClient newAmazonCloudFrontClient(String accessKey, String secretKey) {
    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
    try {/*from w  ww  . j  a  v a2 s. co  m*/
        return new AmazonCloudFrontClient(awsCredentials);
    } catch (AmazonServiceException e) {
        String err = "Could not create connection to Amazon CloudFront " + "due to error: " + e.getMessage();
        throw new StorageException(err, e, RETRY);
    }
}

From source file:org.elasticdroid.model.CloudWatchMetricsModel.java

License:Open Source License

/**
 * Retrieve the list of metrics/*from w w  w  .  ja  v a  2  s.com*/
 * 
 * @return Either
 * <ul>
 *    <li>AmazonServiceException</li>
 *  <li>AmazonClientException</li>
 *  <li>List\<Metric\></li>
 * </ul>
 */
public Object retrieveMetricsList(Dimension... dimensions) {
    //the cloudwatch client to use
    AmazonCloudWatchClient cloudWatchClient = null;
    List<Metric> returnedMetrics = null;
    ArrayList<String> measureNames = new ArrayList<String>();
    ListMetricsRequest request = new ListMetricsRequest();

    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"),
            connectionData.get("secretAccessKey"));

    //create a cloudwatch client
    try {
        cloudWatchClient = new AmazonCloudWatchClient(credentials);
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not 
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    cloudWatchClient.setEndpoint(cloudWatchEndpoint);

    //create the request
    request = new ListMetricsRequest();
    //request.setNextToken(nextToken)
    try {
        returnedMetrics = cloudWatchClient.listMetrics().getMetrics();
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not 
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    //my own disgusting O(mnp) filter. This is REALLY CRAP!
    //remove all that does not fit into the dimension
    //for some reason, there isn't a way to provide dimensions using ListMetricsRequest in Java
    //you can do it in the C# API though :P
    List<Dimension> returnedDimensions;
    boolean added;
    for (Metric metric : returnedMetrics) {
        returnedDimensions = metric.getDimensions();
        added = false;
        for (Dimension returnedDimension : returnedDimensions) {
            //check if any of the dimensions passed in to the model are equal to this.
            for (Dimension dimension : dimensions) {
                if (returnedDimension.getValue().equals(dimension.getValue())) {
                    measureNames.add(metric.getMeasureName());
                    added = true;
                    break;
                }
            }

            if (added) {
                break;
            }
        }
    }

    return measureNames;
}

From source file:org.elasticdroid.model.LoginModel.java

License:Open Source License

public Object performLogin(String... params) {
    //we need username, accessKey, secretAccessKey
    if (params.length != 3) {
        Log.e(this.getClass().getName(), "Need 3 params."); //TODO do something better.
        return null;
    }/*from   w  w w  .j  a  v a2  s .  co m*/

    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(params[1], params[2]);
    //create an IAM client
    AmazonIdentityManagementClient idManagementClient = new AmazonIdentityManagementClient(credentials);
    User userData = null;

    Log.v(this.getClass().getName(), "Executing performLogin AsyncTask...");

    try {
        userData = idManagementClient.getUser().getUser();//ensure the user ID is 
        //matched to the access and secret access keys
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    //if we get here, the userData variable has been initialised.
    //check if the user name specified by the user corresponds to the
    //user name associated with the acess and secret access keys specified         
    String username = userData.getUserName();

    if (username != null) { //this is an IAM username
        if (!username.equals(params[0])) {
            /*Log.e(this.getClass().getName(), "Username " + params[0] + ", " + userData.
                  getUserName() + " does not correspond to access and secret access key!");*/
            //return *not throw* an illegalArgumentException, because this is a different thread.
            return new IllegalArgumentException(
                    "Username does not correspond to access and " + "secret access key!");
        }
    } else {
        //this is a proper AWS account, and not an IAM username.
        //check if the username is a proper email address. Java regexes look +vely awful!
        Pattern emailPattern = Pattern.compile("^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$",
                Pattern.CASE_INSENSITIVE);

        //if this is not an email address
        if (!emailPattern.matcher(params[0]).matches()) {
            return new IllegalArgumentException(
                    "Username is an AWS account. Please enter a" + " valid email address.");
        }
    }

    /*writing to DB*/
    // if we get here, then write the data to the DB
    ElasticDroidDB elasticDroidDB = new ElasticDroidDB(activity);
    //open the database for writing
    SQLiteDatabase db = elasticDroidDB.getWritableDatabase();
    ContentValues rowValues = new ContentValues();
    //check if the username already exists
    //set the data to write
    rowValues.put(LoginTbl.COL_USERNAME, params[0]);
    rowValues.put(LoginTbl.COL_ACCESSKEY, params[1]);
    rowValues.put(LoginTbl.COL_SECRETACCESSKEY, params[2]);

    //if data is found, update.
    if (db.query(LoginTbl.TBL_NAME, new String[] {}, LoginTbl.COL_USERNAME + "=?", new String[] { params[0] },
            null, null, null).getCount() != 0) {
        try {
            db.update(LoginTbl.TBL_NAME, rowValues, LoginTbl.COL_USERNAME + "=?", new String[] { params[0] });
        } catch (SQLException sqlException) {

            Log.e(this.getClass().getName(), "SQLException: " + sqlException.getMessage());
            return sqlException; //return the exception for the View to process.
        } finally {
            db.close();
        }
    } else {
        //now write the data in, replacing if necessary!
        try {
            db.insertOrThrow(LoginTbl.TBL_NAME, null, rowValues);

        } catch (SQLException sqlException) {

            Log.e(this.getClass().getName(), "SQLException: " + sqlException.getMessage());
            return sqlException; //return the exception for the View to process.
        } finally {
            db.close();
        }
    }

    return true;
}

From source file:org.elasticdroid.model.MonitorInstanceModel.java

License:Open Source License

/** 
 * Perform the actual work of retrieving the metrics
 *///  w  ww.  j  av  a 2s .  c o  m
public Object retrieveMetrics(Dimension... dimensions) {
    //the cloudwatch client to use
    AmazonCloudWatchClient cloudWatchClient = null;
    //the request to send to cloudwatch
    GetMetricStatisticsRequest request;
    //the metric stats result.
    GetMetricStatisticsResult result;

    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"),
            connectionData.get("secretAccessKey"));
    //create a cloudwatch client
    try {
        cloudWatchClient = new AmazonCloudWatchClient(credentials);
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    //prepare request
    request = new GetMetricStatisticsRequest();
    request.setStartTime(new Date(cloudWatchInput.getStartTime()));
    request.setEndTime(new Date(cloudWatchInput.getEndTime()));
    request.setPeriod(cloudWatchInput.getPeriod());
    request.setMeasureName(cloudWatchInput.getMeasureName());
    request.setNamespace(cloudWatchInput.getNamespace());
    request.setStatistics(cloudWatchInput.getStatistics());
    request.setDimensions(Arrays.asList(dimensions));
    //tell the cloudwatch client where to look!
    cloudWatchClient.setEndpoint(AWSConstants.getCloudWatchEndpoint(cloudWatchInput.getRegion()));

    //get the monitoring result!
    try {
        result = cloudWatchClient.getMetricStatistics(request);
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not 
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    //get the data and print it out.
    List<Datapoint> data = result.getDatapoints();
    for (Datapoint datum : data) {
        Log.v(TAG, "Datum:" + datum.getAverage());
    }

    //sort the data in ascending order of timestamps
    Collections.sort(data, new CloudWatchDataSorter());

    //return the sorted data
    return data;
}