Example usage for com.google.common.io CharStreams toString

List of usage examples for com.google.common.io CharStreams toString

Introduction

In this page you can find the example usage for com.google.common.io CharStreams toString.

Prototype

public static String toString(Readable r) throws IOException 

Source Link

Document

Reads all characters from a Readable object into a String .

Usage

From source file:com.example.appengine.firetactoe.FirebaseChannel.java

/**
 * Construct the singleton, with derived auth information. The Firebase database url is derived
 * from the snippet that we provide to the client code, to guarantee that the client and the
 * server are communicating with the same Firebase database. The auth credentials we'll use to
 * communicate with Firebase is derived from App Engine's default credentials, and given
 * Firebase's OAuth scopes./*from ww  w . j  a  va 2s .  c  om*/
 */
private FirebaseChannel() {
    try {
        // This variables exist primarily so it can be stubbed out in unit tests.
        if (null == firebaseConfigStream) {
            firebaseConfigStream = new FileInputStream(FIREBASE_SNIPPET_PATH);
        }

        String firebaseSnippet = CharStreams
                .toString(new InputStreamReader(firebaseConfigStream, StandardCharsets.UTF_8));
        firebaseDbUrl = parseFirebaseUrl(firebaseSnippet);

        credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES);
        httpTransport = UrlFetchTransport.getDefaultInstance();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:ee.ria.xroad.monitor.executablelister.AbstractExecLister.java

/**
 * Method for testability/* w w w . j ava 2 s. c o  m*/
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
ProcessOutputs executeProcess() throws IOException, InterruptedException {

    ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", getCommand());

    Process p = b.start();
    p.waitFor();
    ProcessOutputs outputs = new ProcessOutputs();
    // need to read all of output everytime, reading it partially causes bad problems
    outputs.setOut(CharStreams.toString(new InputStreamReader(p.getInputStream())).replace("'", ""));
    outputs.setErr(CharStreams.toString(new InputStreamReader(p.getErrorStream())));
    return outputs;
}

From source file:com.facebook.buck.util.network.BlockingHttpEndpoint.java

@VisibleForTesting
HttpResponse send(final HttpURLConnection connection, final String content) throws IOException {
    try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
        out.writeBytes(content);/*www .ja va2s  .  co  m*/
        out.flush();
        out.close();
        InputStream inputStream = connection.getInputStream();
        String response = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
        return new HttpResponse(response);
    } finally {
        connection.disconnect();
    }
}

From source file:org.glowroot.tests.WebDriverIT.java

static String httpGet(String url) throws Exception {
    try (CloseableHttpResponse response = httpClient.execute(new HttpGet(url));
            InputStream responseContent = response.getEntity().getContent()) {
        String content = CharStreams.toString(new InputStreamReader(responseContent, UTF_8));
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new AssertionError("Unexpected status code: " + statusCode);
        }/* w w  w . ja  v a 2 s.co  m*/
        return content;
    }
}

From source file:de.dentrassi.pm.sec.service.common.SecurityMailService.java

private String loadAndFill(final String resource, final Map<String, ?> model, final URL url) {
    if (url == null) {
        return null;
    }/*from w w  w  . j a v a 2  s .c  o m*/

    String data;
    try (InputStream is = url.openStream(); Reader r = new InputStreamReader(is, StandardCharsets.UTF_8)) {
        data = CharStreams.toString(r);
    } catch (final Exception e) {
        logger.warn("Failed to process mail content", e);
        throw new RuntimeException("Failed to load mail content: " + resource, e);
    }

    if (model != null) {
        data = StringReplacer.replace(data, StringReplacer.newExtendedSource(model),
                StringReplacer.DEFAULT_PATTERN, true);
    }
    return data;
}

From source file:com.matthewmitchell.peercoinj.shapeshift.AsyncHttpClient.java

/**
 * Make an HTTP post request//from ww w.  j  a v a  2 s .c  om
 *
 * @params url A string of the URL to make an HTTP post request to
 * @params postData A string of the post data
 * @params contentType A string of the content mime type to be used with the Content-Type header
 * @params cbks Callbacks for successful or unsuccessful responses
 */
public void post(final String url, final String postData, final String contentType,
        final HttpResponseCallbacks cbks) {

    executor.execute(new Runnable() {

        @Override
        public void run() {

            try {

                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                connection.addRequestProperty("Accept-Encoding", "gzip");

                if (postData != null) {
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Content-Type", contentType);
                    connection.setDoOutput(true);
                    OutputStream os = connection.getOutputStream();
                    os.write(postData.getBytes(Charsets.UTF_8));
                    os.flush();
                    os.close();
                }

                connection.connect();

                final int responseCode = connection.getResponseCode();

                if (responseCode != HttpURLConnection.HTTP_OK) {
                    cbks.onFailure(responseCode, connection.getResponseMessage());
                    return;
                }

                final String contentEncoding = connection.getContentEncoding();

                InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
                if ("gzip".equalsIgnoreCase(contentEncoding))
                    is = new GZIPInputStream(is);

                Reader reader = new InputStreamReader(is, Charsets.UTF_8);
                String result = CharStreams.toString(reader);

                cbks.onSuccess(result);

            } catch (IOException ex) {
                cbks.onFailure(CONNECTION_ERROR, "");
            }
        }

    });

}

From source file:me.tfeng.toolbox.dust.NashornEngine.java

private String readAndClose(InputStream stream) throws IOException {
    try {/*from   www . j a  v a 2 s. c  o m*/
        return CharStreams.toString(new InputStreamReader(stream, Constants.UTF8));
    } finally {
        stream.close();
    }
}

From source file:ddf.catalog.registry.transformer.RegistryTransformer.java

@Override
public Metacard transform(InputStream inputStream, String id) throws IOException, CatalogTransformerException {

    MetacardImpl metacard;/*ww  w  . j  av a  2 s .  co m*/

    try (FileBackedOutputStream fileBackedOutputStream = new FileBackedOutputStream(1000000)) {

        try {
            IOUtils.copy(inputStream, fileBackedOutputStream);

        } catch (IOException e) {
            throw new CatalogTransformerException(
                    "Unable to transform from CSW RIM Service Record to Metacard. Error reading input stream.",
                    e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }

        try (InputStream inputStreamCopy = fileBackedOutputStream.asByteSource().openStream()) {
            metacard = (MetacardImpl) unmarshal(inputStreamCopy);
        } catch (ParserException e) {
            throw new CatalogTransformerException(
                    "Unable to transform from CSW RIM Service Record to Metacard. Parser exception caught", e);
        } catch (RegistryConversionException e) {
            throw new CatalogTransformerException(
                    "Unable to transform from CSW RIM Service Record to Metacard. Conversion exception caught",
                    e);
        }

        if (metacard == null) {
            throw new CatalogTransformerException(
                    "Unable to transform from CSW RIM Service Record to Metacard.");
        } else if (StringUtils.isNotEmpty(id)) {
            metacard.setAttribute(Metacard.ID, id);
        }

        String xml = CharStreams
                .toString(fileBackedOutputStream.asByteSource().asCharSource(Charsets.UTF_8).openStream());

        metacard.setAttribute(Metacard.METADATA, xml);
        metacard.setTags(Collections.singleton(RegistryConstants.REGISTRY_TAG));

    } catch (IOException e) {
        throw new CatalogTransformerException(
                "Unable to transform from CSW RIM Service Record to Metacard. Error using file-backed stream.",
                e);
    }

    return metacard;
}

From source file:org.fenixedu.academic.ui.struts.action.commons.ects.EctsTableFilter.java

public String getContent() throws IOException {
    if (content == null) {
        if (getInputStream() == null) {
            throw new IOException();
        }//from w w w  .  j a v  a 2 s. com
        content = CharStreams.toString(new InputStreamReader(getInputStream(), Charset.defaultCharset()));
    }
    return content;
}

From source file:org.terasology.rendering.assets.shader.GLSLShaderFormat.java

private String readInput(AssetDataFile input) throws IOException {
    try (InputStreamReader reader = new InputStreamReader(input.openStream(), Charsets.UTF_8)) {
        return CharStreams.toString(reader);
    }/*from  w w w . ja  v  a  2s  . c  o  m*/
}