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:dbs.Getfroms3.java

public static void main(String[] args) throws IOException {

    AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.AP_SOUTH_1)
            .withCredentials(new AWSStaticCredentialsProvider(credentials)).build();
    //AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider("inhack2hire28"));
    try {//from  w  w  w  . j a v a  2 s .  c  om
        System.out.println("Downloading an object");
        S3Object s3object = s3Client.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + s3object.getObjectMetadata().getContentType());
        displayTextInputStream(s3object.getObjectContent());

        // Get a range of bytes from an object.

        GetObjectRequest rangeObjectRequest = new GetObjectRequest(bucketName, key);
        rangeObjectRequest.setRange(0, 10);
        S3Object objectPortion = s3Client.getObject(rangeObjectRequest);

        System.out.println("Printing bytes retrieved.");
        displayTextInputStream(objectPortion.getObjectContent());

    } 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:DynamicProvisioning.Requests.java

License:Open Source License

public String waitUntilActiveandRunning(String request) throws InterruptedException {

    boolean isActive = false;
    boolean isRunning = false;
    List<Reservation> reservation = new ArrayList<Reservation>();
    List<Instance> ins = new ArrayList<Instance>();
    String instanceid = null;//w w  w  . ja  va  2  s  . c  o  m
    String ipaddress = null;
    while (!isActive) {
        DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
        describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
        try {
            // Retrieve all of the requests we want to monitor.
            DescribeSpotInstanceRequestsResult describeResult = ec2
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();

            for (SpotInstanceRequest describeResponse : describeResponses) {
                if (describeResponse.getSpotInstanceRequestId().equalsIgnoreCase(request)) {
                    if (describeResponse.getState().equals("active")) {
                        System.out.println(describeResponse.getSpotInstanceRequestId() + " is active");
                        isActive = true;
                        instanceid = describeResponse.getInstanceId();
                        DescribeInstancesRequest req = new DescribeInstancesRequest()
                                .withInstanceIds(instanceid);
                        DescribeInstancesResult k = ec2.describeInstances(req);
                        reservation = k.getReservations();
                        for (Reservation i : reservation) {
                            ins = i.getInstances();
                            for (Instance in : ins) {

                                if ((in.getInstanceId()).equals(instanceid)) {
                                    ipaddress = in.getPublicIpAddress();
                                    while (ipaddress == null) {
                                        Thread.currentThread().sleep(1000);
                                        ipaddress = in.getPublicIpAddress();

                                    }

                                }
                            }
                        }
                    }
                }

                else {
                    Thread.currentThread().sleep(1000);
                }

            }
        } catch (AmazonServiceException e) {
            // Print out the error.
            System.out.println("Error when calling describeSpotInstances");
            System.out.println("Caught Exception: " + e.getMessage());
            System.out.println("Reponse Status Code: " + e.getStatusCode());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Request ID: " + e.getRequestId());

            // If we have an exception, ensure we don't break out of the loop.
            // This prevents the scenario where there was blip on the wire.
        }
    }
    return ipaddress;
}

From source file:ecplugins.s3.S3Util.java

License:Apache License

public static void UploadObject(String bucketName, String key)
        throws AmazonClientException, AmazonServiceException, Exception {
    Properties props = TestUtils.getProperties();
    File file = new File(createFile());
    BasicAWSCredentials credentials = new BasicAWSCredentials(props.getProperty(StringConstants.ACCESS_ID),
            props.getProperty(StringConstants.SECRET_ACCESS_ID));

    // Create TransferManager
    TransferManager tx = new TransferManager(credentials);

    // Get S3 Client
    AmazonS3 s3 = tx.getAmazonS3Client();

    try {//ww  w  . j a  va  2 s  .  c o  m
        System.out.println("Uploading a new object to S3 from a file\n");

        s3.putObject(new PutObjectRequest(bucketName, key, file));

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

}

From source file:edu.columbia.cc.elPonePeli.app.LiveStreamingHelper.java

public void createFormation(String stackName, String logicalResourceName) {

    try {/*from   www .  j av a 2s  .co  m*/

        // Create a stack
        Collection<Parameter> params = new ArrayList<Parameter>();
        Parameter pInstanceType = new Parameter().withParameterKey("InstanceType")
                .withParameterValue("m1.small");
        params.add(pInstanceType);
        Parameter pKeyPair = new Parameter().withParameterKey("KeyPair").withParameterValue("fbtest");
        params.add(pKeyPair);
        Parameter pLicKey = new Parameter().withParameterKey("WowzaLicenseKey")
                .withParameterValue("SVRT3-HEKkZ-zRp6C-xPTA7-b4a8P-VwR9R-7U6W7f6TXXxt");
        params.add(pLicKey);

        CreateStackRequest createRequest = new CreateStackRequest().withTemplateURL(streamingTemplateURL)
                .withStackName(streamingStackName).withParameters(params);
        System.out.println("Creating a stack called " + createRequest.getStackName() + ".");
        stackbuilder.createStack(createRequest);

    } 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:edu.harvard.hms.dbmi.bd2k.irct.aws.event.result.S3AfterGetResult.java

License:Mozilla Public License

@Override
public void fire(Result result) {
    if (result.getResultStatus() != ResultStatus.AVAILABLE) {
        return;/*  w w  w  .j a va2s.com*/
    }
    if (!result.getResultSetLocation().startsWith("S3://")) {
        File temp = new File(result.getResultSetLocation());
        if (temp.exists()) {
            return;
        } else {
            result.setResultSetLocation(
                    "S3://" + s3Folder + result.getResultSetLocation().replaceAll(irctSaveLocation + "/", ""));
        }
    }
    String location = result.getResultSetLocation().substring(5);
    // List the files in that bucket path
    try {

        final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName)
                .withPrefix(location);

        // Loop Through all the files
        ListObjectsV2Result s3Files;
        do {
            s3Files = s3client.listObjectsV2(req);
            for (S3ObjectSummary objectSummary : s3Files.getObjectSummaries()) {
                // Download the files to the directory specified
                String keyName = objectSummary.getKey();
                String fileName = irctSaveLocation + keyName.replace(location, "");
                log.info("Downloading: " + keyName + " --> " + fileName);
                s3client.getObject(new GetObjectRequest(bucketName, keyName), new File(fileName));
            }
            req.setContinuationToken(s3Files.getNextContinuationToken());
        } while (s3Files.isTruncated() == true);

        // Update the result set id
        result.setResultSetLocation(irctSaveLocation + "/" + location.replace(s3Folder, ""));

    } catch (AmazonServiceException ase) {
        log.warn("Caught an AmazonServiceException, which " + "means your request made it "
                + "to Amazon S3, but was rejected with an error response" + " for some reason.");
        log.warn("Error Message:    " + ase.getMessage());
        log.warn("HTTP Status Code: " + ase.getStatusCode());
        log.warn("AWS Error Code:   " + ase.getErrorCode());
        log.warn("Error Type:       " + ase.getErrorType());
        log.warn("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        log.warn("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.");
        log.warn("Error Message: " + ace.getMessage());
    }
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.aws.event.result.S3AfterSaveResult.java

License:Mozilla Public License

@Override
public void fire(SecureSession session, Executable executable) {

    try {// w w  w  .j av  a  2  s.  co  m
        if (executable.getStatus() != ExecutableStatus.COMPLETED) {
            return;
        }

        Result result = executable.getResults();
        for (File resultFile : result.getData().getFileList()) {
            String keyName = s3Folder + result.getId() + "/" + resultFile.getName();
            // Copy the result into S3 if bucketName is not empty or null
            s3client.putObject(new PutObjectRequest(bucketName, keyName, resultFile));
            log.info("Moved " + result.getResultSetLocation() + " to " + bucketName + "/" + keyName);
            // Delete File
            resultFile.delete();
            log.info("Deleted " + resultFile.getName());
        }
        result.setResultSetLocation("S3://" + s3Folder + result.getId());

    } catch (AmazonServiceException ase) {
        log.warn("Caught an AmazonServiceException, which " + "means your request made it "
                + "to Amazon S3, but was rejected with an error response" + " for some reason.");
        log.warn("Error Message:    " + ase.getMessage());
        log.warn("HTTP Status Code: " + ase.getStatusCode());
        log.warn("AWS Error Code:   " + ase.getErrorCode());
        log.warn("Error Type:       " + ase.getErrorType());
        log.warn("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        log.warn("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.");
        log.warn("Error Message: " + ace.getMessage());
    } catch (ResourceInterfaceException e) {
        log.warn("Error Message: " + e.getMessage());
    }
}

From source file:edu.umass.cs.aws.support.AWSEC2.java

License:Apache License

/**
 * Creates an EC2 instance in the region given. Timeout in milleseconds can be specified.
 *
 * @param ec2//from   w w w .ja v  a  2s .  co  m
 * @param region
 * @param amiRecord
 * @param instanceName
 * @param keyName
 * @param securityGroupName
 * @param script
 * @param tags
 * @param elasticIP
 * @param timeout
 * @return a new instance instance
 */
public static Instance createAndInitInstance(AmazonEC2 ec2, RegionRecord region, AMIRecord amiRecord,
        String instanceName, String keyName, String securityGroupName, String script, Map<String, String> tags,
        String elasticIP, int timeout) {

    try {
        // set the region (AKA endpoint)
        setRegion(ec2, region);
        // create the instance
        SecurityGroup securityGroup = findOrCreateSecurityGroup(ec2, securityGroupName);
        String keyPair = findOrCreateKeyPair(ec2, keyName);
        String instanceID = createInstanceAndWait(ec2, amiRecord, keyPair, securityGroup);
        if (instanceID == null) {
            return null;
        }
        System.out.println("Instance " + instanceName + " is running in " + region.name());

        // add a name to the instance
        addInstanceTag(ec2, instanceID, "Name", instanceName);
        if (tags != null) {
            addInstanceTags(ec2, instanceID, tags);
        }
        Instance instance = findInstance(ec2, instanceID);
        if (instance == null) {
            return null;
        }
        String hostname = instance.getPublicDnsName();
        System.out.println("Waiting " + timeout / 1000 + " seconds for " + instanceName + " (" + hostname + ", "
                + instanceID + ") to be reachable.");
        long startTime = System.currentTimeMillis();
        while (!Pinger.isReachable(hostname, SSHPORT, 2000)) {
            ThreadUtils.sleep(1000);
            System.out.print(".");
            if (System.currentTimeMillis() - startTime > timeout) {
                System.out.println(
                        instanceName + " (" + hostname + ")" + " timed out during reachability check.");
                return null;
            }
        }
        System.out.println();
        System.out.println(instanceName + " (" + hostname + ")" + " is reachable.");

        // associate the elasticIP if one is provided
        if (elasticIP != null) {
            System.out.println(
                    "Using ElasticIP " + elasticIP + " for instance " + instanceName + " (" + instanceID + ")");
            AWSEC2.associateAddress(ec2, elasticIP, instance);

            // get a new copy cuz things have changed
            instance = findInstance(ec2, instanceID);
            if (instance == null) {
                return null;
            }
            // recheck reachability
            hostname = instance.getPublicDnsName();
            System.out.println("Waiting " + timeout / 1000 + " s for " + instanceName + " (" + hostname + ", "
                    + instanceID + ") to be reachable after Elastic IP change.");
            startTime = System.currentTimeMillis();
            while (!Pinger.isReachable(hostname, SSHPORT, 2000)) {
                ThreadUtils.sleep(1000);
                System.out.print(".");
                if (System.currentTimeMillis() - startTime > timeout) {// give it a minute and ahalf
                    System.out.println(instanceName + " (" + hostname + ")"
                            + " timed out during second (elastic IP) reachability check.");
                    return null;
                }
            }
            System.out.println();
            System.out.println(instanceName + " (" + hostname + ")" + " is still reachable.");
        }
        if (script != null) {
            File keyFile = new File(KEYHOME + FILESEPARATOR + keyName + PRIVATEKEYFILEEXTENSION);
            ExecuteBash.executeBashScript("ec2-user", hostname, keyFile, true, "installScript.sh", script);
        }
        return instance;

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }
    return null;
}

From source file:edu.umass.cs.aws.support.examples.AWSStatusCheck.java

License:Apache License

/**
 *
 * @param args//from   www. ja  v a  2 s.c o  m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    init();

    /*
     * Amazon EC2
     */
    for (String endpoint : endpoints) {
        try {
            ec2.setEndpoint(endpoint);
            System.out.println("**** Endpoint: " + endpoint);
            DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
            System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                    + " Availability Zones.");
            for (AvailabilityZone zone : availabilityZonesResult.getAvailabilityZones()) {
                System.out.println(zone.getZoneName());
            }

            DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
            List<Reservation> reservations = describeInstancesRequest.getReservations();
            Set<Instance> instances = new HashSet<Instance>();

            System.out.println("Instances: ");
            for (Reservation reservation : reservations) {
                for (Instance instance : reservation.getInstances()) {
                    instances.add(instance);
                    System.out.println(instance.getPublicDnsName() + " is " + instance.getState().getName());
                }
            }

            System.out.println("Security groups: ");
            DescribeSecurityGroupsResult describeSecurityGroupsResult = ec2.describeSecurityGroups();
            for (SecurityGroup securityGroup : describeSecurityGroupsResult.getSecurityGroups()) {
                System.out.println(securityGroup.getGroupName());
            }

            //System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        } catch (AmazonServiceException ase) {
            System.out.println("Caught Exception: " + ase.getMessage());
            System.out.println("Reponse Status Code: " + ase.getStatusCode());
            System.out.println("Error Code: " + ase.getErrorCode());
            System.out.println("Request ID: " + ase.getRequestId());
        }

        /*
         * Amazon SimpleDB
         *
         */
        try {
            ListDomainsRequest sdbRequest = new ListDomainsRequest().withMaxNumberOfDomains(100);
            ListDomainsResult sdbResult = sdb.listDomains(sdbRequest);

            int totalItems = 0;
            for (String domainName : sdbResult.getDomainNames()) {
                DomainMetadataRequest metadataRequest = new DomainMetadataRequest().withDomainName(domainName);
                DomainMetadataResult domainMetadata = sdb.domainMetadata(metadataRequest);
                totalItems += domainMetadata.getItemCount();
            }

            System.out.println("You have " + sdbResult.getDomainNames().size() + " Amazon SimpleDB domain(s)"
                    + "containing a total of " + totalItems + " items.");
        } catch (AmazonServiceException ase) {
            System.out.println("Caught Exception: " + ase.getMessage());
            System.out.println("Reponse Status Code: " + ase.getStatusCode());
            System.out.println("Error Code: " + ase.getErrorCode());
            System.out.println("Request ID: " + ase.getRequestId());
        }

        /*
         * Amazon S3
         *.
         */
        try {
            List<Bucket> buckets = s3.listBuckets();

            long totalSize = 0;
            int totalItems = 0;
            for (Bucket bucket : buckets) {
                /*
                 * In order to save bandwidth, an S3 object listing does not
                 * contain every object in the bucket; after a certain point the
                 * S3ObjectListing is truncated, and further pages must be
                 * obtained with the AmazonS3Client.listNextBatchOfObjects()
                 * method.
                 */
                ObjectListing objects = s3.listObjects(bucket.getName());
                do {
                    for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                        totalSize += objectSummary.getSize();
                        totalItems++;
                    }
                    objects = s3.listNextBatchOfObjects(objects);
                } while (objects.isTruncated());
            }

            System.out.println("You have " + buckets.size() + " Amazon S3 bucket(s), " + "containing "
                    + totalItems + " objects with a total size of " + totalSize + " bytes.");
        } catch (AmazonServiceException ase) {
            /*
             * AmazonServiceExceptions represent an error response from an AWS
             * services, i.e. your request made it to AWS, but the AWS service
             * either found it invalid or encountered an error trying to execute
             * it.
             */
            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) {
            /*
             * AmazonClientExceptions represent an error that occurred inside
             * the client on the local host, either while trying to send the
             * request to AWS or interpret the response. For example, if no
             * network connection is available, the client won't be able to
             * connect to AWS to execute a request and will throw an
             * AmazonClientException.
             */
            System.out.println("Error Message: " + ace.getMessage());
        }
    }
}

From source file:edu.utn.frba.grupo5303.serverenviolibre.services.NotificacionesPushService.java

@Override
public void enviarNotificacion(NotificacionPush notificacion) {
    try {/*from w  w  w  .j av a2s  .co m*/
        logger.log(Level.INFO, "Enviando notificacion al snsId: {0}", notificacion.getGcmIdDestino());
        logger.log(Level.INFO, "Enviando notificacion de tipo: {0}", notificacion.getCodigo());
        PublishRequest publishRequest = new PublishRequest();
        Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes(
                attributesMap.get(plataforma));
        if (notificationAttributes != null && !notificationAttributes.isEmpty()) {
            publishRequest.setMessageAttributes(notificationAttributes);
        }
        publishRequest.setMessageStructure("json");
        // If the message attributes are not set in the requisite method,
        // notification is sent with default attributes
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put(plataforma.name(), notificacion.getMensajeDeNotificacion());
        String message = SampleMessageGenerator.jsonify(messageMap);

        // Create Platform Application. This corresponds to an app on a
        // platform.
        CreatePlatformApplicationResult platformApplicationResult = createPlatformApplication();

        // The Platform Application Arn can be used to uniquely identify the
        // Platform Application.
        String platformApplicationArn = platformApplicationResult.getPlatformApplicationArn();

        // Create an Endpoint. This corresponds to an app on a device.
        CreatePlatformEndpointResult platformEndpointResult = createPlatformEndpoint("CustomData",
                notificacion.getGcmIdDestino(), platformApplicationArn);

        // For direct publish to mobile end points, topicArn is not relevant.
        publishRequest.setTargetArn(platformEndpointResult.getEndpointArn());

        publishRequest.setMessage(message);
        snsClient.publish(publishRequest);
    } catch (AmazonServiceException ase) {
        logger.log(Level.SEVERE, "Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SNS, but was rejected with an error response for some reason.");
        logger.log(Level.SEVERE, "Error Message:    {0}", ase.getMessage());
        logger.log(Level.SEVERE, "HTTP Status Code: {0}", ase.getStatusCode());
        logger.log(Level.SEVERE, "AWS Error Code:   {0}", ase.getErrorCode());
        logger.log(Level.SEVERE, "Error Type:       {0}", ase.getErrorType());
        logger.log(Level.SEVERE, "Request ID:       {0}", ase.getRequestId());
    } catch (AmazonClientException ace) {
        logger.log(Level.SEVERE,
                "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.log(Level.SEVERE, "Error Message: {0}", ace.getMessage());
    }
}

From source file:eu.optimis.interopt.provider.aws.AmazonClient.java

License:Apache License

private String printServiceException(AmazonServiceException se) {
    return se.getMessage() + "(HTTP Code: " + se.getStatusCode() + " - AWS Code: " + se.getErrorCode()
            + " - Error Type: " + se.getErrorType() + " )";
}