Example usage for com.amazonaws AmazonClientException AmazonClientException

List of usage examples for com.amazonaws AmazonClientException AmazonClientException

Introduction

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

Prototype

public AmazonClientException(String message, Throwable t) 

Source Link

Document

Creates a new AmazonClientException with the specified message, and root cause.

Usage

From source file:com.ivona.services.tts.model.transform.listvoices.ListVoicesPostRequestMarshaller.java

License:Open Source License

private void setRequestPayload(Request<ListVoicesRequest> request, ListVoicesRequest listVoicesRequest) {
    try {/* w ww  .j av  a 2s.c  o  m*/
        StringWriter stringWriter = new StringWriter();
        JSONWriter jsonWriter = new JSONWriter(stringWriter);

        jsonWriter.object();
        if (listVoicesRequest.getVoice() != null) {
            Voice voice = listVoicesRequest.getVoice();

            jsonWriter.key(JSON_KEY_VOICE);
            jsonWriter.object();

            if (voice.getGender() != null) {
                jsonWriter.key(JSON_KEY_GENDER).value(voice.getGender());
            }
            if (voice.getLanguage() != null) {
                jsonWriter.key(JSON_KEY_LANGUAGE).value(voice.getLanguage());
            }
            if (voice.getName() != null) {
                jsonWriter.key(JSON_KEY_NAME).value(voice.getName());
            }

            jsonWriter.endObject();
        }
        jsonWriter.endObject();

        String snippet = stringWriter.toString();
        byte[] content = snippet.getBytes(UTF_8);
        request.setContent(new StringInputStream(snippet));
        request.addHeader("Content-Length", Integer.toString(content.length));
    } catch (Throwable t) {
        throw new AmazonClientException("Unable to marshall request to JSON: " + t.getMessage(), t);
    }
}

From source file:com.jfixby.scarabei.red.aws.test.S3Sample.java

License:Open Source License

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

    /*/*from  w ww . jav a 2s  .  c  o m*/
     * The ProfileCredentialsProvider will return your [default] credential profile by reading from the credentials file located
     * at (C:\\Users\\JCode\\.aws\\credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("default").getCredentials();
    } catch (final Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (C:\\Users\\%USERNAME%\\.aws\\credentials), and is in valid format.", e);
    }

    final AmazonS3 s3 = new AmazonS3Client(credentials);
    final Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    final String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    final String key = "MyObjectKey";

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon S3");
    System.out.println("===========================================\n");

    try {
        /*
         * Create a new S3 bucket - Amazon S3 bucket names are globally unique, so once a bucket name has been taken by any user,
         * you can't create another bucket with that same name.
         *
         * You can optionally specify a location for your bucket if you want to keep your data closer to your applications or
         * users.
         */
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (final Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        /*
         * Upload an object to your bucket - You can easily upload a file to S3, or upload directly an InputStream if you know
         * the length of the data in the stream. You can also specify your own metadata when uploading to S3, which allows you
         * set a variety of options like content-type and content-encoding, plus additional metadata specific to your
         * applications.
         */
        System.out.println("Uploading a new object to S3 from a file\n");
        s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        /*
         * Download an object - When you download an object, you get all of the object's metadata and a stream from which to read
         * the contents. It's important to read the contents of the stream as quickly as possibly since the data is streamed
         * directly from Amazon S3 and your network connection will remain open until you read all the data or close the input
         * stream.
         *
         * GetObjectRequest also supports several other options, including conditional downloading of objects based on
         * modification times, ETags, and selectively downloading a range of an object.
         */
        System.out.println("Downloading an object");
        final S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        /*
         * List objects in your bucket by prefix - There are many options for listing the objects in your bucket. Keep in mind
         * that buckets with many objects might truncate their results when listing their objects, so be sure to check if the
         * returned object listing is truncated, and use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
         * additional results.
         */
        System.out.println("Listing objects");
        final ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (final S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();

        /*
         * Delete an object - Unless versioning has been turned on for your bucket, there is no way to undelete an object, so use
         * caution when deleting objects.
         */
        System.out.println("Deleting an object\n");
        s3.deleteObject(bucketName, key);

        /*
         * Delete a bucket - A bucket must be completely empty before it can be deleted, so remember to delete any objects from
         * your buckets before you try to delete them.
         */
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    } catch (final 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 (final AmazonClientException ace) {
        System.out.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.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.leverno.ysbos.archive.example.AmazonGlacierDownloadInventoryWithSQSPolling.java

License:Open Source License

private static void downloadJobOutput(String jobId) throws IOException {

    GetJobOutputRequest getJobOutputRequest = new GetJobOutputRequest().withVaultName(vaultName)
            .withJobId(jobId);//from ww w.  j  av  a  2  s.c  o  m
    GetJobOutputResult getJobOutputResult = client.getJobOutput(getJobOutputRequest);

    FileWriter fstream = new FileWriter(fileName);
    BufferedWriter out = new BufferedWriter(fstream);
    BufferedReader in = new BufferedReader(new InputStreamReader(getJobOutputResult.getBody()));
    String inputLine;
    try {
        while ((inputLine = in.readLine()) != null) {
            out.write(inputLine);
        }
    } catch (IOException e) {
        throw new AmazonClientException("Unable to save archive", e);
    } finally {
        try {
            in.close();
        } catch (Exception e) {
        }
        try {
            out.close();
        } catch (Exception e) {
        }
    }
    System.out.println("Retrieved inventory to " + fileName);
}

From source file:com.mateusz.mateuszsqs.SQSprocessor.java

public static void main(String[] args) throws AmazonClientException {
    System.out.println("Start process SQS");
    try {/*from  w w w.  j a va2 s. c o m*/
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
        System.out.println("Error");
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (~/.aws/credentials), and is in valid format.", e);
    }

    final Thread mainThread = new Thread(() -> {
        while (!Thread.currentThread().isInterrupted()) {
            AmazonSQS sqs = new AmazonSQSClient(credentials);
            Region usWest2 = Region.getRegion(Regions.US_WEST_2);
            sqs.setRegion(usWest2);

            AmazonS3 s3 = new AmazonS3Client(credentials);
            s3.setRegion(usWest2);

            List<String> filesList = SQSConfig.getMessages(sqs, sqsURL);

            for (String file : filesList) {
                String[] files = file.split(",");
                if (!file.equals("missing parameter: fileNames"))
                    for (int i = 0; i < files.length; i++) {
                        try {
                            SQSConfig.processFile(files[i], s3, bucketName);
                        } catch (IOException e) {
                            System.out.println("Error");
                            e.printStackTrace();
                        }
                    }

            }
            System.out.println("\nWaiting for messages.........\n");
        }
    });
    mainThread.start();
}

From source file:com.msi.dns53.client.DNS53Client.java

License:Apache License

@SuppressWarnings("unchecked")
public void exceptionMapper(ClientResponse response, String resultXml) throws AmazonServiceException {
    ErrorResponsePOJO er = null;/*from  ww w  . j a  va 2s  .c om*/
    try {
        StringReader reader = new StringReader(resultXml);
        JAXBContext context = JAXBContext.newInstance(ErrorResponsePOJO.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        er = (ErrorResponsePOJO) unmarshaller.unmarshal(reader);
    } catch (JAXBException e) {
        e.printStackTrace();
        throw new AmazonClientException("There was a problem parsing the error response xml with JAXB.", e);
    }
    if (er == null || er.getError() == null || er.getRequestId() == null || er.getError().getCode() == null
            || er.getError().getMessage() == null || er.getError().getType() == null) {
        throw new AmazonClientException(
                "Error response xml did not contain expected elements although it is well formed.");
    }

    String errCode = er.getError().getCode();
    Class<AmazonServiceException> clazz = null;
    Constructor<AmazonServiceException> c = null;
    AmazonServiceException exception = null;
    try {
        String clazzName = ExceptionMap.getExceptionMap().getMap().get(errCode);
        clazz = (Class<AmazonServiceException>) Class.forName(clazzName);
        c = (Constructor<AmazonServiceException>) clazz.getConstructor(String.class);
        exception = (AmazonServiceException) c.newInstance(new Object[] { er.getError().getMessage() });
    } catch (NullPointerException e) {
        exception = new AmazonServiceException(er.getError().getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        throw new AmazonClientException("Client could not determine the type of the error response.");
    }
    if (exception == null) {
        throw new AmazonClientException(
                "Client encountered a problem while it was mapping the error response.");
    }
    exception.setErrorCode(er.getError().getCode());
    ErrorType et = ErrorType.Unknown;
    if ("Sender".equals(er.getError().getType())) {
        et = ErrorType.Service;
    }
    exception.setErrorType(et);
    exception.setRequestId(er.getRequestId());
    exception.setStatusCode(response.getStatus());
    exception.setServiceName("DNS53");
    throw exception;
}

From source file:com.netflix.edda.EddaAutoScalingClient.java

License:Apache License

public DescribeAutoScalingGroupsResult describeAutoScalingGroups(DescribeAutoScalingGroupsRequest request) {
    TypeReference<List<AutoScalingGroup>> ref = new TypeReference<List<AutoScalingGroup>>() {
    };//from w  w w  . ja  v a2s  .c o  m
    String url = config.url() + "/api/v2/aws/autoScalingGroups;_expand";
    try {
        List<AutoScalingGroup> autoScalingGroups = parse(ref, doGet(url));

        List<String> names = request.getAutoScalingGroupNames();
        if (shouldFilter(names)) {
            List<AutoScalingGroup> asgs = new ArrayList<AutoScalingGroup>();
            for (AutoScalingGroup asg : autoScalingGroups) {
                if (matches(names, asg.getAutoScalingGroupName()))
                    asgs.add(asg);
            }
            autoScalingGroups = asgs;
        }

        return new DescribeAutoScalingGroupsResult().withAutoScalingGroups(autoScalingGroups);
    } catch (IOException e) {
        throw new AmazonClientException("Faled to parse " + url, e);
    }
}

From source file:com.netflix.edda.EddaAutoScalingClient.java

License:Apache License

public DescribeLaunchConfigurationsResult describeLaunchConfigurations(
        DescribeLaunchConfigurationsRequest request) {
    TypeReference<List<LaunchConfiguration>> ref = new TypeReference<List<LaunchConfiguration>>() {
    };//from  w w w . ja v  a2s. c  o m
    String url = config.url() + "/api/v2/aws/launchConfigurations;_expand";
    try {
        List<LaunchConfiguration> launchConfigurations = parse(ref, doGet(url));

        List<String> names = request.getLaunchConfigurationNames();
        if (shouldFilter(names)) {
            List<LaunchConfiguration> lcs = new ArrayList<LaunchConfiguration>();
            for (LaunchConfiguration lc : launchConfigurations) {
                if (matches(names, lc.getLaunchConfigurationName()))
                    lcs.add(lc);
            }
            launchConfigurations = lcs;
        }

        return new DescribeLaunchConfigurationsResult().withLaunchConfigurations(launchConfigurations);
    } catch (IOException e) {
        throw new AmazonClientException("Faled to parse " + url, e);
    }
}

From source file:com.netflix.edda.EddaAutoScalingClient.java

License:Apache License

public DescribePoliciesResult describePolicies(DescribePoliciesRequest request) {
    TypeReference<List<ScalingPolicy>> ref = new TypeReference<List<ScalingPolicy>>() {
    };//from   w w  w. ja  v a2s  .c om
    String url = config.url() + "/api/v2/aws/scalingPolicies;_expand";
    try {
        List<ScalingPolicy> scalingPolicies = parse(ref, doGet(url));

        String asg = request.getAutoScalingGroupName();
        List<String> names = request.getPolicyNames();
        if (shouldFilter(asg) || shouldFilter(names)) {
            List<ScalingPolicy> sps = new ArrayList<ScalingPolicy>();
            for (ScalingPolicy sp : scalingPolicies) {
                if (matches(asg, sp.getAutoScalingGroupName()) && matches(names, sp.getPolicyName()))
                    sps.add(sp);
            }
            scalingPolicies = sps;
        }

        return new DescribePoliciesResult().withScalingPolicies(scalingPolicies);
    } catch (IOException e) {
        throw new AmazonClientException("Faled to parse " + url, e);
    }
}

From source file:com.netflix.edda.EddaCloudWatchClient.java

License:Apache License

public DescribeAlarmsResult describeAlarms(DescribeAlarmsRequest request) {
    validateEmpty("ActionPrefix", request.getActionPrefix());
    validateEmpty("AlarmNamePrefix", request.getAlarmNamePrefix());

    TypeReference<List<MetricAlarm>> ref = new TypeReference<List<MetricAlarm>>() {
    };/*from   w  ww . ja  va  2s  .  com*/
    String url = config.url() + "/api/v2/aws/alarms;_expand";
    try {
        List<MetricAlarm> metricAlarms = parse(ref, doGet(url));

        List<String> names = request.getAlarmNames();
        String state = request.getStateValue();
        if (shouldFilter(names) || shouldFilter(state)) {
            List<MetricAlarm> mas = new ArrayList<MetricAlarm>();
            for (MetricAlarm ma : metricAlarms) {
                if (matches(names, ma.getAlarmName()) && matches(state, ma.getStateValue()))
                    mas.add(ma);
            }
            metricAlarms = mas;
        }

        return new DescribeAlarmsResult().withMetricAlarms(metricAlarms);
    } catch (IOException e) {
        throw new AmazonClientException("Faled to parse " + url, e);
    }
}

From source file:com.netflix.edda.EddaEc2Client.java

License:Apache License

public DescribeClassicLinkInstancesResult describeClassicLinkInstances(
        DescribeClassicLinkInstancesRequest request) {
    validateEmpty("Filter", request.getFilters());

    TypeReference<List<ClassicLinkInstance>> ref = new TypeReference<List<ClassicLinkInstance>>() {
    };//from w  w  w.j  av  a 2s  . c o  m
    String url = config.url() + "/api/v2/aws/classicLinkInstances;_expand";
    try {
        List<ClassicLinkInstance> instances = parse(ref, doGet(url));

        List<String> ids = request.getInstanceIds();
        if (shouldFilter(ids)) {
            List<ClassicLinkInstance> is = new ArrayList<ClassicLinkInstance>();
            for (ClassicLinkInstance i : instances) {
                if (matches(ids, i.getInstanceId()))
                    is.add(i);
            }
            instances = is;
        }

        return new DescribeClassicLinkInstancesResult().withInstances(instances);
    } catch (IOException e) {
        throw new AmazonClientException("Faled to parse " + url, e);
    }
}