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:com.neu.cloud.Controller.FirstUseCaseController.java

private void uploadInS3(String uploadFilePath, String uploadFileName, String dateForFolder) {
    String bucketName = "reports-sppard";
    String keyName = "UseCase1-" + dateForFolder + "/" + uploadFileName;
    AmazonS3 s3client = new AmazonS3Client(
            new BasicAWSCredentials("AKIAJ2E67YVFQ5PZSWQA", "xiVuejpUofGonrsiy2owvu/wgeNKq5nYjxYVC0ma"));
    try {//  w w  w  .  jav  a2s. co m
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFilePath + uploadFileName);
        s3client.putObject(new PutObjectRequest(bucketName, keyName, file));
    } 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:com.neu.cloud.Controller.FourthUseCaseController.java

private void uploadInS3(String uploadFilePath, String uploadFileName, String dateForFolder) {
    String bucketName = "reports-sppard";
    String keyName = "UseCase4-" + dateForFolder + "/" + uploadFileName;
    AmazonS3 s3client = new AmazonS3Client(
            new BasicAWSCredentials("AKIAJ2E67YVFQ5PZSWQA", "xiVuejpUofGonrsiy2owvu/wgeNKq5nYjxYVC0ma"));
    try {// w w w  .j  a v a 2 s  .  com
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFilePath + uploadFileName);
        s3client.putObject(new PutObjectRequest(bucketName, keyName, file));
    } 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:com.neu.cloud.Controller.SecondUseCaseController.java

private void uploadInS3(String uploadFilePath, String uploadFileName, String dateForFolder) {
    String bucketName = "reports-sppard";
    String keyName = "UseCase2-" + dateForFolder + "/" + uploadFileName;
    AmazonS3 s3client = new AmazonS3Client(
            new BasicAWSCredentials("AKIAJ2E67YVFQ5PZSWQA", "xiVuejpUofGonrsiy2owvu/wgeNKq5nYjxYVC0ma"));
    try {/*from  w  w  w. j a  va 2s . c om*/
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFilePath + uploadFileName);
        s3client.putObject(new PutObjectRequest(bucketName, keyName, file));
    } 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:com.neu.cloud.Controller.ThirdUseCaseController.java

private void uploadInS3(String uploadFilePath, String uploadFileName, String dateForFolder) {
    String bucketName = "reports-sppard";
    String keyName = "UseCase3-" + dateForFolder + "/" + uploadFileName;
    AmazonS3 s3client = new AmazonS3Client(
            new BasicAWSCredentials("AKIAJ2E67YVFQ5PZSWQA", "xiVuejpUofGonrsiy2owvu/wgeNKq5nYjxYVC0ma"));
    try {//w w w . j a v a2 s.  com
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFilePath + uploadFileName);
        s3client.putObject(new PutObjectRequest(bucketName, keyName, file));
    } 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:com.nike.cerberus.config.CmsEnvPropertiesLoader.java

License:Apache License

private String getObject(String path) {
    final GetObjectRequest request = new GetObjectRequest(bucketName, path);

    try {/*from w  ww.  j  a v  a  2s . co  m*/
        S3Object s3Object = s3Client.getObject(request);
        InputStream object = s3Object.getObjectContent();
        return IOUtils.toString(object, Charset.defaultCharset());
    } catch (AmazonServiceException ase) {
        if (StringUtils.equalsIgnoreCase(ase.getErrorCode(), "NoSuchKey")) {
            final String errorMessage = String.format("The S3 object doesn't exist. Bucket: %s, Key: %s",
                    bucketName, request.getKey());
            logger.debug(errorMessage);
            throw new IllegalStateException(errorMessage);
        } else {
            logger.error("Unexpected error communicating with AWS.", ase);
            throw ase;
        }
    } catch (IOException e) {
        String errorMessage = String.format(
                "Unable to read contents of S3 object. Bucket: %s, Key: %s, Expected Encoding: %s", bucketName,
                request.getKey(), Charset.defaultCharset());
        logger.error(errorMessage);
        throw new IllegalStateException(errorMessage, e);
    }
}

From source file:com.nike.cerberus.service.AuthenticationService.java

License:Apache License

/**
 * Enables an IAM role to authenticate and get back an encrypted payload that the role is only able to decrypt with
 * KMS./*from   www  .j  a v  a 2  s.  c o m*/
 * @param credentials IAM role credentials
 * @return Encrypted auth response
 */
public IamRoleAuthResponse authenticate(IamRoleCredentials credentials) {
    final String keyId;
    try {
        keyId = getKeyId(credentials);
    } catch (AmazonServiceException e) {
        if ("InvalidArnException".equals(e.getErrorCode())) {
            throw ApiException.newBuilder().withApiErrors(DefaultApiError.AUTH_IAM_ROLE_REJECTED)
                    .withExceptionCause(e)
                    .withExceptionMessage(String.format(
                            "Failed to lazily provision KMS key for arn:aws:iam::%s:role/%s in region: %s",
                            credentials.getAccountId(), credentials.getRoleName(), credentials.getRegion()))
                    .build();
        }
        throw e;
    }

    final Set<String> policies = buildPolicySet(credentials.getAccountId(), credentials.getRoleName());
    String arn = String.format("arn:aws:iam::%s:role/%s", credentials.getAccountId(),
            credentials.getRoleName());

    final Map<String, String> meta = Maps.newHashMap();
    meta.put(VaultAuthPrincipal.METADATA_KEY_AWS_ACCOUNT_ID, credentials.getAccountId());
    meta.put(VaultAuthPrincipal.METADATA_KEY_AWS_IAM_ROLE_NAME, credentials.getRoleName());
    meta.put(VaultAuthPrincipal.METADATA_KEY_AWS_REGION, credentials.getRegion());
    meta.put(VaultAuthPrincipal.METADATA_KEY_USERNAME, arn);

    // We will allow specific ARNs access to the user portions of the API
    if (getAdminRoleArnSet().contains(arn)) {
        meta.put(VaultAuthPrincipal.METADATA_KEY_IS_ADMIN, Boolean.toString(true));
    }

    final VaultTokenAuthRequest tokenAuthRequest = new VaultTokenAuthRequest().setPolicies(policies)
            .setMeta(meta).setTtl(iamTokenTTL).setNoDefaultPolicy(true);

    final VaultAuthResponse authResponse = vaultAdminClient.createOrphanToken(tokenAuthRequest);

    byte[] authResponseJson;
    try {
        authResponseJson = objectMapper.writeValueAsBytes(authResponse);
    } catch (JsonProcessingException e) {
        throw ApiException.newBuilder().withApiErrors(DefaultApiError.INTERNAL_SERVER_ERROR)
                .withExceptionCause(e).withExceptionMessage(
                        "Failed to write IAM role authentication response as JSON for encrypting.")
                .build();
    }
    final byte[] encryptedAuthResponse = encrypt(credentials.getRegion(), keyId, authResponseJson);

    IamRoleAuthResponse iamRoleAuthResponse = new IamRoleAuthResponse();
    iamRoleAuthResponse.setAuthData(Base64.encodeBase64String(encryptedAuthResponse));
    return iamRoleAuthResponse;
}

From source file:com.nike.cerberus.service.Ec2Service.java

License:Apache License

/**
 * Checks if a key pair is present in AWS EC2.
 *
 * @param keyName Friendly name for the key
 * @return If present/*from  ww  w.  j  a va2  s . c  o m*/
 */
public boolean isKeyPairPresent(final String keyName) {
    final DescribeKeyPairsRequest request = new DescribeKeyPairsRequest().withKeyNames(keyName);

    try {
        final DescribeKeyPairsResult result = ec2Client.describeKeyPairs(request);
        return result.getKeyPairs().size() > 0;
    } catch (final AmazonServiceException ase) {
        if (ase.getErrorCode() == "InvalidKeyPair.NotFound") {
            return false;
        }

        throw ase;
    }
}

From source file:com.nike.cerberus.service.S3StoreService.java

License:Apache License

public Optional<String> get(String path) {
    GetObjectRequest request = new GetObjectRequest(s3Bucket, getFullPath(path));

    try {/*www. j a  va2  s . c  o  m*/
        S3Object s3Object = s3Client.getObject(request);
        InputStream object = s3Object.getObjectContent();
        return Optional.of(IOUtils.toString(object, ConfigConstants.DEFAULT_ENCODING));
    } catch (AmazonServiceException ase) {
        if (StringUtils.equalsIgnoreCase(ase.getErrorCode(), "NoSuchKey")) {
            logger.debug(String.format("The S3 object doesn't exist. Bucket: %s, Key: %s", s3Bucket,
                    request.getKey()));
            return Optional.empty();
        } else {
            logger.error("Unexpected error communicating with AWS.", ase);
            throw ase;
        }
    } catch (IOException e) {
        String errorMessage = String.format(
                "Unable to read contents of S3 object. Bucket: %s, Key: %s, Expected Encoding: %s", s3Bucket,
                request.getKey(), ConfigConstants.DEFAULT_ENCODING);
        logger.error(errorMessage);
        throw new UnexpectedDataEncodingException(errorMessage, e);
    }
}

From source file:com.onemenu.server.util.awsnotification.SNSMobilePush.java

License:Open Source License

public static void pushIOSNotification(String message, String deviceToken, Map<String, Object> customData,
        int badge) throws IOException {

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

    sns.setEndpoint("https://sns.us-west-2.amazonaws.com");
    if (logger.isDebugEnabled()) {
        logger.debug("===========================================\n");
        logger.debug("Getting Started with Amazon SNS  IOS");
        logger.debug("===========================================\n");
    }/*w w w. j  a va  2  s  .  c  o m*/

    try {
        SNSMobilePush push = new SNSMobilePush(sns);
        String applicationName = ConfigCache.getValue(ConfigKey.APPLICATION_NAME, "One-Menu");
        String _message = MessageGenerator.getAppleMessage(message, null, badge, customData);
        boolean isSandBox = Boolean.parseBoolean(ConfigCache.getValue(ConfigKey.IS_SAND_BOX, "true"));
        Platform platform = null;
        String Certificate = null;
        String Private_Key = null;
        if (isSandBox) {
            platform = Platform.APNS_SANDBOX;
            Certificate = S_Certificate;
            Private_Key = S_Private_Key;
        } else {
            platform = Platform.APNS;
            Certificate = P_Certificate;
            Private_Key = P_Private_Key;
        }

        push.snsClientWrapper.notification(platform, Certificate, Private_Key, deviceToken, applicationName,
                attributesMap, _message);

    } catch (AmazonServiceException ase) {
        logger.error("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SNS, 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 "
                + "a serious internal problem while trying to communicate with SNS, such as not "
                + "being able to access the network.");
        logger.error("Error Message: " + ace.getMessage());
    }
}

From source file:com.onemenu.server.util.awsnotification.SNSMobilePush.java

License:Open Source License

public static void pushAndroidNotification(String message, String deviceToken, Map<String, Object> customData)
        throws IOException {

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

    sns.setEndpoint("https://sns.us-west-2.amazonaws.com");
    if (logger.isDebugEnabled()) {
        logger.debug("===========================================\n");
        logger.debug("Getting Started with Amazon SNS android");
        logger.debug("===========================================\n");
    }/*from   w w  w.  java  2  s  .  c  o m*/

    try {
        SNSMobilePush push = new SNSMobilePush(sns);
        String applicationName = ConfigCache.getValue(ConfigKey.APPLICATION_NAME, "One-Menu");
        String serverAPIKey = "";
        String _message = MessageGenerator.getSampleAndroidMessage("NewOrder", message, customData);
        push.snsClientWrapper.notification(Platform.GCM, "", serverAPIKey, deviceToken, applicationName,
                attributesMap, _message);

    } catch (AmazonServiceException ase) {
        logger.error("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SNS, 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 "
                + "a serious internal problem while trying to communicate with SNS, such as not "
                + "being able to access the network.");
        logger.error("Error Message: " + ace.getMessage());
    }
}