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.vmware.thinapp.workpool.InstallRunnerImpl.java

@Override
public Result run() throws IOException, InterruptedException {
    log.debug("Using create-vm script from: {}.", CREATE_VM);
    File ini = File.createTempFile("create-vm", null);
    try {//  www .ja  v  a  2s.c  o m
        String rawContents = installRequest.toIni(InstallRequest.nullScrubber);
        String redactedContents = installRequest.toIni(InstallRequest.redactedScrubber);
        log.info("\n" + redactedContents);
        FileCopyUtils.copy(rawContents.getBytes(Charsets.UTF_8), ini);
        log.debug("Logging status to {}.", installRequest.getLogFile());
        log.info("Executing create-vm request.");

        // Have to set PYTHON_EGG_CACHE because otherwise Python will try to extract temporary files to
        // /usr/share/tomcat6 which will not work.
        ProcessBuilder pb = new ProcessBuilder(CREATE_VM, ini.getAbsolutePath());
        pb.environment().put("PYTHON_EGG_CACHE", "/tmp/tomcat-egg-cache");
        Process p = pb.start();

        int ret = p.waitFor();
        log.info("create-vm exited with code: {}.", ret);

        // Relog log file.
        for (String line : Files.readLines(installRequest.getLogFile(), Charsets.UTF_8)) {
            log.info(line);
        }

        String stderr = CharStreams.toString(new InputStreamReader(p.getErrorStream(), Charsets.UTF_8)).trim();

        if (StringUtils.hasLength(stderr)) {
            ret = -1; // suppress content (if any) from stdout and enforce the error handling code path
            log.error(stderr);
        }

        installRequest.getLogFile().delete();

        String moid = "";

        if (ret == 0) {
            moid = CharStreams.toString(new InputStreamReader(p.getInputStream(), Charsets.UTF_8)).trim();
            log.debug("Received installed VM with moid {}.", moid);
        }

        return new Result(moid, StringUtils.hasLength(moid), stderr);
    } finally {
        if (!ini.delete()) {
            log.error("Failed to delete file: {}.", ini);
        }
    }
}

From source file:com.replaymod.replaystudio.pathing.serialize.TimelineSerialization.java

public Map<String, Timeline> load() throws IOException {
    Map<String, Timeline> timelines = new LinkedHashMap<>(
            LegacyTimelineConverter.convert(registry, replayFile));

    Optional<InputStream> optionalIn = replayFile.get(FILE_ENTRY);
    if (optionalIn.isPresent()) {
        String serialized;//from   w  ww  .j  a  va 2 s. c o  m
        try (InputStream in = optionalIn.get()) {
            serialized = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8));
        }
        Map<String, Timeline> deserialized = deserialize(serialized);
        timelines.putAll(deserialized);
    }
    return timelines;
}

From source file:com.github.jqudt.onto.UnitFactory.java

/** Load all units dynamically from the ontlogy */
private void loadUnits() throws RepositoryException, MalformedQueryException, QueryEvaluationException,
        IOException, URISyntaxException {

    RepositoryConnection con = repos.getConnection();

    InputStream sparqlStream = this.getClass().getResourceAsStream("findUnits.sparql");
    Preconditions.checkNotNull(sparqlStream, "sparql query not found");
    String sparqlQ = CharStreams.toString(new InputStreamReader(sparqlStream, Charsets.UTF_8));

    TupleQuery tq = con.prepareTupleQuery(QueryLanguage.SPARQL, sparqlQ);
    TupleQueryResult res = tq.evaluate();
    while (res.hasNext()) {
        BindingSet bs = res.next();//w  ww. j a v  a 2 s .  co  m
        Iterator<Binding> bindIt = bs.iterator();
        Unit unit = new Unit();
        Multiplier multiplier = new Multiplier();
        while (bindIt.hasNext()) {
            Binding binding = bindIt.next();
            String name = binding.getName();
            Value val = binding.getValue();
            // System.out.println(name + "\t" + val);

            if (name.equals("s")) {
                unit.setResource(new URI(val.stringValue()));
            } else if (name.equals("label")) {
                unit.setLabel(val.stringValue());
            } else if (name.equals("symbol")) {
                unit.setSymbol(val.stringValue());
            } else if (name.equals("abbrev")) {
                unit.setAbbreviation(val.stringValue());
            } else if (name.equals("convOffset")) {
                multiplier.setOffset(Double.parseDouble(val.stringValue()));
            } else if (name.equals("convMult")) {
                multiplier.setMultiplier(Double.parseDouble(val.stringValue()));
            } else if (name.equals("type")) {
                if (!(val instanceof BNode)) {
                    URIImpl typeURI = new URIImpl(val.stringValue());
                    if (!shouldBeIgnored(typeURI)) {
                        unit.setType(new URI(typeURI.stringValue()));
                    }
                }
            } else {
                throw new MalformedQueryException("found bizare binding: " + binding);
            }
        }
        unit.setMultiplier(multiplier);
        ALL_UNITS.add(unit);
    }
}

From source file:org.terasology.rendering.assetLoaders.GLSLShaderLoader.java

private String readUrl(URL url) throws IOException {
    InputStream stream = url.openStream();
    InputStreamReader reader = new InputStreamReader(stream);
    try {/*ww w . j av  a  2s .c  o  m*/
        return CharStreams.toString(reader);
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            logger.error("Failed to close stream", e);
        }
    }
}

From source file:io.macgyver.core.cli.CLIDownloadController.java

@RequestMapping(path = "/cli/install", produces = "text/plain")
public void installClient(HttpServletRequest request, HttpServletResponse response) throws IOException {
    org.springframework.core.io.Resource resource = applicationContext
            .getResource("classpath:cli/install-cli.sh");

    try (InputStreamReader r = new InputStreamReader(resource.getInputStream())) {
        String script = CharStreams.toString(r);

        String url = request.getRequestURL().toString().toLowerCase();

        url = url.substring(0, url.indexOf("/cli/"));

        script = script.replace("MACGYVER_TEMPLATE_URL", url);

        response.getWriter().println(script);
    }/*from   w w w  .  java  2s. c  o m*/
}

From source file:com.bennavetta.vetinari.parse.PageParser.java

public Page parsePage(Path file, VetinariContext context) throws PageParseException {
    log.info("Parsing content file {}", file);
    Path relativePath = context.getContentRoot().relativize(file);

    try (BufferedReader reader = Files.newBufferedReader(file, context.getContentEncoding())) {
        Config metadata = ConfigFactory.empty();
        StringBuilder contentBuilder = new StringBuilder();

        final String firstLine = reader.readLine();
        if (!Strings.isNullOrEmpty(firstLine)) // only look for metadata if there's actually content
        {//from  w ww  .j  a v  a2 s . c o m
            ConfigSyntax syntax = DELIMITERS.get(firstLine.trim());
            if (syntax != null) // frontmatter present
            {
                log.debug("Detected frontmatter syntax: {}", syntax);

                final String delimiter = firstLine.trim();
                final StringBuilder frontmatterBuilder = new StringBuilder();
                for (String line = reader.readLine(); !delimiter.equals(line); line = reader.readLine()) {
                    if (line == null) {
                        throw new PageParseException(
                                "Reached EOF before end delimiter '" + delimiter + "' in " + file);
                    }

                    frontmatterBuilder.append(line).append('\n');
                }

                metadata = ConfigFactory.parseString(frontmatterBuilder.toString(),
                        ConfigParseOptions.defaults().setOriginDescription(file.toString()).setSyntax(syntax));
                log.trace("Read frontmatter {}", metadata);
            } else {
                contentBuilder.append(firstLine).append('\n');
            }
        }

        contentBuilder.append(CharStreams.toString(reader));
        log.trace("Read page content: \"{}\"", contentBuilder);

        return new Page(metadata, relativePath, contentBuilder.toString());
    } catch (IOException e) {
        throw new PageParseException("Error reading page content for " + file, e);
    }
}

From source file:eu.interedition.collatex.cli.URLWitness.java

public URLWitness read(Function<String, Iterable<String>> tokenizer, Function<String, String> normalizer,
        Charset charset, XPathExpression tokenXPath)
        throws IOException, XPathExpressionException, SAXException {
    InputStream stream = null;/* w w  w  .j  a v a 2 s  . c o m*/
    try {
        stream = url.openStream();
        if (tokenXPath != null) {
            final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            final Document document = documentBuilder.parse(stream);
            document.normalizeDocument();

            final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document, XPathConstants.NODESET);
            final List<Token> tokens = Lists.newArrayListWithExpectedSize(tokenNodes.getLength());
            for (int nc = 0; nc < tokenNodes.getLength(); nc++) {
                final Node tokenNode = tokenNodes.item(nc);
                final String tokenText = tokenNode.getTextContent();
                tokens.add(new NodeToken(this, tokenText, normalizer.apply(tokenText), tokenNode));
            }
            setTokens(tokens);
        } else {
            final List<Token> tokens = Lists.newLinkedList();
            for (String tokenText : tokenizer
                    .apply(CharStreams.toString(new InputStreamReader(stream, charset)))) {
                tokens.add(new SimpleToken(this, tokenText, normalizer.apply(tokenText)));
            }
            setTokens(tokens);
        }
    } catch (ParserConfigurationException e) {
        throw new SAXException(e);
    } finally {
        Closeables.close(stream, false);
    }
    return this;
}

From source file:hihex.cs.Preferences.java

private String readDefaultLogFilter() {
    final InputStream stream = mContext.getResources().openRawResource(R.raw.default_filter_config);
    final Reader reader = new InputStreamReader(stream, Charsets.UTF_8);
    try {//ww w .ja  v  a  2 s .c  o m
        return CharStreams.toString(reader);
    } catch (final IOException e) {
        // Should not happen
        throw new RuntimeException(e);
    } finally {
        Closeables.closeQuietly(reader);
    }
}

From source file:zipkin.storage.cassandra.Schema.java

static void applyCqlFile(String keyspace, Session session, String resource) {
    try (Reader reader = new InputStreamReader(Schema.class.getResourceAsStream(resource))) {
        for (String cmd : CharStreams.toString(reader).split(";")) {
            cmd = cmd.trim().replace(" zipkin", " " + keyspace);
            if (!cmd.isEmpty()) {
                session.execute(cmd);// ww w . j  av  a  2 s  . c  o m
            }
        }
    } catch (IOException ex) {
        LOG.error(ex.getMessage(), ex);
    }
}

From source file:tests.SearchTestsHarness.java

static String call(final String request, final String contentType) {
    try {/*  w ww . j  av a2s  . c  o  m*/
        final URLConnection url = new URL("http://localhost:" + TEST_SERVER_PORT + "/" + request)
                .openConnection();
        url.setRequestProperty("Accept", contentType);
        return CharStreams.toString(new InputStreamReader(url.getInputStream(), Charsets.UTF_8));
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}