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:net.myrrix.common.io.IOUtils.java

/**
 * @param url URL whose contents are to be read
 * @return the contents of the URL, interpreted as a UTF-8 encoded string
 * @throws IOException if the URL can't be read or the file can't be written
 *//*ww  w  . j a v a2 s.  co  m*/
public static String readSmallTextFromURL(URL url) throws IOException {
    Reader in = new InputStreamReader(url.openStream(), Charsets.UTF_8);
    try {
        return CharStreams.toString(in);
    } finally {
        in.close();
    }
}

From source file:com.lyndir.lhunath.opal.system.Shell.java

/**
 * Run an application or shell script and read its standard output and standard error into a string.
 *
 * @param charset The character set to decode the process' output with.
 * @param currDir The current directory for the child process.
 * @param cmd     The command to invoke for running the new process.
 *
 * @return The standard output and standard error of the process.
 *///ww  w.jav  a2 s.  co m
@Nullable
public static String execRead(final Charset charset, final File currDir, final String... cmd) {

    try {
        PipedOutputStream output = new PipedOutputStream();
        exec(output, new NullOutputStream(), currDir, cmd);

        return CharStreams.toString(new InputStreamReader(new PipedInputStream(output), charset));
    } catch (final FileNotFoundException e) {
        logger.err(e, "Command to execute was not found!");
    } catch (final IOException e) {
        logger.err(e, "Failed to read from the process!");
    }

    return null;
}

From source file:com.facebook.presto.cli.QueryPreprocessor.java

private static String preprocessQueryInternal(Optional<String> catalog, Optional<String> schema, String query,
        List<String> preprocessorCommand, Duration timeout) throws QueryPreprocessorException {
    // execute the process in a child thread so we can better handle interruption and timeouts
    AtomicReference<Process> processReference = new AtomicReference<>();

    Future<String> task = executeInNewThread("Query preprocessor", () -> {
        String result;/*  w w  w .  java  2  s .c o m*/
        int exitCode;
        Future<String> readStderr;
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(preprocessorCommand);
            processBuilder.environment().put(ENV_PRESTO_CATALOG, catalog.orElse(""));
            processBuilder.environment().put(ENV_PRESTO_SCHEMA, schema.orElse(""));

            Process process = processBuilder.start();
            processReference.set(process);

            Future<?> writeOutput = null;
            try {
                // write query to process standard out
                writeOutput = executeInNewThread("Query preprocessor output", () -> {
                    try (OutputStream outputStream = process.getOutputStream()) {
                        outputStream.write(query.getBytes(UTF_8));
                    }
                    return null;
                });

                // read stderr
                readStderr = executeInNewThread("Query preprocessor read stderr", () -> {
                    StringBuilder builder = new StringBuilder();
                    try (InputStream inputStream = process.getErrorStream()) {
                        CharStreams.copy(new InputStreamReader(inputStream, UTF_8), builder);
                    } catch (IOException | RuntimeException ignored) {
                    }
                    return builder.toString();
                });

                // read response
                try (InputStream inputStream = process.getInputStream()) {
                    result = CharStreams.toString(new InputStreamReader(inputStream, UTF_8));
                }

                // verify output was written successfully
                try {
                    writeOutput.get();
                } catch (ExecutionException e) {
                    throw e.getCause();
                }

                // wait for process to finish
                exitCode = process.waitFor();
            } finally {
                process.destroyForcibly();
                if (writeOutput != null) {
                    writeOutput.cancel(true);
                }
            }
        } catch (QueryPreprocessorException e) {
            throw e;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new QueryPreprocessorException("Interrupted while preprocessing query");
        } catch (Throwable e) {
            throw new QueryPreprocessorException("Error preprocessing query: " + e.getMessage(), e);
        }

        // check we got a valid exit code
        if (exitCode != 0) {
            Optional<String> errorMessage = tryGetFutureValue(readStderr, 100, MILLISECONDS)
                    .flatMap(value -> Optional.ofNullable(emptyToNull(value.trim())));

            throw new QueryPreprocessorException("Query preprocessor exited " + exitCode
                    + errorMessage.map(message1 -> "\n===\n" + message1 + "\n===").orElse(""));
        }
        return result;
    });

    try {
        return task.get(timeout.toMillis(), MILLISECONDS);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new QueryPreprocessorException("Interrupted while preprocessing query");
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        propagateIfPossible(cause, QueryPreprocessorException.class);
        throw new QueryPreprocessorException("Error preprocessing query: " + cause.getMessage(), cause);
    } catch (TimeoutException e) {
        throw new QueryPreprocessorException("Timed out waiting for query preprocessor after " + timeout);
    } finally {
        Process process = processReference.get();
        if (process != null) {
            process.destroyForcibly();
        }
        task.cancel(true);
    }
}

From source file:org.eclipse.jdt.ls.core.internal.handlers.CompletionResolveHandler.java

public CompletionItem resolve(CompletionItem param) {

    @SuppressWarnings("unchecked")
    Map<String, String> data = (Map<String, String>) param.getData();
    // clean resolve data
    param.setData(null);//from  ww w. j a  v  a 2 s.c  om

    if (!data.containsKey(DATA_FIELD_URI) || !data.containsKey(DATA_FIELD_REQUEST_ID)
            || !data.containsKey(DATA_FIELD_PROPOSAL_ID)) {
        return param;
    }
    int proposalId = Integer.parseInt(data.get(DATA_FIELD_PROPOSAL_ID));
    long requestId = Long.parseLong(data.get(DATA_FIELD_REQUEST_ID));
    CompletionResponse completionResponse = CompletionResponses.get(requestId);
    if (completionResponse == null || completionResponse.getProposals().size() <= proposalId) {
        throw new IllegalStateException("Invalid completion proposal");
    }
    String uri = data.get(DATA_FIELD_URI);
    ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri);
    if (unit == null) {
        throw new IllegalStateException(NLS.bind("Unable to match Compilation Unit from {0} ", uri));
    }
    CompletionProposalReplacementProvider proposalProvider = new CompletionProposalReplacementProvider(unit,
            completionResponse.getContext(), completionResponse.getOffset());
    proposalProvider.updateReplacement(completionResponse.getProposals().get(proposalId), param, '\0');

    if (data.containsKey(DATA_FIELD_DECLARATION_SIGNATURE)) {
        String typeName = stripSignatureToFQN(String.valueOf(data.get(DATA_FIELD_DECLARATION_SIGNATURE)));
        try {
            IMember member = null;
            IType type = unit.getJavaProject().findType(typeName);

            if (type != null && data.containsKey(DATA_FIELD_NAME)) {
                String name = data.get(DATA_FIELD_NAME);
                String[] paramSigs = CharOperation.NO_STRINGS;
                if (data.containsKey(DATA_FIELD_SIGNATURE)) {
                    String[] parameters = Signature.getParameterTypes(
                            String.valueOf(fix83600(data.get(DATA_FIELD_SIGNATURE).toCharArray())));
                    for (int i = 0; i < parameters.length; i++) {
                        parameters[i] = getLowerBound(parameters[i]);
                    }
                    paramSigs = parameters;
                }
                IMethod method = type.getMethod(name, paramSigs);
                if (method.exists()) {
                    member = method;
                } else {
                    IField field = type.getField(name);
                    if (field.exists()) {
                        member = field;
                    }
                }
            } else {
                member = type;
            }

            if (member != null && member.exists()) {
                Reader reader = JavadocContentAccess.getHTMLContentReader(member, true, true);
                if (reader != null) {
                    try {
                        param.setDocumentation(CharStreams.toString(reader));
                    } catch (IOException e) {
                        JavaLanguageServerPlugin.logException("Unable to read documentation", e);
                    }
                }
            }
        } catch (JavaModelException e) {
            JavaLanguageServerPlugin.logException("Unable to resolve compilation", e);
        }
    }
    return param;
}

From source file:org.jclouds.snia.cdmi.v1.options.CreateDataObjectOptions.java

/**
 * Create CDMI data object with InputStream value
 * /*from  w ww .  j  a v  a 2s.  c  o  m*/
 * @param value
 *           InputSteam
 * @param charset
 *           character set of input stream InputSteam is converted to a String value with charset
 *           UTF_8
 * @return CreateDataObjectOptions
 */
public CreateDataObjectOptions value(InputStream value, Charset charset) throws IOException {
    jsonObjectBody.addProperty("value",
            (value == null) ? "" : CharStreams.toString(new InputStreamReader(value, charset)));
    this.payload = jsonObjectBody.toString();
    return this;
}

From source file:com.google.dart.tools.core.generator.AbstractSample.java

private String getResourceAsString(String resourceName) throws IOException {
    InputStream in = getClass().getResourceAsStream(resourceName);

    if (in == null) {
        return "";
    } else {/*from ww w .  ja va  2 s  .  com*/
        Reader reader = new InputStreamReader(in, Charsets.UTF_8);

        return CharStreams.toString(reader);
    }
}

From source file:com.github.cassandra.jdbc.BaseCassandraPreparedStatement.java

public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
    // FIXME Slow and will run into OOM issue
    try {//from  w ww .jav  a  2s  . c o  m
        setString(parameterIndex, CharStreams.toString(reader));
    } catch (IOException e) {
        throw new SQLException(e);
    }
}

From source file:com.github.dirkraft.jash.AbstractBundler.java

static String readClasspathResource(String classpathRes) {
    try {// ww  w .  ja  v  a2 s . c o m
        return CharStreams.toString(
                new InputStreamReader(Resources.getResource(classpathRes).openStream(), Charsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mycelium.wallet.bitid.BitIdAsyncTask.java

@Override
protected BitIDResponse doInBackground(Void... params) {
    final BitIDResponse response = new BitIDResponse();
    try {//ww  w.j av a 2  s  . co  m

        SignedMessage signature = privateKey.signMessage(request.getFullUri(), new AndroidRandomSource());

        final HttpURLConnection conn = (HttpURLConnection) new URL(request.getCallbackUri()).openConnection();
        //todo evaluate enforceSslCorrectness to disable verification stuff if false (and remove setting it to true)
        enforceSslCorrectness = true;
        conn.setReadTimeout(MyceliumWalletApi.SHORT_TIMEOUT_MS);
        conn.setConnectTimeout(MyceliumWalletApi.SHORT_TIMEOUT_MS);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(request.getCallbackJson(address, signature).toString());
        writer.flush();
        writer.close();
        os.close();

        conn.connect();
        try {
            response.code = conn.getResponseCode();
        } catch (IOException ioe) {
            //yes, this seems weird, but there might be a IOException in case of a 401 response, and afterwards the object is in a stable state again
            response.code = conn.getResponseCode();
        }
        response.message = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                if (response.code >= 200 && response.code < 300) {
                    return conn.getInputStream();
                }
                return conn.getErrorStream();
            }
        }, Charsets.UTF_8));

        if (response.code >= 200 && response.code < 300) {
            response.status = BitIDResponse.ResponseStatus.SUCCESS;
        } else {
            response.status = BitIDResponse.ResponseStatus.ERROR;
        }

    } catch (SocketTimeoutException e) {
        //connection timed out
        response.status = BitIDResponse.ResponseStatus.TIMEOUT;
    } catch (UnknownHostException e) {
        //host not known, most probably the device has no internet connection
        response.status = BitIDResponse.ResponseStatus.NOCONNECTION;
    } catch (SSLException e) {
        Preconditions.checkState(enforceSslCorrectness);
        //ask user whether he wants to proceed although there is a problem with the certificate
        response.message = e.getLocalizedMessage();
        response.status = BitIDResponse.ResponseStatus.SSLPROBLEM;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return response;
}

From source file:org.eclipse.scada.da.server.exporter.rest.VariantProvider.java

private Variant variantFromString(final InputStream entityStream, String charsetName) throws IOException {
    if (charsetName == null) {
        charsetName = "UTF-8";
    }//w ww .j a v  a 2 s  . c  o m
    final InputStreamReader reader = new InputStreamReader(entityStream, Charset.forName(charsetName));

    final String data = CharStreams.toString(reader);

    final VariantEditor ve = new VariantEditor();
    ve.setAsText(data);
    return (Variant) ve.getValue();
}