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.openqa.selenium.firefox.Preferences.java

private void readDefaultPreferences(Reader defaultsReader) {
    try {//from www . j  a v  a 2s  . c o  m
        String rawJson = CharStreams.toString(defaultsReader);
        Map<String, Object> map = new JsonToBeanConverter().convert(Map.class, rawJson);

        Map<String, Object> frozen = (Map<String, Object>) map.get("frozen");
        for (Map.Entry<String, Object> entry : frozen.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof Long) {
                value = new Integer(((Long) value).intValue());
            }
            setPreference(key, value);
            immutablePrefs.put(key, value);
        }

        Map<String, Object> mutable = (Map<String, Object>) map.get("mutable");
        for (Map.Entry<String, Object> entry : mutable.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof Long) {
                value = new Integer(((Long) value).intValue());
            }
            setPreference(entry.getKey(), value);
        }
    } catch (IOException e) {
        throw new WebDriverException(e);
    }
}

From source file:org.eclipse.che.api.core.rest.HttpRequestHelper.java

public static String requestString(int timeout, String url, String method, Object body,
        Pair<String, ?>... parameters) throws IOException, ServerException, ForbiddenException,
        NotFoundException, UnauthorizedException, ConflictException {
    final String authToken = EnvironmentContext.getCurrent().getSubject().getToken();
    if ((parameters != null && parameters.length > 0) || authToken != null) {
        final UriBuilder ub = UriBuilder.fromUri(url);
        // remove sensitive information from url.
        ub.replaceQueryParam("token", null);

        if (parameters != null && parameters.length > 0) {
            for (Pair<String, ?> parameter : parameters) {
                ub.queryParam(parameter.first, parameter.second);
            }/*from ww  w.  j  ava2s.c o m*/
        }
        url = ub.build().toString();
    }
    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(timeout > 0 ? timeout : 60000);
    conn.setReadTimeout(timeout > 0 ? timeout : 60000);
    try {
        conn.setRequestMethod(method);
        // drop a hint for server side that we want to receive application/json
        //            conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        if (authToken != null) {
            conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authToken);
        }
        if (body != null) {
            //                conn.addRequestProperty(HttpHeaders.CONTENT_TYPE,
            // MediaType.APPLICATION_JSON);
            conn.setDoOutput(true);

            if (HttpMethod.DELETE.equals(method)) { // to avoid jdk bug described here
                // http://bugs.java.com/view_bug.do?bug_id=7157360
                conn.setRequestMethod(HttpMethod.POST);
                conn.setRequestProperty("X-HTTP-Method-Override", HttpMethod.DELETE);
            }

            try (OutputStream output = conn.getOutputStream()) {
                output.write(DtoFactory.getInstance().toJson(body).getBytes());
            }
        }

        final int responseCode = conn.getResponseCode();
        if ((responseCode / 100) != 2) {
            InputStream in = conn.getErrorStream();
            if (in == null) {
                in = conn.getInputStream();
            }
            final String str;
            try (Reader reader = new InputStreamReader(in)) {
                str = CharStreams.toString(reader);
            }
            final String contentType = conn.getContentType();
            if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON)) {
                final ServiceError serviceError = DtoFactory.getInstance().createDtoFromJson(str,
                        ServiceError.class);
                if (serviceError.getMessage() != null) {
                    if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
                        throw new ForbiddenException(serviceError);
                    } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
                        throw new NotFoundException(serviceError);
                    } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
                        throw new UnauthorizedException(serviceError);
                    } else if (responseCode == Response.Status.CONFLICT.getStatusCode()) {
                        throw new ConflictException(serviceError);
                    } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
                        throw new ServerException(serviceError);
                    }
                    throw new ServerException(serviceError);
                }
            }
            // Can't parse content as json or content has format other we expect for error.
            throw new IOException(String.format("Failed access: %s, method: %s, response code: %d, message: %s",
                    UriBuilder.fromUri(url).replaceQuery("token").build(), method, responseCode, str));
        }

        //            final String contentType = conn.getContentType();

        //            if (!(contentType == null ||
        // contentType.startsWith(MediaType.APPLICATION_JSON))) {
        //                throw new IOException(conn.getResponseMessage());
        //            }

        try (Reader reader = new InputStreamReader(conn.getInputStream())) {
            return CharStreams.toString(reader);
        }
    } finally {
        conn.disconnect();
    }
}

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

/**
 * Gets the reader content as a String//from  ww w. jav a  2  s . com
 *
 * @param reader the reader
 * @return the reader content as string
 */
private static String getString(Reader reader) {
    try {
        return CharStreams.toString(reader);
    } catch (IOException ignored) {
        //meh
    }
    return null;
}

From source file:org.eclipse.packagedrone.repo.adapter.maven.upload.Uploader.java

private String toChecksumString(final InputStream stream) throws IOException {
    if (stream == null) {
        return "";
    }//  w w  w . j  a  v  a2s .c  om
    return CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
}

From source file:eu.operando.core.ose.api.impl.HelperMethods.java

/**
 * Add the OSP policy to PDB module via the OSP API.
 * @param fileLoc The json file with the content
 * @return The ID of the created OSP policy
 *//*from   ww w.  j a v a 2 s  .  com*/
public boolean createOSPReason(String ospId, String fileLoc) {

    InputStream fis = null;
    try {
        fis = HelperMethods.class.getResourceAsStream(fileLoc);
        if (fis == null) {
            throw new FileNotFoundException("File not in classpath: " + fileLoc);
        }
        String content = CharStreams.toString(new InputStreamReader(fis, Charsets.UTF_8));
        Closeables.closeQuietly(fis);

        WebResource webResourcePDB = client.resource(PDB_OSP_URL + "/" + ospId + "/privacy-policy/");
        ClientResponse policyResponse = webResourcePDB.type("application/json").put(ClientResponse.class,
                content);

        System.out.println("POST " + fileLoc + "status code:" + policyResponse.getStatus());

        if (policyResponse.getStatus() != 204) {
            System.err.println("POST " + fileLoc + "error message:" + policyResponse.getEntity(String.class));
            return false;
        }

        return true;
    } catch (IOException e) {
        // Display to console for debugging purposes.
        System.err.println("POST " + fileLoc + "Error creating UPP in pdb - " + e.getLocalizedMessage());
        return false;
    }
}

From source file:com.google.dart.tools.debug.core.webkit.ChromiumConnector.java

private static String readText(HttpUrlConnector connection, InputStream in) throws IOException {
    Reader reader = new InputStreamReader(in, Charsets.UTF_8);

    String data = CharStreams.toString(reader);

    reader.close();/*from ww w  . jav  a  2  s  .  c o  m*/

    return data;
}

From source file:google.registry.whois.WhoisReader.java

/**
 * Read a command from some source to produce a new instance of
 * WhoisCommand.//from w w  w. j a  va  2  s. c  om
 *
 * @throws IOException If the command could not be read from the reader.
 * @throws WhoisException If the command could not be parsed as a WhoisCommand.
 */
WhoisCommand readCommand() throws IOException, WhoisException {
    return parseCommand(CharStreams.toString(reader));
}

From source file:com.palantir.atlasdb.shell.AtlasShellHelp.java

private String read(String path) {
    try {/*from  w ww.ja va2s . c  o m*/
        URL url = this.getClass().getResource(path);
        Charset charSet = Charset.forName("UTF-8");
        Reader reader = Resources.asCharSource(url, charSet).openStream();
        return CharStreams.toString(reader);
    } catch (IOException e) {
        throw Throwables.throwUncheckedException(e);
    }
}

From source file:org.glowroot.agent.dist.PluginJsonTransformer.java

private static @Nullable String getGlowrootPluginJson(Artifact artifact) throws IOException {
    File artifactFile = artifact.getFile();
    if (!artifactFile.exists()) {
        return null;
    }// w  ww  .j  a v a  2  s . c  o m
    if (artifactFile.isDirectory()) {
        File jsonFile = new File(artifactFile, "META-INF/glowroot.plugin.json");
        if (!jsonFile.exists()) {
            return null;
        }
        return Files.toString(jsonFile, UTF_8);
    }
    JarInputStream jarIn = new JarInputStream(new FileInputStream(artifact.getFile()));
    try {
        JarEntry jarEntry;
        while ((jarEntry = jarIn.getNextJarEntry()) != null) {
            String name = jarEntry.getName();
            if (jarEntry.isDirectory()) {
                continue;
            }
            if (!name.equals("META-INF/glowroot.plugin.json")) {
                continue;
            }
            InputStreamReader in = new InputStreamReader(jarIn, UTF_8);
            String content = CharStreams.toString(in);
            in.close();
            return content;
        }
        return null;
    } finally {
        jarIn.close();
    }
}

From source file:com.bigfatgun.fixjures.json.JSONSource.java

private String loadSource() throws IOException {
    return CharStreams.toString(new InputStreamReader(Channels.newInputStream(getSource()), getCharset()));
}