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.emc.vipr.services.s3.ViPRS3HttpClient.java

License:Open Source License

public ViPRS3HttpClient(ViPRS3Config viprConfig) {
    super(viprConfig.getClientConfiguration(), new SmartHttpClient(viprConfig.toSmartClientConfig()), null);

    ClientConfiguration azConfig = viprConfig.getClientConfiguration();
    HttpParams httpClientParams = httpClient.getParams();

    HttpConnectionParams.setConnectionTimeout(httpClientParams, azConfig.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, azConfig.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = azConfig.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = azConfig.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }/*  www. j  a  va2 s .c  om*/

    ClientConnectionManager connectionManager = httpClient.getConnectionManager();
    ((SmartHttpClient) httpClient).setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);
        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty(SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = azConfig.getProxyHost();
    int proxyPort = azConfig.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = azConfig.getProxyUsername();
        String proxyPassword = azConfig.getProxyPassword();
        String proxyDomain = azConfig.getProxyDomain();
        String proxyWorkstation = azConfig.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            ((SmartHttpClient) httpClient).getCredentialsProvider().setCredentials(
                    new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }

        // Add a request interceptor that sets up proxy authentication pre-emptively if configured
        if (azConfig.isPreemptiveBasicProxyAuth()) {
            ((SmartHttpClient) httpClient).addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0);
        }
    }
}

From source file:com.example.S3Sample02.java

License:Open Source License

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

    /*//  w w w.  java 2  s. c  o  m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (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 (~/.aws/credentials), and is in valid format.", e);
    }

    AmazonS3 s3 = new AmazonS3Client(credentials);

    //        AP_SOUTHEAST_2

    //       Region usWest2 = Region.getRegion(Regions.AP_SOUTHEAST_2 );
    //       s3.setRegion(usWest2);

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

    String bucketName = "imos-test-data-1";

    String key = "MyObjectKey" + UUID.randomUUID();

    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 (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()));

        System.out.println("done\n");

        /*
         * 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");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        System.out.println("done\n");

        /*
         * 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");
        ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();
        System.out.println("done\n");

        /*
         * 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 (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 "
                + "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.grublr.geo.GeoDataManager.java

License:Open Source License

/**
 * Query Amazon DynamoDB in parallel and filter the result.
 * //from ww  w . j  av a  2  s .  c o m
 * @param ranges
 *            A list of geohash ranges that will be used to query Amazon DynamoDB.
 * 
 * @param latLngRect
 *            The rectangle area that will be used as a reference point for precise filtering.
 * 
 * @return Aggregated and filtered items returned from Amazon DynamoDB.
 */
private GeoQueryResult dispatchQueries(List<GeohashRange> ranges, GeoQueryRequest geoQueryRequest) {
    GeoQueryResult geoQueryResult = new GeoQueryResult();

    ExecutorService executorService = config.getExecutorService();
    List<Future<?>> futureList = new ArrayList<Future<?>>();

    for (GeohashRange outerRange : ranges) {
        for (GeohashRange range : outerRange.trySplit(config.getHashKeyLength())) {
            GeoQueryThread geoQueryThread = new GeoQueryThread(geoQueryRequest, geoQueryResult, range);
            Future<?> fut = executorService.submit(geoQueryThread);
            futureList.add(fut);
        }
    }
    ranges = null;

    for (int i = 0; i < futureList.size(); i++) {
        try {
            futureList.get(i).get();
        } catch (Exception e) {
            for (int j = i + 1; j < futureList.size(); j++) {
                futureList.get(j).cancel(true);
            }
            throw new AmazonClientException("Querying Amazon DynamoDB failed.", e);
        }
    }
    futureList = null;

    return geoQueryResult;
}

From source file:com.hussi.aws.dynamoDB.AmazonDynamoDBSample.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials
 * consisting of the AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints, are performed
 * automatically. Client parameters, such as proxies, can be specified in an
 * optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.ProfilesConfigFile
 * @see com.amazonaws.ClientConfiguration
 *//*from   www.java2  s.c  o  m*/
private static void init() throws Exception {
    /*
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().getCredentials();
        System.out.println("credentials.getAWSAccessKeyId()===>>>" + credentials.getAWSAccessKeyId());
        System.out.println("credentials.getAWSSecretKey()===>>>" + credentials.getAWSSecretKey());
        //System.exi   t(0);

    } catch (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 (~/.aws/credentials), and is in valid format.", e);
    }
    dynamoDB = new AmazonDynamoDBClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    dynamoDB.setRegion(usWest2);
}

From source file:com.ibm.og.s3.v4.AwsChunkedEncodingInputStream.java

License:Open Source License

private byte[] createSignedChunk(final byte[] chunkData) {
    final StringBuilder chunkHeader = new StringBuilder();
    // chunk-size
    chunkHeader.append(Integer.toHexString(chunkData.length));

    byte[] chunkDigest;
    if (this.digestCache != null) {
        try {// ww w.  ja v  a 2s.  c  o  m
            chunkDigest = this.digestCache.get((long) chunkData.length);
        } catch (final ExecutionException e) {
            throw new RuntimeException(e);
        }
    } else {
        chunkDigest = this.sha256.digest(chunkData);
    }

    // sig-extension
    final String chunkStringToSign = CHUNK_STRING_TO_SIGN_PREFIX + "\n" + this.dateTime + "\n" + this.keyPath
            + "\n" + this.priorChunkSignature + "\n" + AbstractAWSSigner.EMPTY_STRING_SHA256_HEX + "\n"
            + BinaryUtils.toHex(chunkDigest);

    final String chunkSignature = BinaryUtils
            .toHex(this.aws4Signer.signWithMac(chunkStringToSign, this.hmacSha256));
    this.priorChunkSignature = chunkSignature;
    chunkHeader.append(CHUNK_SIGNATURE_HEADER).append(chunkSignature).append(CRLF);
    try {
        final byte[] header = chunkHeader.toString().getBytes(UTF8);
        final byte[] trailer = CRLF.getBytes(UTF8);
        final byte[] signedChunk = new byte[header.length + chunkData.length + trailer.length];
        System.arraycopy(header, 0, signedChunk, 0, header.length);
        System.arraycopy(chunkData, 0, signedChunk, header.length, chunkData.length);
        System.arraycopy(trailer, 0, signedChunk, header.length + chunkData.length, trailer.length);
        return signedChunk;
    } catch (final Exception e) {
        throw new AmazonClientException("Unable to sign the chunked data. " + e.getMessage(), e);
    }
}

From source file:com.ibm.og.s3.v4.AWSS3V4Signer.java

License:Open Source License

/**
 * Returns the pre-defined header value and set other necessary headers if the request needs to be
 * chunk-encoded. Otherwise calls the superclass method which calculates the hash of the whole
 * content for signing./*from  w  w w.j ava 2  s  .  c  o m*/
 */
@Override
protected String calculateContentHash(final SignableRequest<?> request) {
    // To be consistent with other service clients using sig-v4,
    // we just set the header as "required", and AWS4Signer.sign() will be
    // notified to pick up the header value returned by this method.
    request.addHeader(X_AMZ_CONTENT_SHA256, "required");
    final String contentLength = request.getHeaders().get(Headers.CONTENT_LENGTH);
    if (useChunkEncoding(request)) {
        final long originalContentLength;
        if (contentLength != null) {
            originalContentLength = Long.parseLong(contentLength);
        } else {
            /**
             * "Content-Length" header could be missing if the caller is uploading a stream without
             * setting Content-Length in ObjectMetadata. Before using sigv4, we rely on HttpClient to
             * add this header by using BufferedHttpEntity when creating the HttpRequest object. But
             * now, we need this information immediately for the signing process, so we have to cache
             * the stream here.
             */
            try {
                originalContentLength = getContentLength(request);
            } catch (final IOException e) {
                throw new AmazonClientException("Cannot get the content-length of the request content.", e);
            }
        }
        request.addHeader("x-amz-decoded-content-length", Long.toString(originalContentLength));
        // Make sure "Content-Length" header is not empty so that HttpClient
        // won't cache the stream again to recover Content-Length
        request.addHeader(Headers.CONTENT_LENGTH, Long
                .toString(AwsChunkedEncodingInputStream.calculateStreamContentLength(originalContentLength)));
        return CONTENT_SHA_256;
    }

    if (this.digestCache != null) {
        try {
            final long length = contentLength != null ? Long.parseLong(contentLength) : 0;
            return BinaryUtils.toHex(this.digestCache.get(length));
        } catch (final ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
    return super.calculateContentHash(request);
}

From source file:com.imos.sample.S3SampleCheck.java

License:Open Source License

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

    /*//from   ww  w. j  a  v a  2s . c o  m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (/home/alok/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("default").getCredentials();
    } catch (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 (/home/alok/.aws/credentials), and is in valid format.", e);
    }

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

    String bucketName = "alok-test";
    String key = "sample.json";

    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 (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()));
        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");
        //            S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        S3Object object = s3.getObject(new GetObjectRequest("alok-test", 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");
        ObjectListing objectListing = s3.listObjects(new ListObjectsRequest()
                //                    .withBucketName(bucketName)
                .withBucketName("alok-test"));
        //                    .withPrefix("My"));
        objectListing.getObjectSummaries().forEach((objectSummary) -> {
            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 (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 "
                + "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.intrinsicMetric.aws.AwsConsoleApp.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials
 * consisting of the AWS Access Key ID and Secret Access Key. All other
 * configuration, such as the service endpoints, are performed
 * automatically. Client parameters, such as proxies, can be specified in an
 * optional ClientConfiguration object when constructing a client.
 *
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.PropertiesCredentials
 * @see com.amazonaws.ClientConfiguration
 *///from  w w  w . j av  a  2 s  .com
private static void init() throws Exception {

    /*
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (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 (~/.aws/credentials), and is in valid format.", e);
    }
    ec2 = new AmazonEC2Client(credentials);
    s3 = new AmazonS3Client(credentials);
    sdb = new AmazonSimpleDBClient(credentials);
}

From source file:com.ivona.services.tts.model.transform.createspeech.CreateSpeechPostRequestMarshaller.java

License:Open Source License

private void setRequestPayload(Request<CreateSpeechRequest> request, CreateSpeechRequest createSpeechRequest) {
    try {/*from   ww w.  j  a v a2  s .  c  om*/
        StringWriter stringWriter = new StringWriter();
        JSONWriter jsonWriter = new JSONWriter(stringWriter);

        jsonWriter.object();

        if (createSpeechRequest.getInput() != null) {
            Input input = createSpeechRequest.getInput();

            jsonWriter.key(JSON_KEY_INPUT);
            jsonWriter.object();
            if (input.getData() != null) {
                jsonWriter.key(JSON_KEY_INPUT_DATA).value(input.getData());
            }
            if (input.getType() != null) {
                jsonWriter.key(JSON_KEY_INPUT_TYPE).value(input.getType());
            }
            jsonWriter.endObject();
        }

        if (createSpeechRequest.getOutputFormat() != null) {
            OutputFormat outputFormat = createSpeechRequest.getOutputFormat();

            jsonWriter.key(JSON_KEY_OUTPUT_FORMAT);
            jsonWriter.object();
            if (outputFormat.getCodec() != null) {
                jsonWriter.key(JSON_KEY_OUTPUT_FORMAT_CODEC).value(outputFormat.getCodec());
            }
            if (outputFormat.getSampleRate() != null && outputFormat.getSampleRate() > 0) {
                jsonWriter.key(JSON_KEY_OUTPUT_FORMAT_SAMPLE_RATE).value((long) outputFormat.getSampleRate());
            }
            if (outputFormat.getSpeechMarks() != null) {
                jsonWriter.key(JSON_KEY_OUTPUT_FORMAT_SPEECHMARKS);
                jsonWriter.object();
                SpeechMarks speechMarks = outputFormat.getSpeechMarks();
                if (speechMarks != null) {
                    if (speechMarks.isSentence()) {
                        jsonWriter.key(JSON_KEY_OUTPUT_FORMAT_SPEECHMARKS_SENTENCE).value(true);
                    }
                    if (speechMarks.isSsml()) {
                        jsonWriter.key(JSON_KEY_OUTPUT_FORMAT_SPEECHMARKS_SSML).value(true);
                    }
                    if (speechMarks.isViseme()) {
                        jsonWriter.key(JSON_KEY_OUTPUT_FORMAT_SPEECHMARKS_VISEME).value(true);
                    }
                    if (speechMarks.isWord()) {
                        jsonWriter.key(JSON_KEY_OUTPUT_FORMAT_SPEECHMARKS_WORD).value(true);
                    }
                }
                jsonWriter.endObject();
            }
            jsonWriter.endObject();
        }

        if (createSpeechRequest.getParameters() != null) {
            Parameters parameters = createSpeechRequest.getParameters();

            jsonWriter.key(JSON_KEY_PARAMETERS);
            jsonWriter.object();
            if (parameters.getRate() != null) {
                jsonWriter.key(JSON_KEY_PARAMETERS_RATE).value(parameters.getRate());
            }
            if (parameters.getVolume() != null) {
                jsonWriter.key(JSON_KEY_PARAMETERS_VOLUME).value(parameters.getVolume());
            }
            if (parameters.getSentenceBreak() != null) {
                jsonWriter.key(JSON_KEY_PARAMETERS_SENTENCE_BREAK).value((long) parameters.getSentenceBreak());
            }
            if (parameters.getParagraphBreak() != null) {
                jsonWriter.key(JSON_KEY_PARAMETERS_PARAGRAPH_BREAK)
                        .value((long) parameters.getParagraphBreak());
            }
            jsonWriter.endObject();
        }

        if (createSpeechRequest.getLexiconNames() != null) {
            List<String> names = createSpeechRequest.getLexiconNames();
            jsonWriter.key(JSON_KEY_LEXICONS).value(names);
        }

        if (createSpeechRequest.getVoice() != null) {
            Voice voice = createSpeechRequest.getVoice();

            jsonWriter.key(JSON_KEY_VOICE);
            jsonWriter.object();
            if (voice.getGender() != null) {
                jsonWriter.key(JSON_KEY_VOICE_GENDER).value(voice.getGender());
            }
            if (voice.getLanguage() != null) {
                jsonWriter.key(JSON_KEY_VOICE_LANGUAGE).value(voice.getLanguage());
            }
            if (voice.getName() != null) {
                jsonWriter.key(JSON_KEY_VOICE_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 (JSONException e) {
        throw new AmazonClientException("Unable to marshall request to JSON", e);
    } catch (UnsupportedEncodingException e) {
        throw new AmazonClientException("Unable to marshall request to JSON", e);
    }
}

From source file:com.ivona.services.tts.model.transform.lexicons.ListLexiconsPostRequestMarshaller.java

License:Open Source License

private void setRequestPayload(Request<ListLexiconsRequest> request, ListLexiconsRequest listLexiconsRequest) {
    StringWriter stringWriter = new StringWriter();
    JSONWriter jsonWriter = new JSONWriter(stringWriter);

    try {/* ww  w .  j  a va 2  s  .c  o  m*/
        jsonWriter.object();
        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 (JSONException e) {
        throw new AmazonClientException("Unable to marshall request to JSON", e);
    } catch (UnsupportedEncodingException e) {
        throw new AmazonClientException("Unable to marshall request to JSON", e);
    }
}