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.ritesh.idea.plugin.util.HttpRequestBuilder.java

public <T> T asJson(Class<T> clazz) throws IOException, URISyntaxException {
    try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .build()) {/*ww w.  j ava2  s.  c  o  m*/
        HttpRequestBase request = getHttpRequest();
        CloseableHttpResponse response = client.execute(request);
        String content = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
        try {
            if (StringUtils.isEmpty(content))
                throw new Exception("Empty response recieved");
            return new Gson().fromJson(content, clazz);
        } catch (Exception e) {
            throw new UnexpectedResponseException(
                    "Status: " + response.getStatusLine() + ", Response : " + content, e);
        }
    }
}

From source file:com.google.dart.compiler.DeltaAnalyzer.java

private DartParser getParser(Source source) throws IOException {
    Reader r = source.getSourceReader();
    String sourceString = CharStreams.toString(r);
    Closeables.close(r, false);/*from   w ww. j  a va2s  .co  m*/
    return new DartParser(new DartScannerParserContext(source, sourceString, listener), false);
}

From source file:co.freeside.betamax.tape.MemoryTape.java

private String stringify(Request request) {
    try {//ww  w .j  a  va 2s .co  m
        return "method: " + request.getMethod() + ", " + "uri: " + request.getUri() + ", " + "headers: "
                + request.getHeaders() + ", " + "body: " + CharStreams.toString(request.getBodyAsText());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mockey.storage.xml.MockeyXmlFileManager.java

/**
 * /*from w  w  w .  jav a2s  .  co  m*/
 * @param file
 *            - xml configuration file for Mockey
 * @throws IOException
 * @throws SAXException
 * @throws SAXParseException
 */
public String getFileContentAsString(InputStream fstream) throws IOException, SAXParseException, SAXException {

    String inputStreamString = CharStreams.toString(new InputStreamReader(fstream, "UTF-8"));
    return inputStreamString;

}

From source file:org.assertj.assertions.generator.Template.java

private String readContentThenClose(InputStream input) throws IOException {
    InputStreamReader reader = new InputStreamReader(input);
    try {//from  w ww. j a  v  a2 s  .co m
        return CharStreams.toString(reader);
    } finally {
        closeQuietly(input);
        closeQuietly(reader);
    }
}

From source file:mx.bigdata.jcalais.rest.CalaisRestClient.java

private String post(Map<String, String> formData, CalaisConfig config) throws IOException {
    StringBuilder data = new StringBuilder();
    for (Map.Entry<String, String> me : formData.entrySet()) {
        data.append(URLEncoder.encode(me.getKey(), "UTF-8"));
        data.append("=");
        data.append(URLEncoder.encode(me.getValue(), "UTF-8"));
        data.append("&");
    }/*w  ww  . ja v a  2 s.  c o  m*/
    data.deleteCharAt(data.length() - 1);
    URL url = new URL(RESOURCE);
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(config.get(ConnParam.CONNECT_TIMEOUT));
    conn.setReadTimeout(config.get(ConnParam.READ_TIMEOUT));
    conn.setDoOutput(true);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    try {
        out.write(data.toString());
        out.flush();
    } finally {
        out.close();
    }
    Reader in = new InputStreamReader(conn.getInputStream());
    try {
        return CharStreams.toString(in);
    } finally {
        in.close();
    }
}

From source file:com.google.gerrit.server.mail.receive.RawMailParser.java

/**
 * Traverses a mime tree and parses out text and html parts. All other parts will be dropped.
 *
 * @param part MimePart to parse/*from w ww.ja  va  2s . c  o  m*/
 * @param textBuilder StringBuilder to append all plaintext parts
 * @param htmlBuilder StringBuilder to append all html parts
 * @throws IOException
 */
private static void handleMimePart(Entity part, StringBuilder textBuilder, StringBuilder htmlBuilder)
        throws IOException {
    if (isPlainOrHtml(part.getMimeType()) && !isAttachment(part.getDispositionType())) {
        TextBody tb = (TextBody) part.getBody();
        String result = CharStreams.toString(new InputStreamReader(tb.getInputStream(), tb.getMimeCharset()));
        if (part.getMimeType().equals("text/plain")) {
            textBuilder.append(result);
        } else if (part.getMimeType().equals("text/html")) {
            htmlBuilder.append(result);
        }
    } else if (isMixedOrAlternative(part.getMimeType())) {
        Multipart multipart = (Multipart) part.getBody();
        for (Entity e : multipart.getBodyParts()) {
            handleMimePart(e, textBuilder, htmlBuilder);
        }
    }
}

From source file:contestWebsite.AdminPanel.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets");
    ve.init();//from   ww  w. j a  v  a  2s  . co m
    VelocityContext context = new VelocityContext();
    Pair<Entity, UserCookie> infoAndCookie = init(context, req);

    UserCookie userCookie = infoAndCookie.y;
    boolean loggedIn = (boolean) context.get("loggedIn");

    String updated = req.getParameter("updated");
    if (updated != null && updated.equals("1") && !loggedIn) {
        resp.sendRedirect("/adminPanel?updated=1");
    }
    context.put("updated", req.getParameter("updated"));

    if (loggedIn && userCookie.isAdmin()) {
        Entity contestInfo = infoAndCookie.x;
        context.put("contestInfo", contestInfo);

        String confPassError = req.getParameter("confPassError");
        context.put("confPassError",
                confPassError != null && confPassError.equals("1") ? "Those passwords didn't match, try again."
                        : null);
        String passError = req.getParameter("passError");
        context.put("passError",
                passError != null && passError.equals("1") ? "That password is incorrect, try again." : null);

        context.put("middleSubjects", Test.getTests(Level.MIDDLE));
        context.put("Level", Level.class);
        context.put("subjects", Subject.values());

        String[] defaultEmails = { "forgotPass", "question", "registration" };
        for (String defaultEmail : defaultEmails) {
            String email;
            if (contestInfo.hasProperty(defaultEmail + "Email")) {
                email = ((Text) contestInfo.getProperty(defaultEmail + "Email")).getValue();
            } else {
                InputStream emailStream = getServletContext()
                        .getResourceAsStream("/html/email/" + defaultEmail + ".html");
                email = CharStreams.toString(new InputStreamReader(emailStream, Charsets.UTF_8));
                emailStream.close();
            }
            context.put(defaultEmail + "Email", email);
        }

        try {
            context.put("awardCriteria", Retrieve.awardCriteria(contestInfo));
            context.put("qualifyingCriteria", Retrieve.qualifyingCriteria(contestInfo));
            context.put("clientId", contestInfo.getProperty("OAuth2ClientId"));
        } catch (Exception e) {
            System.err.println("Surpressing exception while loading admin panel");
            e.printStackTrace();
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+6"));

        try {
            Date endDate = dateFormat.parse((String) contestInfo.getProperty("editEndDate"));
            Date startDate = dateFormat.parse((String) contestInfo.getProperty("editStartDate"));
            if (new Date().after(endDate) || new Date().before(startDate)) {
                context.put("regEditClosed", true);
            }
        } catch (Exception e) {
            context.put("regEditClosed", true);
        }

        try {
            Date endDate = dateFormat.parse((String) contestInfo.getProperty("endDate"));
            Date startDate = dateFormat.parse((String) contestInfo.getProperty("startDate"));
            if (new Date().after(endDate) || new Date().before(startDate)) {
                context.put("regClosed", true);
            }
        } catch (Exception e) {
            context.put("regClosed", true);
        }

        MemcacheService memCache = MemcacheServiceFactory.getMemcacheService();
        memCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(java.util.logging.Level.INFO));
        byte[] tabulationTaskStatusBytes = (byte[]) memCache.get("tabulationTaskStatus");
        if (tabulationTaskStatusBytes != null) {
            String[] tabulationTaskStatus = new String(tabulationTaskStatusBytes).split("_");
            context.put("tabulationTaskStatus", tabulationTaskStatus[0]);
            List<String> tabulationTaskStatusTime = new ArrayList<String>();
            long timeAgo = new Date().getTime() - new Date(Long.parseLong(tabulationTaskStatus[1])).getTime();
            List<Pair<TimeUnit, String>> timeUnits = new ArrayList<Pair<TimeUnit, String>>() {
                {
                    add(new Pair<TimeUnit, String>(TimeUnit.DAYS, "day"));
                    add(new Pair<TimeUnit, String>(TimeUnit.HOURS, "hour"));
                    add(new Pair<TimeUnit, String>(TimeUnit.MINUTES, "minute"));
                    add(new Pair<TimeUnit, String>(TimeUnit.SECONDS, "second"));
                }
            };
            for (Pair<TimeUnit, String> entry : timeUnits) {
                if (entry.getX().convert(timeAgo, TimeUnit.MILLISECONDS) > 0) {
                    long numUnit = entry.getX().convert(timeAgo, TimeUnit.MILLISECONDS);
                    tabulationTaskStatusTime.add(numUnit + " " + entry.getY() + (numUnit == 1 ? "" : "s"));
                    timeAgo -= TimeUnit.MILLISECONDS.convert(numUnit, entry.getX());
                }
            }
            if (tabulationTaskStatusTime.size() >= 1) {
                context.put("tabulationTaskStatusTime", StringUtils.join(tabulationTaskStatusTime, ", "));
            } else {
                context.put("tabulationTaskStatusTime", timeAgo + " milliseconds");
            }
        }

        close(context, ve.getTemplate("adminPanel.html"), resp);
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Contest Administrator privileges required for that operation");
    }
}

From source file:org.jfrog.teamcity.server.project.maven.MavenReleaseManagementTab.java

private Build locateLatestBuildInfo(SBuildType buildType) throws Exception {
    List<SFinishedBuild> finishedBuilds = buildType.getHistory();
    for (SFinishedBuild finishedBuild : finishedBuilds) {
        SBuildType finishedBuildType = finishedBuild.getBuildType();
        if (finishedBuildType != null) {
            File artifactsDirectory = new File(finishedBuildType.getArtifactsDirectory(),
                    finishedBuild.getBuildId() + "");
            File buildInfo = new File(artifactsDirectory, ".teamcity/" + BUILD_INFO_FILE_NAME_PACKED);
            if (buildInfo.exists()) {
                String buildInfoString = CharStreams
                        .toString(new InputStreamReader(new GZIPInputStream(new FileInputStream(buildInfo))));
                return BuildInfoExtractorUtils.jsonStringToBuildInfo(buildInfoString);
            }//  ww  w .j  a  va2  s  .com
        }
    }
    return null;
}

From source file:com.google.dart.tools.core.internal.model.ExternalCompilationUnitImpl.java

@Override
protected void readBuffer(Buffer buffer, boolean isWorkingCopy) throws DartModelException {
    DartSource source = getDartSource();
    if (source == null) {
        buffer.setContents(CharOperation.NO_CHAR);
        return;/*w  w w.  j  a  va  2s.  co m*/
    }
    try {
        Reader reader = source.getSourceReader();
        try {
            buffer.setContents(CharStreams.toString(reader));
        } finally {
            Closeables.closeQuietly(reader);
        }
    } catch (IOException e) {
        buffer.setContents(CharOperation.NO_CHAR);
        throw new DartModelException(e, 0);
    }
}