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.nesscomputing.httpclient.response.StringContentConverter.java

@Override
public String convert(HttpClientResponse httpClientResponse, InputStream inputStream) throws IOException {
    final int responseCode = httpClientResponse.getStatusCode();
    switch (responseCode) {
    case 200://from w  w w .ja  v a2  s.c o m
    case 201:
        final Charset charset = Charset.forName(Objects.firstNonNull(httpClientResponse.getCharset(), "UTF-8"));
        final InputStreamReader reader = new InputStreamReader(inputStream, charset);

        try {
            return CharStreams.toString(reader);
        } finally {
            Closeables.closeQuietly(reader);
        }

    case 204:
        return "";

    case 404:
        if (ignore404) {
            return "";
        }
        throw throwHttpResponseException(httpClientResponse);

    default:
        throw throwHttpResponseException(httpClientResponse);
    }
}

From source file:com.facebook.buck.java.ZipEntryJavaFileObject.java

/**
 * Returns the contents of the {@link ZipEntry} as a string. Ensures that the entry is read at
 * most once./* w ww.  ja va 2  s. co  m*/
 */
private synchronized String getContentsAsString() {
    if (contents != null) {
        return contents;
    }

    try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
        contents = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return contents;
}

From source file:org.hbz.oerworldmap.JsonDecoder.java

@Override
public void process(final Reader reader) {
    STARTED = false;//from www . j a  v a 2  s .  c  o m
    JsonDecoder.LOG.debug("############################ New");
    // necessary if it is JSONP
    String text;
    try {
        text = CharStreams.toString(reader);
        this.jsonParser = new JsonFactory().createParser(text);
        // find start
        JsonToken currentToken = null;
        try {
            currentToken = this.jsonParser.nextToken();
        } catch (final JsonParseException e) {
            // assuming JSONP :
            final String callbackString = text.substring(0, text.indexOf(JsonDecoder.JSON_START_CHAR) - 1);
            text = text.substring(text.indexOf(JsonDecoder.JSON_START_CHAR), text.length() - 1);
            this.jsonParser = new JsonFactory().createParser(text);
            JsonDecoder.LOG.debug("key=" + JsonDecoder.JSON_CALLBACK + " value=" + callbackString);
            getReceiver().startRecord("");
            STARTED = true;
            JSONP = true;
            getReceiver().literal(JsonDecoder.JSON_CALLBACK, callbackString);
            JsonDecoder.LOG.debug("Text=" + text);
            currentToken = this.jsonParser.nextToken();
        }
        while (JsonToken.START_OBJECT != currentToken) {
            this.jsonParser.nextToken();
        }

        String key = null;
        while (currentToken != null) {
            if (JsonToken.START_OBJECT == currentToken) {
                if (!STARTED) {
                    getReceiver().startRecord("");
                    STARTED = true;
                }
                currentToken = this.jsonParser.nextToken();
                while (currentToken != null) {
                    if (JsonToken.FIELD_NAME == currentToken) {
                        key = this.jsonParser.getCurrentName();
                    }
                    if (JsonToken.START_ARRAY == currentToken) {
                        if (this.JSONP) {
                            currentToken = this.jsonParser.nextToken();
                            currentToken = this.jsonParser.nextToken();
                        } else {
                            currentToken = this.jsonParser.nextToken();
                            // treat objects in arrays as new objects
                            if (JsonToken.START_OBJECT == currentToken) {
                                break;
                            }
                            // values of arrays are submitted with an index
                            // so
                            // you can handle
                            // semantics in the morph
                            int i = 0;
                            while (JsonToken.END_ARRAY != currentToken) {
                                final String value = this.jsonParser.getText();
                                JsonDecoder.LOG.debug("key=" + key + i + " valueArray=" + value);
                                getReceiver().literal(key + i, value);
                                currentToken = this.jsonParser.nextToken();
                                i++;
                            }
                        }
                    }
                    if (JsonToken.START_OBJECT == currentToken) {
                        if (this.jsonParser.getCurrentName() == null) {
                            break;
                        }
                    } else {
                        handleValue(currentToken, key);
                    }
                    try {
                        currentToken = this.jsonParser.nextToken();
                    } catch (JsonParseException jpe) {
                        LOG.info(
                                "JsonParseException happens at the end of an non JSON object, e.g. if it is JSONP",
                                jpe.getMessage());
                        currentToken = null;
                        break;
                    }
                }
            }
            JsonDecoder.LOG.debug("############################ End");
            if (STARTED) {
                getReceiver().endRecord();
                STARTED = false;

            }
        }
    } catch (final IOException e) {
        throw new MetafactureException(e);

    }
}

From source file:org.openscada.configurator.sec.utils.JSScriptParser.java

protected EObject parseContent(final InputStreamReader stream) throws IOException {
    final String value = CharStreams.toString(stream);

    final JavaScript script = SecurityFactory.eINSTANCE.createJavaScript();
    script.setSource(value);/*w  w w  .  j a va  2s. c o m*/

    return script;
}

From source file:google.registry.tools.AppEngineConnection.java

/** Returns the HTML from the connection error stream, if any, otherwise the empty string. */
private static String getErrorHtmlAsString(HttpResponse response) throws IOException {
    return CharStreams.toString(new InputStreamReader(response.getContent(), UTF_8));
}

From source file:org.ow2.proactive.scheduler.rest.readers.TaskResultReader.java

@Override
public Serializable readFrom(Class<Serializable> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    Closer closer = Closer.create();//w w w.  j  a  v a2 s .  c o m
    try {
        entityStream = closer.register(entityStream);
        return CharStreams.toString(new InputStreamReader(entityStream));
    } catch (IOException ioe) {
        throw closer.rethrow(ioe);
    } finally {
        closer.close();
    }
}

From source file:org.eclipse.che.api.workspace.server.WorkspaceConfigMessageBodyAdapter.java

@Override
public InputStream adapt(InputStream entityStream) throws WebApplicationException, IOException {
    try (Reader r = new InputStreamReader(entityStream)) {
        return new ByteArrayInputStream(adapt(CharStreams.toString(r)).getBytes(defaultCharset()));
    } catch (IllegalArgumentException x) {
        throw new WebApplicationException(x.getMessage(), x, BAD_REQUEST);
    } catch (RuntimeException x) {
        throw new WebApplicationException(x.getMessage(), x, INTERNAL_SERVER_ERROR);
    }/*from   w w  w . ja  v a 2 s  .  co m*/
}

From source file:org.apache.provisionr.core.templates.xml.XmlTemplate.java

/**
 * @return an XmlTemplate instance resulted from parsing a file
 *///from   w  w w  . ja  v  a 2 s.  c o  m
public static XmlTemplate newXmlTemplate(File file) {
    Reader reader = null;
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(file);
        reader = new InputStreamReader(inputStream, Charsets.UTF_8);

        return newXmlTemplate(CharStreams.toString(reader));

    } catch (IOException e) {
        throw Throwables.propagate(e);

    } finally {
        Closeables.closeQuietly(inputStream);
        Closeables.closeQuietly(reader);
    }
}

From source file:eu.esdihumboldt.hale.io.html.svg.mapping.MappingExporter.java

@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter)
        throws IOProviderConfigurationException, IOException {
    progress.begin("Generate mapping documentation", ProgressIndicator.UNKNOWN);

    // retrieve template URL
    URL templateUrl = getClass().getResource("mapping.html");

    // create template binding
    @SuppressWarnings("unchecked")
    Map<String, Object> binding = MappingDocumentation.createBinding(getProjectInfo(), getAlignment());

    // read javascript from file and store it in the binding
    StringBuilder js = new StringBuilder();
    try (Reader reader = new InputStreamReader(getClass().getResourceAsStream("snap.svg-min.js"),
            StandardCharsets.UTF_8)) {
        js.append(CharStreams.toString(reader));
    }//from   ww  w  .  j ava 2 s . c  om
    js.append("\n\n");
    try (Reader reader = new InputStreamReader(getClass().getResourceAsStream("render-mapping.js"),
            StandardCharsets.UTF_8)) {
        js.append(CharStreams.toString(reader));
    }
    binding.put("javascript", js.toString());

    // initialize template engine
    GStringTemplateEngine engine = new GStringTemplateEngine();

    // bind and write template
    try (Writer out = new OutputStreamWriter(getTarget().getOutput(), StandardCharsets.UTF_8)) {
        Writable template = engine.createTemplate(templateUrl).make(binding);
        template.writeTo(out);

        reporter.setSuccess(true);
    } catch (Exception e) {
        reporter.error(new IOMessageImpl("Error creating mapping documentation", e));
        reporter.setSuccess(false);
    } finally {
        progress.end();
    }

    return reporter;
}

From source file:com.facebook.buck.testutil.integration.ZipInspector.java

public void assertFileContents(String pathRelativeToRoot, String expected) throws IOException {
    try (ZipFile zipFile = new ZipFile(this.zipFile.toFile())) {
        ZipEntry entry = zipFile.getEntry(pathRelativeToRoot);
        assertThat(CharStreams.toString(new InputStreamReader(zipFile.getInputStream(entry))),
                Matchers.equalTo(expected));
    }/*  w  w w  . j  av  a2 s .c om*/
}