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.terasology.rendering.assets.shader.GLSLShaderLoader.java

private String readUrl(URL url) throws IOException {
    try (InputStreamReader reader = new InputStreamReader(url.openStream(), Charsets.UTF_8)) {
        return CharStreams.toString(reader);
    }/*from   w  w  w  .jav a2  s.c  o  m*/
}

From source file:com.google.enterprise.connector.db.InputStreamFactories.java

/** Fully reads an input stream from the value and Base64 encodes it. */
public static final String toString(Value binaryValue) throws IOException, RepositoryDocumentException {
    return CharStreams
            .toString(new InputStreamReader(((BinaryValue) binaryValue).getInputStream(), Charsets.UTF_8));
}

From source file:com.fitbur.core.el.spring.SpringExpressionService.java

private Expression compile(String name, Reader template) {
    Expression expression = null;

    try {/*from  w w w.j  av  a 2 s  . co  m*/
        expression = cache.get(name, () -> {
            return parser.parseExpression(CharStreams.toString(template));
        });
    } catch (ExecutionException e) {
    }

    return expression;

}

From source file:lu.list.itis.dkd.aig.util.TemplateManager.java

/**
 * Method used for storing a template file.
 *
 * @param context//from w ww.j av a  2 s .  c  om
 *        The context of the servlet calling the {@link TemplateManager} used to determine the
 *        path to store the file.
 * @param stream
 *        The inputs stream from which the template to be store is read.
 * @param name
 *        The name of the template to store. The template will be stored as:
 *        [subFolder]/name.xml
 * @param subFolder
 *        The sub-folder from the template directory defined in the properties, to store the
 *        template file in. If you specify a subFolder you need to provide a trailing slash.
 * @throws IOException
 *         If an I/O error occurs while reading from the stream.
 * @throws UnsupportedEncodingException
 *         If the encoding of the stream is not supported.
 */
public static void store(final ServletContext context, final InputStream stream, final String name,
        @Nullable final String subFolder) throws UnsupportedEncodingException, IOException {
    final File template = new File(context.getRealPath("/"), Strings.nullToEmpty(subFolder) + name + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
    if (!template.exists()) {
        template.getParentFile().mkdirs();
        template.createNewFile();
    }

    try (PrintWriter writer = new PrintWriter(
            new OutputStreamWriter(new FileOutputStream(template), "UTF-8"))) { //$NON-NLS-1$
        final String stringFromStream = CharStreams.toString(new InputStreamReader(stream, "UTF-8")); //$NON-NLS-1$
        writer.println(stringFromStream);
    }
}

From source file:org.killbill.billing.jaxrs.CallbackServlet.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final int current = receivedCalls.incrementAndGet();
    if (forceToFail.get()) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.info("CallmebackServlet is forced to fail for testing purposes");
        return;/*from  ww w .j a v a  2  s . c  om*/
    }

    final String body = CharStreams.toString(new InputStreamReader(request.getInputStream(), "UTF-8"));
    response.setStatus(HttpServletResponse.SC_OK);

    final NotificationJson notification = objectMapper.readValue(body, NotificationJson.class);
    log.info("Got notification: {}", notification);
    assertEqualsNicely(
            notification.getEventType() == null ? null : ExtBusEventType.valueOf(notification.getEventType()));
    notifyIfStackEmpty();
}

From source file:brooklyn.util.stream.Streams.java

public static String readFully(Reader is) {
    try {//  w w  w  .ja  v  a  2  s.com
        return CharStreams.toString(is);
    } catch (IOException ioe) {
        throw Exceptions.propagate(ioe);
    }
}

From source file:io.apiman.cli.core.api.command.ApiPolicyAddCommand.java

@Override
public void performAction(CmdLineParser parser) throws CommandException {
    if (!configStdIn && null == configFile) {
        throw new ExitWithCodeException(1, "Policy configuration must be provided", true);
    }/*from ww  w. j  av  a 2 s.  c  o  m*/

    // read configuration from STDIN or file
    String policyConfig;
    try (InputStream is = (configStdIn ? System.in : Files.newInputStream(configFile))) {
        policyConfig = CharStreams.toString(new InputStreamReader(is));

    } catch (IOException e) {
        throw new CommandException(e);
    }

    LOGGER.debug("Adding policy '{}' to API '{}' with configuration: {}", () -> policyName, this::getModelName,
            () -> policyConfig);

    final ApiPolicy apiPolicy = new ApiPolicy(policyName);
    apiPolicy.setDefinitionId(policyName);

    ManagementApiUtil.invokeAndCheckResponse(() -> buildServerApiClient(VersionAgnosticApi.class, serverVersion)
            .addPolicy(orgName, name, version, apiPolicy));
}

From source file:com.google.gerrit.server.mail.MailSoyTofuProvider.java

private void addTemplate(SoyFileSet.Builder builder, String name) throws ProvisionException {
    // Load as a file in the mail templates directory if present.
    Path tmpl = site.mail_dir.resolve(name);
    if (Files.isRegularFile(tmpl)) {
        String content;//from   www  .  j av  a2s  .com
        try (Reader r = Files.newBufferedReader(tmpl, StandardCharsets.UTF_8)) {
            content = CharStreams.toString(r);
        } catch (IOException err) {
            throw new ProvisionException("Failed to read template file " + tmpl.toAbsolutePath().toString(),
                    err);
        }
        builder.add(content, tmpl.toAbsolutePath().toString());
        return;
    }

    // Otherwise load the template as a resource.
    String resourcePath = "com/google/gerrit/server/mail/" + name;
    builder.add(Resources.getResource(resourcePath));
}

From source file:com.fitbur.core.core.el.mvel.MvelTemplateService.java

private CompiledTemplate compile(String name, Reader template) {
    CompiledTemplate comiledTemplate = null;

    try {//from  www .  ja v  a  2  s .  c o m
        comiledTemplate = cache.get(name, () -> {
            return TemplateCompiler.compileTemplate(CharStreams.toString(template));
        });
    } catch (ExecutionException e) {
    }

    return comiledTemplate;
}

From source file:com.vmware.thinapp.workpool.CloneRunnerImpl.java

@Override
public Result run() throws IOException, InterruptedException {
    log.debug("Using clone-vm script from: {}.", CLONE_VM);
    File ini = File.createTempFile("clone-vm", null);
    try {/*w  w  w. j  a va  2s  .  c  o  m*/
        String rawContents = cloneRequest.toIni(CloneRequest.nullScrubber);
        String redactedContents = cloneRequest.toIni(CloneRequest.redactedScrubber);
        log.info("\n" + redactedContents);
        FileCopyUtils.copy(rawContents.getBytes(Charsets.UTF_8), ini);
        log.info("Executing clone-vm request.");

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

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

        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);
        }

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

        cloneRequest.getLogFile().delete();

        String moid = "";

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

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