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.google.dart.tools.debug.core.util.ResourceServer.java

protected String getAvailableAppsContent() throws IOException {
    InputStream in = ResourceServer.class.getResourceAsStream("template.html");

    String template = CharStreams.toString(new InputStreamReader(in));

    List<HTMLFile> appFiles = getAllHtmlFiles();

    // Sort by project name, then html file name
    Collections.sort(appFiles, new Comparator<HTMLFile>() {
        @Override// w w w.  java 2  s .  c  o m
        public int compare(HTMLFile o1, HTMLFile o2) {
            String str1 = o1.getDartProject().getElementName() + " " + o1.getElementName();
            String str2 = o2.getDartProject().getElementName() + " " + o2.getElementName();

            return str1.compareToIgnoreCase(str2);
        }
    });

    if (appFiles.size() == 0) {
        template = replaceTemplate(template, "count", "No");
        template = replaceTemplate(template, "apps", "");
    } else {
        template = replaceTemplate(template, "count", Integer.toString(appFiles.size()));

        StringBuilder builder = new StringBuilder();

        for (HTMLFile htmlFile : appFiles) {
            try {
                if (htmlFile.getReferencedLibraries().length < 1) {
                    continue;
                }

                IResource htmlResource = htmlFile.getCorrespondingResource();
                DartLibrary library = htmlFile.getReferencedLibraries()[0];
                IResource libraryResource = library.getCorrespondingResource();

                String href = "<a href=\"" + getPathFor(htmlFile) + "\">";

                builder.append("<div class=\"app\"><table><tr>");
                builder.append(
                        "<td rowspan=2>" + href + "<img src=\"dart_32_32.gif\" width=32 height=32></a></td>");
                builder.append("<td class=\"title\">" + htmlResource.getProject().getName() + " - " + href
                        + htmlFile.getElementName() + "</a></td</tr>");
                builder.append("<tr><td class=\"info\">" + webSafe(libraryResource.getFullPath().toOSString())
                        + "</td></tr>");
                builder.append("</table></div>");
            } catch (DartModelException dme) {

            }
        }

        template = replaceTemplate(template, "apps", builder.toString());
    }

    return template;
}

From source file:com.citytechinc.cq.clientlibs.core.services.clientlibs.cache.impl.DefaultClientLibraryCacheManager.java

@Override
public Optional<String> getCachedLibrary(Resource root, LibraryType type, String brand)
        throws CachedClientLibraryLookupException, LoginException {

    /*//from w  ww .j  a  v  a 2  s.c  o m
     * NOTE: Using the administrative resource resolver here as it was the resolver creating the cached resource
     * In cases where library requests come back to back, the resource resolver from the root may not have been
     * refreshed in time to see the cached library -
     *
     * TODO: use root's ResourceResolver in Sling7 once the refresh method is implemented on ResourceResolver
     */

    Resource cachedResource = getAdministrativeResourceResolver()
            .getResource(getPathToLibraryFile(root.getPath(), type, brand));

    if (cachedResource != null) {

        Node node = cachedResource.adaptTo(Node.class);

        try {

            Property dataProperty = node.getProperty("jcr:content/jcr:data");

            Reader libraryReader = new InputStreamReader(dataProperty.getBinary().getStream(),
                    ClientLibrary.UTF_8_ENCODING);

            String libraryString = CharStreams.toString(libraryReader);

            libraryReader.close();

            return Optional.of(libraryString);

        } catch (RepositoryException e) {
            LOG.error("Repository Exception encountered looking up cached library for "
                    + cachedResource.getPath(), e);
            throw new CachedClientLibraryLookupException(
                    "Repository Exception encountered looking up cached library for "
                            + cachedResource.getPath(),
                    e);
        } catch (IOException e) {
            LOG.error("IO Exception encountered looking up cached library for " + cachedResource.getPath(), e);
            throw new CachedClientLibraryLookupException(
                    "IO Exception encountered looking up cached library for " + cachedResource.getPath(), e);
        }
    }

    return Optional.absent();

}

From source file:pt.ist.fenixedu.quc.ui.struts.action.gep.inquiries.UploadInquiriesResultsDA.java

private String readFile(ResultsFileBean resultsBean) throws IOException {
    return CharStreams.toString(new InputStreamReader(resultsBean.getInputStream()));
}

From source file:xyz.putzi.slackmc.bukkit.messaging.Messenger.java

@Override
public void send() {
    plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> {
        JsonObject object = toJsonObject();
        Objects.requireNonNull(object, "Object must not be null.");

        String payload = "payload=" + object.toString();

        try {//  ww w  .  j a va  2 s .c o  m
            HttpURLConnection connection = (HttpURLConnection) new URL(slackHookUrl).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);

            BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
            outputStream.write(payload.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            outputStream.close();

            int serverResponse = connection.getResponseCode();
            if (serverResponse >= 400 && serverResponse < 600) {
                BufferedInputStream errorStream = new BufferedInputStream(connection.getErrorStream());
                String errorMessage = CharStreams.toString(new InputStreamReader(errorStream, Charsets.UTF_8));
                System.out.println(errorMessage);
                System.out.println(serverResponse);
                errorStream.close();
            }
            connection.disconnect();
        } catch (IOException exception) {
            System.out.println("An error occurred while sending message to slack!");
        }
    });
}

From source file:edu.umb.cs.source.std.Utils.java

static Output compile(List<List<SourceToken>> src, String outer) {
    try {/*from w  w w. j  av a2s.  c  om*/
        int retcode = 0;
        String fn = outer + ".java";

        // write the source to file
        FileWriter fstream = new FileWriter(tempDir.getAbsolutePath() + "/" + fn);
        BufferedWriter outFile = new BufferedWriter(fstream);

        for (List<SourceToken> line : src)
            for (SourceToken tk : line)
                outFile.write(tk.image());
        //Close the output stream
        outFile.close();

        // compile the source
        Process p = Runtime.getRuntime().exec("javac " + fn, null, tempDir);
        try {
            p.waitFor();
            retcode = p.exitValue();
        } catch (InterruptedException ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
            return new Output(ex.getMessage(), true);
        }

        if (retcode != 0) {
            // cannot compile!
            return new Output(CharStreams.toString(new InputStreamReader(p.getErrorStream())), true);
        }

        // execute the source
        p = Runtime.getRuntime().exec("java " + outer, null, tempDir);
        try {
            p.waitFor();
            retcode = p.exitValue();
        } catch (InterruptedException ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
            return new Output(ex.getMessage(), true);
        }

        if (retcode != 0) {
            // something wrong!
            return new Output(CharStreams.toString(new InputStreamReader(p.getErrorStream())), true);
        }

        // otherwise, return the output
        String ret = CharStreams.toString(new InputStreamReader(p.getInputStream()));

        // TODO: clean up the temp files ?
        return new Output(ret, false);
    } catch (IOException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        return new Output(ex.getMessage(), true);
    }
}

From source file:com.theoryinpractise.coffeescript.JoinSet.java

public String getConcatenatedStringOfFiles() throws IOException {
    if (null == concatenatedStringOfFiles) {
        StringBuilder sb = new StringBuilder();

        for (File file : getFiles()) {
            if (!file.exists()) {
                throw new IOException(
                        String.format("JoinSet %s references missing file: %s", getId(), file.getPath()));
            }/* ww  w .  jav  a 2 s  . c o m*/

            InputSupplier<InputStreamReader> readerSupplier = Files.newReaderSupplier(file, Charsets.UTF_8);
            sb.append(CharStreams.toString(readerSupplier));
            sb.append("\n");
        }

        concatenatedStringOfFiles = sb.toString();
    }

    return concatenatedStringOfFiles;
}

From source file:com.facebook.buck.util.BlockingHttpEndpoint.java

@VisibleForTesting
ListenableFuture<HttpResponse> send(final HttpURLConnection connection, final String content) {
    return requestService.submit(new Callable<HttpResponse>() {
        @Override/*from  ww  w.ja  v  a  2 s.c  o  m*/
        public HttpResponse call() {
            try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
                out.writeBytes(content);
                out.flush();
                out.close();
                InputStream inputStream = connection.getInputStream();
                String response = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
                return new HttpResponse(content, response);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:com.cinchapi.concourse.util.ZipFiles.java

/**
 * Extract and return the content of the
 * {@link ZipInputStream#getNextEntry() current entry} from the {@code in}
 * put stream./* w  w  w  .  ja  va2s .com*/
 * 
 * @param in the {@link ZipInputStream} that is correctly positioned at the
 *            desired entry
 * @return content of the current entry
 */
private static String extract(ZipInputStream in) {
    try {
        return CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:de.dentrassi.pm.mail.service.java.DefaultMailService.java

@Override
public void sendMessage(final String to, final String subject, final Readable readable) throws Exception {
    // create message

    final Message message = createMessage(to, subject);

    // set text/*  w w w.j  a  va 2  s. c o  m*/

    message.setText(CharStreams.toString(readable));

    // send message

    sendMessage(message);
}

From source file:fr.norad.visuwall.core.application.common.ApplicationHelper.java

public static void changeLogLvl() {
    try {/*from   www. j av  a 2  s.co  m*/
        InputStream logConfStream = ApplicationHelper.class.getResourceAsStream("/visuwall-logback.xml");
        String logConfString = CharStreams.toString(new InputStreamReader(logConfStream));
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        try {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(lc);
            lc.reset();
            configurator.doConfigure(new ByteArrayInputStream(logConfString.getBytes()));
        } catch (JoranException je) {
            je.printStackTrace();
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
    } catch (IOException e) {
        LOG.error("Can not change application log level", e);
    }

    // don't change root lvl as is may put hibernate or jetty in debug
    //        Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    //        root.setLevel(loglvl);
}