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: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//from   w  ww. j  a va 2  s.  com
 * @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;
}

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

License:Apache License

public InputStream getObject(S3ObjectSummary objectSummary) {

    S3Object object = null;// w  w w .  j a  va2 s. c o m

    try {
        logger.info("Retrieving object inputstream for s3://{}/{}", objectSummary.getBucketName(),
                objectSummary.getKey());
        object = s3Client
                .getObject(new GetObjectRequest(objectSummary.getBucketName(), objectSummary.getKey()));

    } 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 object == null ? null : object.getObjectContent();
}

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

License:Apache License

public void putObject(String destBucket, String key, InputStream inputStream, ObjectMetadata metaData) {

    try {/* w w  w . j a  va  2  s.c o  m*/
        logger.info("Put object for s3://{}/{}", destBucket, key);
        byte[] bytes = IOUtils.toByteArray(inputStream);

        if (metaData == null)
            metaData = new ObjectMetadata();

        metaData.setContentLength(bytes.length);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

        s3Client.putObject(new PutObjectRequest(destBucket, key, byteArrayInputStream, metaData));

    } 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());
    } catch (IOException e) {
        logger.error("Obtaining length", e);
    }

}

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

License:Apache License

public void moveObject(S3ObjectSummary objectSummary, String destBucket, String destKey) {
    try {//from ww w . ja  va 2 s  .  com
        // Copying object
        CopyObjectRequest copyObjRequest = new CopyObjectRequest(objectSummary.getBucketName(),
                objectSummary.getKey(), destBucket, destKey);

        s3Client.copyObject(copyObjRequest);

        DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(objectSummary.getBucketName(),
                objectSummary.getKey());

        s3Client.deleteObject(deleteObjectRequest);
    } 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());
    }
}

From source file:org.terracotta.TerracottaCloudFormationSample.java

License:Open Source License

@org.junit.BeforeClass
public static void createStack() throws Exception {

    /*//w  w  w  .  j a va 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
    */
    amazonCloudFormationClient = new AmazonCloudFormationClient(new PropertiesCredentials(
            TerracottaCloudFormationSample.class.getResourceAsStream("/AwsCredentials.properties")));

    System.out.println("================================");
    System.out.println("Terracotta CloudFormation Sample");
    System.out.println("================================\n");

    try {
        // Create a stack
        CreateStackRequest createRequest = new CreateStackRequest();
        createRequest.setStackName(stackName);
        createRequest.setTemplateBody(convertStreamToString(
                TerracottaCloudFormationSample.class.getResourceAsStream("/TerracottaServerArray.template")));

        Parameter parameter = new Parameter();
        parameter.setParameterKey("KeyName");
        parameter.setParameterValue(keyChainName);
        List parameters = new ArrayList();
        parameters.add(parameter);
        createRequest.setParameters(parameters);
        System.out.println("Creating a stack called " + createRequest.getStackName() + ".");
        amazonCloudFormationClient.createStack(createRequest);

        // Wait for stack to be created
        // Note that you could use SNS notifications on the CreateStack call to track the progress of the stack creation
        System.out.println("Stack creation completed, the stack " + stackName + " completed with "
                + waitForCompletion(amazonCloudFormationClient, stackName));

        // Show all the stacks for this account along with the resources for each stack
        for (Stack stack : amazonCloudFormationClient.describeStacks(new DescribeStacksRequest()).getStacks()) {
            System.out.println(
                    "Stack : " + stack.getStackName() + " [" + stack.getStackStatus().toString() + "]");

            DescribeStackResourcesRequest stackResourceRequest = new DescribeStackResourcesRequest();
            stackResourceRequest.setStackName(stack.getStackName());
            for (StackResource resource : amazonCloudFormationClient
                    .describeStackResources(stackResourceRequest).getStackResources()) {
                System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                        resource.getLogicalResourceId(), resource.getPhysicalResourceId());
            }
        }

        // Lookup a resource by its logical name
        DescribeStackResourcesRequest logicalNameResourceRequest = new DescribeStackResourcesRequest();
        logicalNameResourceRequest.setStackName(stackName);
        logicalNameResourceRequest.setLogicalResourceId(logicalResourceName);
        System.out.format("Looking up resource name %1$s from stack %2$s\n",
                logicalNameResourceRequest.getLogicalResourceId(), logicalNameResourceRequest.getStackName());
        for (StackResource resource : amazonCloudFormationClient
                .describeStackResources(logicalNameResourceRequest).getStackResources()) {
            System.out.format("    %1$-40s %2$-25s %3$s\n", resource.getResourceType(),
                    resource.getLogicalResourceId(), resource.getPhysicalResourceId());
        }

        //deleteStack

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS CloudFormation, 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 CloudFormation, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:org.xmlsh.aws.asDescribeGroups.java

License:BSD License

private int describe(List<XValue> args)
        throws IOException, XMLStreamException, SaxonApiException, CoreException, InterruptedException {

    OutputPort stdout = getStdout();//from www. j  av  a 2s.  c o  m
    mWriter = new SafeXMLStreamWriter(stdout.asXMLStreamWriter(getSerializeOpts()));

    startDocument();
    startElement(getName());

    DescribeAutoScalingGroupsRequest request = new DescribeAutoScalingGroupsRequest();
    if (!args.isEmpty())
        request.setAutoScalingGroupNames(Util.toStringList(args));

    traceCall("describeAutoScalingGroups");
    DescribeAutoScalingGroupsResult result = null;

    int retry = rateRetry;
    int delay = retryDelay;
    do {
        try {
            result = getAWSClient().describeAutoScalingGroups(request);
            break;

        } catch (AmazonServiceException e) {
            mShell.printErr("AmazonServiceException", e);
            if (retry > 0 && Util.isEqual("RequestLimitExceeded", e.getErrorCode())) {
                mShell.printErr("AWS RequestLimitExceeded - sleeping " + delay);
                Thread.sleep(delay);
                retry--;
                delay *= 2;
            } else
                throw e;
        }
    } while (retry > 0);

    for (AutoScalingGroup group : result.getAutoScalingGroups())
        write(group);

    endElement();
    endDocument();
    closeWriter();

    stdout.writeSequenceTerminator(getSerializeOpts());

    return 0;

}

From source file:org.xmlsh.aws.gradle.AwsPluginExtension.java

License:BSD License

public String getUserArn() {
    AmazonIdentityManagement iam = createClient(AmazonIdentityManagementClient.class, profileName);
    try {// w  w  w .  j  a v  a  2  s .  c  o m
        GetUserResult getUserResult = iam.getUser();
        return getUserResult.getUser().getArn();
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("AccessDenied") == false) {
            throw e;
        }
        String msg = e.getMessage();
        int arnIdx = msg.indexOf("arn:aws");
        if (arnIdx == -1) {
            throw e;
        }
        int arnSpace = msg.indexOf(" ", arnIdx);
        return msg.substring(arnIdx, arnSpace);
    }
}

From source file:org.xmlsh.aws.gradle.ec2.AmazonEC2AuthorizeSecurityGroupEgressTask.java

License:BSD License

@TaskAction
public void authorizeEgress() {
    // to enable conventionMappings feature
    String groupId = getGroupId();
    Object ipPermissions = getIpPermissions();

    if (groupId == null)
        throw new GradleException("groupId is not specified");
    if (ipPermissions == null)
        throw new GradleException("ipPermissions is not specified");

    AmazonEC2PluginExtension ext = getProject().getExtensions().getByType(AmazonEC2PluginExtension.class);
    AmazonEC2 ec2 = ext.getClient();//from  w  w  w  . java  2 s .  com

    try {
        ec2.authorizeSecurityGroupEgress(new AuthorizeSecurityGroupEgressRequest().withGroupId(groupId)
                .withIpPermissions(parse(ipPermissions)));
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("InvalidPermission.Duplicate")) {
            getLogger().warn(e.getMessage());
        } else {
            throw e;
        }
    }
}

From source file:org.xmlsh.aws.gradle.ec2.AmazonEC2AuthorizeSecurityGroupIngressTask.java

License:BSD License

@TaskAction
public void authorizeIngress() {
    // to enable conventionMappings feature
    String groupId = getGroupId();
    Object ipPermissions = getIpPermissions();

    if (groupId == null)
        throw new GradleException("groupId is not specified");
    if (ipPermissions == null)
        throw new GradleException("ipPermissions is not specified");

    AmazonEC2PluginExtension ext = getProject().getExtensions().getByType(AmazonEC2PluginExtension.class);
    AmazonEC2 ec2 = ext.getClient();//from  w  w w. j  ava2s  . co  m

    try {
        ec2.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest().withGroupId(groupId)
                .withIpPermissions(parse(ipPermissions)));
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("InvalidPermission.Duplicate")) {
            getLogger().warn(e.getMessage());
        } else {
            throw e;
        }
    }
}

From source file:org.xmlsh.aws.gradle.ec2.AmazonEC2RevokeSecurityGroupEgressTask.java

License:BSD License

@TaskAction
public void revokeEgress() {
    // to enable conventionMappings feature
    String groupId = getGroupId();
    Object ipPermissions = getIpPermissions();

    if (groupId == null)
        throw new GradleException("groupId is not specified");
    if (ipPermissions == null)
        throw new GradleException("ipPermissions is not specified");

    AmazonEC2PluginExtension ext = getProject().getExtensions().getByType(AmazonEC2PluginExtension.class);
    AmazonEC2 ec2 = ext.getClient();// w  ww.ja  va  2 s .  c o m

    try {
        ec2.revokeSecurityGroupEgress(new RevokeSecurityGroupEgressRequest().withGroupId(groupId)
                .withIpPermissions(parse(ipPermissions)));
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("InvalidPermission.NotFound")) {
            getLogger().warn(e.getMessage());
        } else {
            throw e;
        }
    }
}