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:org.eclipse.xtend.core.macro.AbstractFileSystemSupport.java

@Override
public CharSequence getContents(final Path path) {
    try {/*from   ww w . j  a v  a2  s  .c o  m*/
        InputStream _contentsAsStream = this.getContentsAsStream(path);
        String _charset = this.getCharset(path);
        final InputStreamReader reader = new InputStreamReader(_contentsAsStream, _charset);
        IOException threw = null;
        try {
            return CharStreams.toString(reader);
        } catch (final Throwable _t) {
            if (_t instanceof IOException) {
                final IOException e = (IOException) _t;
                threw = e;
            } else {
                throw Exceptions.sneakyThrow(_t);
            }
        } finally {
            try {
                reader.close();
            } catch (final Throwable _t_1) {
                if (_t_1 instanceof IOException) {
                    final IOException e_1 = (IOException) _t_1;
                    if ((threw == null)) {
                        threw = e_1;
                    }
                } else {
                    throw Exceptions.sneakyThrow(_t_1);
                }
            }
        }
        if ((threw == null)) {
            throw new AssertionError("threw cannot be null here");
        }
        throw threw;
    } catch (final Throwable _t_2) {
        if (_t_2 instanceof IOException) {
            final IOException exc = (IOException) _t_2;
            String _message = exc.getMessage();
            throw new IllegalArgumentException(_message, exc);
        } else {
            throw Exceptions.sneakyThrow(_t_2);
        }
    }
}

From source file:org.terasology.asset.loaders.GLSLShaderLoader.java

private String readUrl(URL url) throws IOException {
    InputStream stream = url.openStream();
    InputStreamReader reader = new InputStreamReader(stream);
    try {//from  www. j  ava 2  s  .  co m
        return CharStreams.toString(reader);
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Failed to close stream", e);
        }
    }
}

From source file:com.google.devtools.j2objc.util.FileUtil.java

public static String readFile(InputFile file) throws IOException {
    return CharStreams.toString(file.openReader());
}

From source file:com.google.template.soy.javasrc.dyncompile.InMemoryJavaFileObject.java

@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
    return CharStreams.toString(openReader(ignoreEncodingErrors));
}

From source file:org.geosdi.geoplatform.connector.server.request.PostConnectorRequest.java

@Override
public String getResponseAsString() throws Exception {
    String content;/*from ww  w  . ja  v  a2  s.com*/

    HttpPost httpPost = this.getPostMethod();
    CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpPost);
    HttpEntity responseEntity = httpResponse.getEntity();

    if (responseEntity != null) {
        InputStream is = responseEntity.getContent();
        content = CharStreams.toString(new InputStreamReader(is, UTF_8));
        EntityUtils.consume(responseEntity);
    } else {
        throw new IllegalStateException("Connector Server Error: Connection problem");
    }
    return content;
}

From source file:com.google.android.work.emmnotifications.RetryHttpInitializerWrapper.java

public void initialize(HttpRequest request) {
    final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler(
            new ExponentialBackOff()).setSleeper(sleeper);
    request.setInterceptor(wrappedCredential);

    request.setConnectTimeout(3 * 60000); // 3 minutes connect timeout
    request.setReadTimeout(3 * 60000); // 3 minutes read timeout

    request.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {
        public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
                throws IOException {

            LOG.info("RetryHandler: " + CharStreams.toString(new InputStreamReader(response.getContent())));

            if (wrappedCredential.handleResponse(request, response, supportsRetry)) {
                // If credential decides it can handle it,
                // the return code or message indicated
                // something specific to authentication,
                // and no backoff is desired.

                LOG.info("Requested: " + request.getUrl().toString());
                return true;
            } else if (backoffHandler.handleResponse(request, response, supportsRetry)) {

                // Otherwise, we defer to the judgement of
                // our internal backoff handler.
                LOG.info("Retrying " + request.getUrl());
                return true;
            } else {
                return false;
            }// w  ww .  j  av a 2s .  c  o  m
        }
    });
    request.setIOExceptionHandler(
            new HttpBackOffIOExceptionHandler(new ExponentialBackOff()).setSleeper(sleeper));
}

From source file:com.microsoft.azure.management.appservice.implementation.DeploymentSlotImpl.java

@Override
public PublishingProfile getPublishingProfile() {
    InputStream stream = manager().inner().webApps()
            .listPublishingProfileXmlWithSecretsSlot(resourceGroupName(), this.parent().name(), name());
    try {/*w  w  w  . j av a2 s  . c om*/
        String xml = CharStreams.toString(new InputStreamReader(stream));
        return new PublishingProfileImpl(xml, this);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.metamx.druid.indexer.HadoopDruidIndexerNode.java

@LifecycleStart
public void start() throws Exception {
    Preconditions.checkNotNull(argumentSpec, "argumentSpec");

    final HadoopDruidIndexerConfig config;
    if (argumentSpec.startsWith("{")) {
        config = HadoopDruidIndexerConfig.fromString(argumentSpec);
    } else if (argumentSpec.startsWith("s3://")) {
        final Path s3nPath = new Path(String.format("s3n://%s", argumentSpec.substring("s3://".length())));
        final FileSystem fs = s3nPath.getFileSystem(new Configuration());

        String configString = CharStreams.toString(new InputSupplier<InputStreamReader>() {
            @Override//from ww w.jav a2  s. c o m
            public InputStreamReader getInput() throws IOException {
                return new InputStreamReader(fs.open(s3nPath));
            }
        });

        config = HadoopDruidIndexerConfig.fromString(configString);
    } else {
        config = HadoopDruidIndexerConfig.fromFile(new File(argumentSpec));
    }

    if (intervalSpec != null) {
        final List<Interval> dataInterval = Lists.transform(Arrays.asList(intervalSpec.split(",")),
                new StringIntervalFunction());

        config.setIntervals(dataInterval);
    }

    new HadoopDruidIndexerJob(config).run();
}

From source file:com.proofpoint.discovery.client.announce.HttpDiscoveryAnnouncementClient.java

private static String getBodyForError(Response response) {
    try {/* w ww .  j  a  v a2 s.c  om*/
        return CharStreams.toString(new InputStreamReader(response.getInputStream(), Charsets.UTF_8));
    } catch (IOException e) {
        return "(error getting body)";
    }
}

From source file:com.sixt.service.framework.jetty.JsonHandler.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    logger.debug("Handling json request");

    GoTimer methodTimer = null;// w w w.  java  2s.  c  o  m
    String methodName = null;
    Span span = null;
    long startTime = System.nanoTime();
    Map<String, String> headers = gatherHttpHeaders(req);
    OrangeContext context = new OrangeContext(headers);
    try {

        MDC.put(CORRELATION_ID, context.getCorrelationId());

        String postedContent = CharStreams.toString(req.getReader());
        logger.debug("Request JSON: {}", postedContent);

        JsonRpcRequest rpcRequest;

        try {
            rpcRequest = parseRpcRequest(postedContent);
        } catch (IllegalArgumentException iaex) {
            logger.warn("Error parsing request: " + postedContent, iaex);
            @SuppressWarnings("ThrowableNotThrown")
            RpcCallException callException = new RpcCallException(RpcCallException.Category.BadRequest,
                    iaex.getMessage());
            JsonObject jsonResponse = new JsonObject();
            jsonResponse.add(ERROR_FIELD, callException.toJson());
            writeResponse(resp, HttpServletResponse.SC_BAD_REQUEST, jsonResponse.toString());
            incrementFailureCounter("unknown", context.getRpcOriginService(), context.getRpcOriginMethod());
            return;
        }

        methodName = rpcRequest.getMethod();

        span = getSpan(methodName, headers, context);

        methodTimer = getMethodTimer(methodName, context.getRpcOriginService(), context.getRpcOriginMethod());
        startTime = methodTimer.start();
        context.setCorrelationId(rpcRequest.getIdAsString());
        JsonRpcResponse finalResponse = dispatchJsonRpcRequest(rpcRequest, context);

        resp.setContentType(TYPE_JSON);
        writeResponse(resp, finalResponse.getStatusCode(), finalResponse.toJson().toString());

        //TODO: should we check the response for errors (for metrics)?
        methodTimer.recordSuccess(startTime);
        incrementSuccessCounter(methodName, context.getRpcOriginService(), context.getRpcOriginMethod());
    } catch (IOException e) {
        if (span != null) {
            Tags.ERROR.set(span, true);
        }
        //TODO: this case doesn't return a response.  should it?
        methodTimer.recordFailure(startTime);
        logger.error("Error handling request", e);
        incrementFailureCounter(methodName, context.getRpcOriginService(), context.getRpcOriginMethod());
    } finally {
        if (span != null) {
            span.finish();
        }
        MDC.remove(CORRELATION_ID);
    }
}