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.microsoft.rest.interceptors.LoggingInterceptor.java

@Override
public Response intercept(Chain chain) throws IOException {
    // get logger
    Request request = chain.request();
    String context = request.header(LOGGING_HEADER);
    if (context == null) {
        context = "";
    }/*  w  w  w  .j  a v  a  2  s . c  om*/
    Logger logger = LoggerFactory.getLogger(context);

    // log URL
    if (logLevel != LogLevel.NONE) {
        log(logger, String.format("--> %s %s", request.method(), request.url()));
    }
    // log headers
    if (logLevel == LogLevel.HEADERS || logLevel == LogLevel.BODY_AND_HEADERS) {
        for (String header : request.headers().names()) {
            if (!LOGGING_HEADER.equals(header)) {
                log(logger, String.format("%s: %s", header, Joiner.on(", ").join(request.headers(header))));
            }
        }
    }
    // log body
    if (logLevel == LogLevel.BODY || logLevel == LogLevel.BODY_AND_HEADERS) {
        if (request.body() != null) {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);

            Charset charset = Charset.forName("UTF8");
            MediaType contentType = request.body().contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }

            if (isPlaintext(buffer)) {
                String content = buffer.clone().readString(charset);
                if (logLevel.isPrettyJson()) {
                    try {
                        content = MAPPER.writerWithDefaultPrettyPrinter()
                                .writeValueAsString(MAPPER.readValue(content, JsonNode.class));
                    } catch (Exception e) {
                        // swallow, keep original content
                    }
                }
                log(logger, String.format("%s-byte body:\n%s", request.body().contentLength(), content));
                log(logger, "--> END " + request.method());
            } else {
                log(logger, "--> END " + request.method() + " (binary " + request.body().contentLength()
                        + "-byte body omitted)");
            }
        }
    }

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        log(logger, "<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";

    // log URL
    if (logLevel != LogLevel.NONE) {
        log(logger, String.format("<-- %s %s %s (%s ms, %s body)", response.code(), response.message(),
                response.request().url(), tookMs, bodySize));
    }

    // log headers
    if (logLevel == LogLevel.HEADERS || logLevel == LogLevel.BODY_AND_HEADERS) {
        for (String header : response.headers().names()) {
            log(logger, String.format("%s: %s", header, Joiner.on(", ").join(response.headers(header))));
        }
    }

    // log body
    if (logLevel == LogLevel.BODY || logLevel == LogLevel.BODY_AND_HEADERS) {
        if (response.body() != null) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = Charset.forName("UTF8");
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(charset);
                } catch (UnsupportedCharsetException e) {
                    log(logger, "Couldn't decode the response body; charset is likely malformed.");
                    log(logger, "<-- END HTTP");
                    return response;
                }
            }

            boolean gzipped = response.header("content-encoding") != null
                    && StringUtils.containsIgnoreCase(response.header("content-encoding"), "gzip");
            if (!isPlaintext(buffer) && !gzipped) {
                log(logger, "<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }

            if (contentLength != 0) {
                String content;
                if (gzipped) {
                    content = CharStreams
                            .toString(new InputStreamReader(new GZIPInputStream(buffer.clone().inputStream())));
                } else {
                    content = buffer.clone().readString(charset);
                }
                if (logLevel.isPrettyJson()) {
                    try {
                        content = MAPPER.writerWithDefaultPrettyPrinter()
                                .writeValueAsString(MAPPER.readValue(content, JsonNode.class));
                    } catch (Exception e) {
                        // swallow, keep original content
                    }
                }
                log(logger, String.format("%s-byte body:\n%s", buffer.size(), content));
            }
            log(logger, "<-- END HTTP");
        }
    }
    return response;
}

From source file:org.prebake.util.PbTestCase.java

public static String fileSystemToAsciiArt(FileSystem fs, final int contentLimit) {
    final StringBuilder sb = new StringBuilder();
    for (Path root : fs.getRootDirectories()) {
        java.nio.file.Files.walkFileTree(root, new FileVisitor<Path>() {
            private int indent;

            public FileVisitResult postVisitDirectory(Path d, IOException ex) {
                --indent;//from www .  j a va2  s .  com
                return FileVisitResult.CONTINUE;
            }

            public FileVisitResult preVisitDirectory(Path d) {
                indent();
                if ("/".equals(d.getName().toString())) {
                    sb.append("/\n");
                } else {
                    sb.append(d.getName()).append('/').append('\n');
                }
                ++indent;
                return FileVisitResult.CONTINUE;
            }

            public FileVisitResult preVisitDirectoryFailed(Path d, IOException ex) {
                ex.printStackTrace();
                indent();
                if ("/".equals(d.getName().toString())) {
                    sb.append("/ ?\n");
                } else {
                    sb.append(d.getName()).append("/ ?\n");
                }
                return FileVisitResult.CONTINUE;
            }

            public FileVisitResult visitFile(Path f, BasicFileAttributes atts) {
                indent();
                String content = null;
                sb.append(f.getName());
                try {
                    Reader r = new InputStreamReader(f.newInputStream(), Charsets.UTF_8);
                    try {
                        content = CharStreams.toString(r);
                    } finally {
                        r.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                if (content != null && !"".equals(content)) {
                    if (content.length() <= contentLimit) {
                        sb.append(' ');
                        JsonSink.stringify(content, sb);
                    } else {
                        sb.append(" \"...\"");
                    }
                }
                sb.append('\n');
                return FileVisitResult.CONTINUE;
            }

            public FileVisitResult visitFileFailed(Path f, IOException ex) {
                ex.printStackTrace();
                indent();
                sb.append(f.getName()).append(" ?\n");
                return FileVisitResult.CONTINUE;
            }

            private void indent() {
                for (int i = indent; --i >= 0;) {
                    sb.append("  ");
                }
            }
        });
    }
    return sb.toString();
}

From source file:org.apache.kudu.client.MiniKdc.java

/**
 * Returns the output from the 'klist' utility. This is useful for logging the
 * local ticket cache state./*from www  .jav a 2s.c  o m*/
 */
String klist() throws IOException {
    Process proc = startProcessWithKrbEnv(getBinaryPath("klist"), "-A");
    checkReturnCode(proc, "klist", false);
    return CharStreams.toString(new InputStreamReader(proc.getInputStream()));
}

From source file:tests.SearchTestsHarness.java

private static String config() {
    String res = null;/*from w w  w . j  a va 2s .  c  om*/
    try {
        final InputStream config = new FileInputStream(TEST_CONFIG);
        try (InputStreamReader reader = new InputStreamReader(config, "UTF-8")) {
            res = CharStreams.toString(reader);
        }
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    return res;
}

From source file:org.obm.push.protocol.data.MSEmailEncoder.java

@VisibleForTesting
void encodeData(MSEmailBody body, Element bodyElement) throws IOException {
    Optional<SerializableInputStream> dataStream = body.getMimeData();
    if (!dataStream.isPresent()) {
        return;/*from  www .ja va  2s.  co m*/
    }

    if (body.getBodyType().isCDataEncoded()) {
        DOMUtils.createElementAndCDataText(bodyElement, ASAirs.DATA.asASValue(), dataStream.get(),
                body.getCharset());
    } else {
        String html = CharStreams.toString(new InputStreamReader(dataStream.get(), body.getCharset()));
        DOMUtils.createElementAndText(bodyElement, ASAirs.DATA.asASValue(), html);
    }
}

From source file:ch.digitalfondue.stampo.ServeAndWatch.java

private static String getReloadScript() {
    try (InputStream is = ServeAndWatch.class.getClassLoader().getResourceAsStream("stampo-reload-script.js")) {
        return CharStreams.toString(new InputStreamReader(is, UTF_8));
    } catch (IOException e) {
        throw new IllegalStateException("cannot read stampo-reload-script.js", e);
    }//from ww w. j a  v a 2s.c  o m
}

From source file:br.com.caelum.vraptor.serialization.gson.GsonDeserialization.java

private String getContentOfStream(InputStream input) throws IOException {
    String charset = getRequestCharset();
    logger.debug("Using charset {}", charset);

    return CharStreams.toString(new InputStreamReader(input, charset));
}

From source file:me.tfeng.play.plugins.DustPlugin.java

private String readAndClose(InputStream stream) {
    try {//w ww  .  j  a v a 2s.c o  m
        return CharStreams.toString(new InputStreamReader(stream, Constants.UTF8));
    } catch (IOException e) {
        throw new RuntimeException("Unable to read from stream", e);
    } finally {
        try {
            stream.close();
        } catch (IOException e) {
            throw new RuntimeException("Unable to close stream", e);
        }
    }
}

From source file:com.clarkparsia.fourstore.sesame.FourStoreRepositoryConnection.java

/**
 * @inheritDoc/*from   w w w  . j  av  a2 s  .  com*/
 */
@Override
public void add(final Reader theReader, final String theBaseURI, final RDFFormat theRDFFormat,
        final Resource... theContexts) throws IOException, RDFParseException, RepositoryException {
    // this is not terribly efficient, reading in the contents of the reader like this.  but our 4store api doesn't
    // expose something to handle Reader's since you cannot pass a Reader to an HTTPConnection.
    // could always do something like this:  http://www.koders.com/java/fid0A51E45C950B2B8BD9365C19F2626DE35EC09090.aspx

    add(new ByteArrayInputStream(CharStreams.toString(theReader).getBytes(Charsets.UTF_8)), theBaseURI,
            theRDFFormat, theContexts);
}

From source file:com.dtolabs.rundeck.core.execution.ExecutionServiceImpl.java

public NodeStepResult executeNodeStep(StepExecutionContext context, NodeStepExecutionItem item, INodeEntry node)
        throws NodeStepException {

    final NodeStepExecutor interpreter;
    try {//from  ww  w  .ja  va 2s.  c  om
        interpreter = framework.getNodeStepExecutorForItem(item);
    } catch (ExecutionServiceException e) {
        throw new NodeStepException(e, ServiceFailureReason.ServiceFailure, node.getNodename());
    }

    if (null != getWorkflowListener(context)) {
        getWorkflowListener(context).beginExecuteNodeStep(context, item, node);
    }
    //create node context for node and substitute data references in command
    boolean secureOptionReplaced = false;
    Map<String, String> nodeDeferredOptions = context.getDataContext().get("nodeDeferred");
    Map<String, String> options = context.getDataContext().get("option");
    if (nodeDeferredOptions != null) {
        for (String key : nodeDeferredOptions.keySet()) {
            String val = nodeDeferredOptions.get(key);
            if (options != null && options.containsKey(key)) {
                String currentValue = options.get(key);
                if (currentValue.equals(val)) {
                    //replace node references
                    val = SharedDataContextUtils.replaceDataReferences(val, context.getSharedDataContext(),
                            //add node name to qualifier to read node-data first
                            ContextView.node(node.getNodename()), ContextView::nodeStep,
                            DataContextUtils.replaceMissingOptionsWithBlank, false, false);
                    try {
                        InputStream defaultVal = context.getStorageTree().getResource(val).getContents()
                                .getInputStream();
                        String pass = CharStreams.toString(new InputStreamReader(defaultVal, Charsets.UTF_8));
                        context.getDataContext().get("option").put(key, pass);
                        secureOptionReplaced = true;
                    } catch (IOException ex) {
                        throw new NodeStepException(ex, StepFailureReason.Unknown, node.getNodename());
                    }
                }
            }
        }
    }

    NodeStepResult result = null;
    try {
        final ExecutionContextImpl nodeContext;
        if (secureOptionReplaced) {
            nodeContext = new ExecutionContextImpl.Builder(context).singleNodeContext(node, true)
                    .sharedDataContext(
                            WFSharedContext.with(ContextView.global(), context.getDataContextObject()))
                    .build();
        } else {
            nodeContext = new ExecutionContextImpl.Builder(context).singleNodeContext(node, true).build();
        }

        PluginLoggingManager pluginLogging = null;
        if (null != context.getLoggingManager()) {
            pluginLogging = context.getLoggingManager().createPluginLogging(nodeContext, item);
        }
        if (null != pluginLogging) {
            pluginLogging.begin();
        }
        try {
            context.getPluginControlService().checkDisabledPlugin(item.getNodeStepType(),
                    ServiceNameConstants.WorkflowNodeStep);
            result = interpreter.executeNodeStep(nodeContext, item, node);
        } finally {
            if (null != pluginLogging) {
                pluginLogging.end();
            }
        }
        if (!result.isSuccess()) {
            context.getExecutionListener().log(0, "Failed: " + result.toString());
        }
    } catch (NodeStepException e) {
        result = new NodeStepResultImpl(e, e.getFailureReason(), e.getMessage(), node);
        throw e;
    } catch (Throwable t) {
        result = new NodeStepResultImpl(t, StepFailureReason.Unknown, t.getMessage(), node);
        throw new NodeStepException(t, StepFailureReason.Unknown, node.getNodename());
    } finally {
        if (null != getWorkflowListener(context)) {
            getWorkflowListener(context).finishExecuteNodeStep(result, context, item, node);
        }
    }
    return result;
}