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.netflix.dynomitemanager.sidecore.backup.S3Restore.java

License:Apache License

/**
  * Uses the Amazon S3 API to restore from S3
  *///from   w ww .ja va2  s .  co  m
@Override
public boolean restoreData(String dateString) {
    long time = restoreTime(dateString);
    if (time > -1) {
        logger.info("Restoring data from S3.");
        AmazonS3Client s3Client = new AmazonS3Client(cred.getAwsCredentialProvider());

        try {
            /* construct the key for the backup data */
            String keyName = config.getBackupLocation() + "/" + iid.getInstance().getDatacenter() + "/"
                    + iid.getInstance().getRack() + "/" + iid.getInstance().getToken() + "/" + time;

            logger.info("S3 Bucket Name: " + config.getBucketName());
            logger.info("Key in Bucket: " + keyName);

            // Checking if the S3 bucket exists, and if does not, then we create it
            if (!(s3Client.doesBucketExist(config.getBucketName()))) {
                logger.error("Bucket with name: " + config.getBucketName() + " does not exist");
            } else {
                S3Object s3object = s3Client.getObject(new GetObjectRequest(config.getBucketName(), keyName));

                logger.info("Content-Type: " + s3object.getObjectMetadata().getContentType());

                String filepath = null;

                if (config.isAof()) {
                    filepath = config.getPersistenceLocation() + "/appendonly.aof";
                } else {
                    filepath = config.getPersistenceLocation() + "/nfredis.rdb";
                }

                IOUtils.copy(s3object.getObjectContent(), new FileOutputStream(new File(filepath)));
            }
            return true;
        } catch (AmazonServiceException ase) {

            logger.error("AmazonServiceException;"
                    + " request made it to Amazon S3, but was rejected with an error ");
            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("AmazonClientException;" + " the client encountered "
                    + "an internal error while trying to " + "communicate with S3, ");
            logger.error("Error Message: " + ace.getMessage());
        } catch (IOException io) {
            logger.error("File storing error: " + io.getMessage());
        }
    } else {
        logger.error("Date in FP: " + dateString);
    }
    return false;
}

From source file:com.netflix.simianarmy.aws.AWSClient.java

License:Apache License

/** {@inheritDoc} */
@Override//w w w .  j ava  2s . co m
public void terminateInstance(String instanceId) {
    try {
        ec2Client().terminateInstances(new TerminateInstancesRequest(Arrays.asList(instanceId)));
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) {
            throw new NotFoundException("AWS instance " + instanceId + " not found", e);
        }
        throw e;
    }
}

From source file:com.netflix.simianarmy.client.aws.AWSClient.java

License:Apache License

/** {@inheritDoc} */
@Override/*  www.j av a 2  s. c o m*/
public void terminateInstance(String instanceId) {
    Validate.notEmpty(instanceId);
    LOGGER.info(String.format("Terminating instance %s in region %s.", instanceId, region));
    try {
        ec2Client().terminateInstances(new TerminateInstancesRequest(Arrays.asList(instanceId)));
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) {
            throw new NotFoundException("AWS instance " + instanceId + " not found", e);
        }
        throw e;
    }
}

From source file:com.netflix.simianarmy.client.aws.AWSClient.java

License:Apache License

/** {@inheritDoc} */
public void setInstanceSecurityGroups(String instanceId, List<String> groupIds) {
    Validate.notEmpty(instanceId);/*w  w  w. ja va 2 s.  c o  m*/
    LOGGER.info(
            String.format("Removing all security groups from instance %s in region %s.", instanceId, region));
    try {
        ModifyInstanceAttributeRequest request = new ModifyInstanceAttributeRequest();
        request.setInstanceId(instanceId);
        request.setGroups(groupIds);
        ec2Client().modifyInstanceAttribute(request);
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) {
            throw new NotFoundException("AWS instance " + instanceId + " not found", e);
        }
        throw e;
    }
}

From source file:com.netflix.simianarmy.client.aws.AWSClient.java

License:Apache License

@Override
public void detachVolume(String instanceId, String volumeId, boolean force) {
    Validate.notEmpty(instanceId);/*from   www .  j  av  a 2  s .c o  m*/
    LOGGER.info(String.format("Detach volumes from instance %s in region %s.", instanceId, region));
    try {
        DetachVolumeRequest detachVolumeRequest = new DetachVolumeRequest();
        detachVolumeRequest.setForce(force);
        detachVolumeRequest.setInstanceId(instanceId);
        detachVolumeRequest.setVolumeId(volumeId);
        ec2Client().detachVolume(detachVolumeRequest);
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) {
            throw new NotFoundException("AWS instance " + instanceId + " not found", e);
        }
        throw e;
    }
}

From source file:com.netflix.simianarmy.client.aws.AWSClient.java

License:Apache License

@Override
public List<String> listAttachedVolumes(String instanceId, boolean includeRoot) {
    Validate.notEmpty(instanceId);// w w w  .  j  av a2s.com
    LOGGER.info(String.format("Listing volumes attached to instance %s in region %s.", instanceId, region));
    try {
        List<String> volumeIds = new ArrayList<String>();
        for (Instance instance : describeInstances(instanceId)) {
            String rootDeviceName = instance.getRootDeviceName();

            for (InstanceBlockDeviceMapping ibdm : instance.getBlockDeviceMappings()) {
                EbsInstanceBlockDevice ebs = ibdm.getEbs();
                if (ebs == null) {
                    continue;
                }

                String volumeId = ebs.getVolumeId();
                if (Strings.isNullOrEmpty(volumeId)) {
                    continue;
                }

                if (!includeRoot && rootDeviceName != null && rootDeviceName.equals(ibdm.getDeviceName())) {
                    continue;
                }

                volumeIds.add(volumeId);
            }
        }
        return volumeIds;
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) {
            throw new NotFoundException("AWS instance " + instanceId + " not found", e);
        }
        throw e;
    }
}

From source file:com.netflix.simianarmy.client.aws.AWSClient.java

License:Apache License

/**
 * Describe a set of security groups.// w ww  .  j  a v a  2 s .c o m
 *
 * @param groupNames the names of the groups to find
 * @return a list of matching groups
 */
public List<SecurityGroup> describeSecurityGroups(String... groupNames) {
    AmazonEC2 ec2Client = ec2Client();
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();

    if (groupNames == null || groupNames.length == 0) {
        LOGGER.info(String.format("Getting all EC2 security groups in region %s.", region));
    } else {
        LOGGER.info(String.format("Getting EC2 security groups for %d names in region %s.", groupNames.length,
                region));
        request.withGroupNames(groupNames);
    }

    DescribeSecurityGroupsResult result;
    try {
        result = ec2Client.describeSecurityGroups(request);
    } catch (AmazonServiceException e) {
        if (e.getErrorCode().equals("InvalidGroup.NotFound")) {
            LOGGER.info("Got InvalidGroup.NotFound error for security groups; returning empty list");
            return Collections.emptyList();
        }
        throw e;
    }

    List<SecurityGroup> securityGroups = result.getSecurityGroups();
    LOGGER.info(String.format("Got %d EC2 security groups in region %s.", securityGroups.size(), region));
    return securityGroups;
}

From source file:com.netflix.spinnaker.clouddriver.aws.security.DefaultAWSAccountInfoLookup.java

License:Apache License

@Override
public String findAccountId() {
    AmazonEC2 ec2 = amazonClientProvider.getAmazonEC2(credentialsProvider, AmazonClientProvider.DEFAULT_REGION);
    try {//w ww . j a  v  a 2s. c  om
        List<Vpc> vpcs = ec2.describeVpcs().getVpcs();
        boolean supportsByName = false;
        if (vpcs.isEmpty()) {
            supportsByName = true;
        } else {
            for (Vpc vpc : vpcs) {
                if (vpc.getIsDefault()) {
                    supportsByName = true;
                    break;
                }
            }
        }

        DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
        if (supportsByName) {
            request.withGroupNames(DEFAULT_SECURITY_GROUP_NAME);
        }
        DescribeSecurityGroupsResult result = ec2.describeSecurityGroups(request);

        for (SecurityGroup sg : result.getSecurityGroups()) {
            //if there is a vpcId or it is the default security group it won't be an EC2 cross account group
            if ((sg.getVpcId() != null && sg.getVpcId().length() > 0)
                    || DEFAULT_SECURITY_GROUP_NAME.equals(sg.getGroupName())) {
                return sg.getOwnerId();
            }
        }

        throw new IllegalArgumentException("Unable to lookup accountId with provided credentials");
    } catch (AmazonServiceException ase) {
        if ("AccessDenied".equals(ase.getErrorCode())) {
            String message = ase.getMessage();
            Matcher matcher = IAM_ARN_PATTERN.matcher(message);
            if (matcher.matches()) {
                return matcher.group(1);
            }
        }
        throw ase;
    }
}

From source file:com.netflix.spinnaker.kork.aws.AwsMetricsSupport.java

License:Apache License

static String[] buildExceptionTags(AmazonWebServiceRequest originalRequest, Exception exception) {
    final AmazonServiceException ase = amazonServiceException(exception);

    String targetAccountId = DEFAULT_UNKNOWN;
    if (ase.getHttpHeaders() != null) {
        targetAccountId = ase.getHttpHeaders().get("targetAccountId");
    }//from   w  w  w .  j a v a2  s .c  o  m

    return new String[] { "requestType", originalRequest.getClass().getSimpleName(), "statusCode",
            Integer.toString(ase.getStatusCode()), "errorCode",
            Optional.ofNullable(ase.getErrorCode()).orElse(DEFAULT_UNKNOWN), "serviceName",
            Optional.ofNullable(ase.getServiceName()).orElse(DEFAULT_UNKNOWN), "errorType",
            Optional.ofNullable(ase.getErrorType()).orElse(AmazonServiceException.ErrorType.Unknown).name(),
            "accountId", Optional.ofNullable(targetAccountId).orElse(DEFAULT_UNKNOWN) };
}

From source file:com.neu.cloud.Controller.FifthUseCaseController.java

private void uploadInS3(String uploadFilePath, String uploadFileName, String dateForFolder) {
    String bucketName = "reports-sppard";
    String keyName = "UseCase5-" + dateForFolder + "/" + uploadFileName;
    AmazonS3 s3client = new AmazonS3Client(
            new BasicAWSCredentials("AKIAJ2E67YVFQ5PZSWQA", "xiVuejpUofGonrsiy2owvu/wgeNKq5nYjxYVC0ma"));
    try {//from w w  w  . ja v a  2s. 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());
    }
}