Example usage for com.amazonaws AmazonServiceException getStatusCode

List of usage examples for com.amazonaws AmazonServiceException getStatusCode

Introduction

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

Prototype

public int getStatusCode() 

Source Link

Document

Returns the HTTP status code that was returned with this service exception.

Usage

From source file:net.solarnetwork.node.backup.s3.SdkS3Client.java

License:Open Source License

@Override
public Set<S3ObjectReference> listObjects(String prefix) throws IOException {
    AmazonS3 client = getClient();//w  w w  .  j av  a  2s .  c  o m
    Set<S3ObjectReference> result = new LinkedHashSet<>(100);
    try {
        final ListObjectsV2Request req = new ListObjectsV2Request();
        req.setBucketName(bucketName);
        req.setMaxKeys(maximumKeysPerRequest);
        req.setPrefix(prefix);
        ListObjectsV2Result listResult;
        do {
            listResult = client.listObjectsV2(req);

            for (S3ObjectSummary objectSummary : listResult.getObjectSummaries()) {
                result.add(new S3ObjectReference(objectSummary.getKey(), objectSummary.getSize(),
                        objectSummary.getLastModified()));
            }
            req.setContinuationToken(listResult.getNextContinuationToken());
        } while (listResult.isTruncated() == true);

    } catch (AmazonServiceException e) {
        log.warn("AWS error: {}; HTTP code {}; AWS code {}; type {}; request ID {}", e.getMessage(),
                e.getStatusCode(), e.getErrorCode(), e.getErrorType(), e.getRequestId());
        throw new RemoteServiceException("Error listing S3 objects at " + prefix, e);
    } catch (AmazonClientException e) {
        log.debug("Error communicating with AWS: {}", e.getMessage());
        throw new IOException("Error communicating with AWS", e);
    }
    return result;
}

From source file:net.solarnetwork.node.backup.s3.SdkS3Client.java

License:Open Source License

@Override
public String getObjectAsString(String key) throws IOException {
    AmazonS3 client = getClient();/*www . ja  v  a 2s . c  o  m*/
    try {
        return client.getObjectAsString(bucketName, key);
    } catch (AmazonServiceException e) {
        log.warn("AWS error: {}; HTTP code {}; AWS code {}; type {}; request ID {}", e.getMessage(),
                e.getStatusCode(), e.getErrorCode(), e.getErrorType(), e.getRequestId());
        throw new RemoteServiceException("Error getting S3 object at " + key, e);
    } catch (AmazonClientException e) {
        log.debug("Error communicating with AWS: {}", e.getMessage());
        throw new IOException("Error communicating with AWS", e);
    }
}

From source file:net.solarnetwork.node.backup.s3.SdkS3Client.java

License:Open Source License

@Override
public S3Object getObject(String key) throws IOException {
    AmazonS3 client = getClient();//from   www.  ja  v a2s.  c om
    try {
        return client.getObject(bucketName, key);
    } catch (AmazonServiceException e) {
        log.warn("AWS error: {}; HTTP code {}; AWS code {}; type {}; request ID {}", e.getMessage(),
                e.getStatusCode(), e.getErrorCode(), e.getErrorType(), e.getRequestId());
        throw new RemoteServiceException("Error getting S3 object at " + key, e);
    } catch (AmazonClientException e) {
        log.debug("Error communicating with AWS: {}", e.getMessage());
        throw new IOException("Error communicating with AWS", e);
    }
}

From source file:net.solarnetwork.node.backup.s3.SdkS3Client.java

License:Open Source License

@Override
public S3ObjectReference putObject(String key, InputStream in, ObjectMetadata objectMetadata)
        throws IOException {
    AmazonS3 client = getClient();/* ww  w. j  a  va2  s . c o m*/
    try {
        PutObjectRequest req = new PutObjectRequest(bucketName, key, in, objectMetadata);
        client.putObject(req);
        return new S3ObjectReference(key, objectMetadata.getContentLength(), objectMetadata.getLastModified());
    } catch (AmazonServiceException e) {
        log.warn("AWS error: {}; HTTP code {}; AWS code {}; type {}; request ID {}", e.getMessage(),
                e.getStatusCode(), e.getErrorCode(), e.getErrorType(), e.getRequestId());
        throw new RemoteServiceException("Error putting S3 object at " + key, e);
    } catch (AmazonClientException e) {
        log.debug("Error communicating with AWS: {}", e.getMessage());
        throw new IOException("Error communicating with AWS", e);
    }
}

From source file:net.solarnetwork.node.backup.s3.SdkS3Client.java

License:Open Source License

@Override
public void deleteObjects(Set<String> keys) throws IOException {
    AmazonS3 client = getClient();//from   w  ww  . j a va 2 s  .c  o  m
    try {
        DeleteObjectsRequest req = new DeleteObjectsRequest(bucketName)
                .withKeys(keys.stream().map(k -> new KeyVersion(k)).collect(Collectors.toList()));
        client.deleteObjects(req);
    } catch (AmazonServiceException e) {
        log.warn("AWS error: {}; HTTP code {}; AWS code {}; type {}; request ID {}", e.getMessage(),
                e.getStatusCode(), e.getErrorCode(), e.getErrorType(), e.getRequestId());
        throw new RemoteServiceException("Error deleting S3 objects " + keys, e);
    } catch (AmazonClientException e) {
        log.debug("Error communicating with AWS: {}", e.getMessage());
        throw new IOException("Error communicating with AWS", e);
    }
}

From source file:nl.nekoconeko.glaciercmd.GlacierClient.java

License:Open Source License

private GetJobOutputResult waitForJobCompletion(String vault, String jobId) throws InterruptedException {
    GetJobOutputRequest job = new GetJobOutputRequest();
    job.setVaultName(vault);/*w  ww.  j a  v a 2  s . co  m*/
    job.setJobId(jobId);

    GetJobOutputResult res = null;
    boolean stop = false;
    while (!stop) {
        int code = 0;
        String error = "";
        try {
            res = this.client.getJobOutput(job);
            code = res.getStatus();
        } catch (AmazonServiceException e) {
            error = e.getMessage();
            code = e.getStatusCode();
        }

        switch (code) {
        case 200:
            stop = true;
            break;
        case 400:
            if (error.contains("The job is not currently available for download")) {
                Formatter.printInfoLine("Job is not finished yet, waiting...");
            } else {
                Formatter.printErrorLine("AWS returned code 400. Body Malformed.");
                System.exit(1);
            }
            break;
        case 404:
            Formatter.printErrorLine("AWS returned code 404. Vault or Job could not be found.");
            System.exit(1);
        default:
            Formatter.printInfoLine(String.format("Job returned code %d, waiting 30 seconds", code));
            break;
        }
        if (!stop) {
            Thread.sleep(1000 * 60);
        }
    }

    return res;
}

From source file:org.akvo.flow.deploy.Deploy.java

License:Open Source License

public static void main(String[] args) throws IOException {
    if (args.length != 7) {
        System.err.println("Missing argument, please provide S3 access key, S3 secret key, "
                + "instanceId , apkPath, version, GAE username and GAE password");
        return;//from   w  ww  . j ava 2 s .  c  om
    }

    File file = new File(args[APK_PATH]);
    if (!file.exists()) {
        System.err.println("Can't find apk at " + args[APK_PATH]);
        return;
    }

    final String accessKey = args[S3_ACCESS_KEY];
    final String secretKey = args[S3_SECRET_KEY];
    final String instance = args[INSTANCE_ID];
    final String accountId = args[ACCOUNT_ID];
    final String accountSecret = args[ACCOUNT_SECRET];
    final String version = args[VERSION];

    final String s3Path = "apk/" + instance + "/" + file.getName();
    final String s3Url = "http://akvoflow.s3.amazonaws.com/apk/" + instance + '/' + file.getName();
    final String host = instance + ".appspot.com";

    try {
        uploadS3(accessKey, secretKey, s3Path, file);
        updateVersion(host, accountId, accountSecret, s3Url, version, getMD5Checksum(file));
    } catch (AmazonServiceException ase) {
        System.err.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon S3, but was rejected with an error response for some reason.");
        System.err.println("Error Message:    " + ase.getMessage());
        System.err.println("HTTP Status Code: " + ase.getStatusCode());
        System.err.println("AWS Error Code:   " + ase.getErrorCode());
        System.err.println("Error Type:       " + ase.getErrorType());
        System.err.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.err.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.err.println("Error Message: " + ace.getMessage());
    } catch (IOException e) {
        System.err.println("Error updating APK version in GAE");
        e.printStackTrace();
    }

}

From source file:org.apache.airavata.gfac.ec2.AmazonInstanceScheduler.java

License:Apache License

/**
 * Monitors the CPU Utilization using Amazon Cloud Watch. In order to monitor the instance, Cloud Watch Monitoring
 * should be enabled for the running instance.
 *
 * @param credential EC2 credentials//from ww  w . j av  a  2 s  .c  om
 * @param instanceId instance id
 * @return average CPU utilization of the instance
 */
public static double monitorInstance(AWSCredentials credential, String instanceId) {
    try {
        AmazonCloudWatchClient cw = new AmazonCloudWatchClient(credential);

        long offsetInMilliseconds = 1000 * 60 * 60 * 24;
        GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
                .withStartTime(new Date(new Date().getTime() - offsetInMilliseconds)).withNamespace("AWS/EC2")
                .withPeriod(60 * 60)
                .withDimensions(new Dimension().withName("InstanceId").withValue(instanceId))
                .withMetricName("CPUUtilization").withStatistics("Average", "Maximum").withEndTime(new Date());
        GetMetricStatisticsResult getMetricStatisticsResult = cw.getMetricStatistics(request);

        double avgCPUUtilization = 0;
        List dataPoint = getMetricStatisticsResult.getDatapoints();
        for (Object aDataPoint : dataPoint) {
            Datapoint dp = (Datapoint) aDataPoint;
            avgCPUUtilization = dp.getAverage();
            log.info(instanceId + " instance's average CPU utilization : " + dp.getAverage());
        }

        return avgCPUUtilization;

    } catch (AmazonServiceException ase) {
        log.error("Caught an AmazonServiceException, which means the request was made  "
                + "to Amazon EC2, but was rejected with an error response for some reason.");
        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());

    }
    return 0;
}

From source file:org.apache.camel.component.aws.s3.S3Endpoint.java

License:Apache License

@Override
public void doStart() throws Exception {
    super.doStart();

    String fileName = getConfiguration().getFileName();

    if (fileName != null) {
        LOG.trace("File name [{}] requested, so skipping bucket check...", fileName);
        return;/*from  w w  w .  ja va 2s .  c o m*/
    }

    String bucketName = getConfiguration().getBucketName();
    LOG.trace("Quering whether bucket [{}] already exists...", bucketName);

    try {
        getS3Client().listObjects(new ListObjectsRequest(bucketName, null, null, null, 0));
        LOG.trace("Bucket [{}] already exists", bucketName);
        return;
    } catch (AmazonServiceException ase) {
        /* 404 means the bucket doesn't exist */
        if (ase.getStatusCode() != 404) {
            throw ase;
        }
    }

    LOG.trace("Bucket [{}] doesn't exist yet", bucketName);

    // creates the new bucket because it doesn't exist yet
    CreateBucketRequest createBucketRequest = new CreateBucketRequest(getConfiguration().getBucketName());
    if (getConfiguration().getRegion() != null) {
        createBucketRequest.setRegion(getConfiguration().getRegion());
    }

    LOG.trace("Creating bucket [{}] in region [{}] with request [{}]...",
            new Object[] { configuration.getBucketName(), configuration.getRegion(), createBucketRequest });

    getS3Client().createBucket(createBucketRequest);

    LOG.trace("Bucket created");

    if (configuration.getPolicy() != null) {
        LOG.trace("Updating bucket [{}] with policy [{}]", bucketName, configuration.getPolicy());

        getS3Client().setBucketPolicy(bucketName, configuration.getPolicy());

        LOG.trace("Bucket policy updated");
    }
}

From source file:org.apache.druid.storage.s3.S3TaskLogs.java

License:Apache License

private Optional<ByteSource> streamTaskFile(final long offset, String taskKey) throws IOException {
    try {//from   w  w  w .j a va2 s  .co  m
        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);
        }
    }
}