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.caliper.runner.target.Shell.java

private Future<String> inputStreamToString(final InputStream in) {
    return executor.submit(new Callable<String>() {
        @Override// www  .  ja  v a2s.  com
        public String call() throws IOException {
            // TODO(cgdecker): Figure out how to use the right charset for this.
            // In the case of adb, the stdout/stderr in question here are from the adb process
            // running on this (the runner) device. But of course there could be output from adb
            // shell, which is output from shell commands run on the Android device. I don't know
            // how adb deals with any discrepancy there in the first place. Beyond that, the default
            // charset of the JVM we're running on could have been set to something different than
            // than the default charset the adb command is using. I don't know how we can get a
            // "correct" charset for either situation.
            return CharStreams.toString(new InputStreamReader(in, Charset.defaultCharset()));
        }
    });
}

From source file:com.github.autermann.wps.streaming.delegate.WPSClient.java

private String executeRemote(String request) throws IOException {
    HttpPost httpRequest = new HttpPost(this.uri);
    log.debug("Request: {}", request);
    httpRequest.setEntity(EntityBuilder.create().setContentType(CONTENT_TYPE).setText(request).build());
    try (CloseableHttpResponse httpResponse = client.execute(httpRequest);
            InputStream entity = httpResponse.getEntity().getContent();
            InputStreamReader reader = new InputStreamReader(entity, Charsets.UTF_8)) {
        String response = CharStreams.toString(reader);
        log.debug("Response: {}", response);
        return response;
    }//from  w  w  w  . jav a  2s.c  om
}

From source file:com.notifier.desktop.os.impl.OperatingSystemProcessManagerImpl.java

@Override
public void executeCommand(Notification notification, String deviceName, String command, boolean privateMode) {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.redirectErrorStream(true);
    processBuilder.directory(new File(System.getProperty("user.dir")));

    boolean notifiedError = false;
    Iterable<String> commands = COMMAND_SPLITTER.split(command);
    for (String c : commands) {
        c = c.replace(DEVICE_ID_PLACEHOLDER, notification.getDeviceId());
        c = c.replace(NOTIFICATION_ID_PLACEHOLDER, Long.toString(notification.getNotificationId()));
        c = c.replace(NOTIFICATION_TYPE_PLACEHOLDER, notification.getType().name());
        c = c.replace(NOTIFICATION_DATA_PLACEHOLDER, "\"" + notification.getData() + "\"");
        c = c.replace(NOTIFICATION_DESCRIPTION_PLACEHOLDER,
                "\"" + notification.getDescription(privateMode) + "\"");
        c = c.replace(NOTIFICATION_TITLE_PLACEHOLDER, "\"" + notification.getTitle(deviceName) + "\"");

        final String commandToExecute = c;
        if (OperatingSystems.CURRENT_FAMILY == OperatingSystems.Family.WINDOWS) {
            processBuilder.command("cmd.exe", "/X", "/C",
                    "\"" + commandToExecute.replaceAll("\"", "\\\"") + "\"");
        } else {//  w w  w .j ava2 s  .  c o  m
            processBuilder.command("sh", "-c", commandToExecute);
        }
        try {
            final Process process = processBuilder.start();
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String output = CharStreams.toString(new InputSupplier<BufferedReader>() {
                            @Override
                            public BufferedReader getInput() throws IOException {
                                return new BufferedReader(new InputStreamReader(process.getInputStream()));
                            }
                        });
                        logger.info("Output of command execution: {}\n{}", commandToExecute, output);
                    } catch (Exception e) {
                        logger.error("Could not get command output: " + commandToExecute, e);
                    }

                    try {
                        int exitCode = process.waitFor();
                        logger.info("Command [{}] exited with code [{}]", commandToExecute, exitCode);
                    } catch (InterruptedException e) {
                        // Will exit
                    }
                }
            });
        } catch (Exception e) {
            logger.error("Error executing notification command: " + c, e);
            if (!notifiedError) {
                notifiedError = true;
                application.showError(Application.NAME + " Error Executing Command",
                        "An error occurred while executing command.\n" + c);
            }
        }
    }
}

From source file:org.apache.gobblin.data.management.copy.replication.ReplicaHadoopFsEndPoint.java

@Override
public synchronized Optional<ComparableWatermark> getWatermark() {
    if (this.watermarkInitialized) {
        return this.cachedWatermark;
    }//from   w  w w  . j a  v a  2  s.c  om

    this.watermarkInitialized = true;
    try {
        Path metaData = new Path(rc.getPath(), WATERMARK_FILE);
        FileSystem fs = FileSystem.get(rc.getFsURI(), new Configuration());
        if (fs.exists(metaData)) {
            try (FSDataInputStream fin = fs.open(metaData)) {
                InputStreamReader reader = new InputStreamReader(fin, Charsets.UTF_8);
                String content = CharStreams.toString(reader);
                Watermark w = WatermarkMetadataUtil.deserialize(content);
                if (w instanceof ComparableWatermark) {
                    this.cachedWatermark = Optional.of((ComparableWatermark) w);
                }
            }
            return this.cachedWatermark;
        }

        // for replica, can not use the file time stamp as that is different with original source time stamp
        return this.cachedWatermark;
    } catch (IOException e) {
        log.warn("Can not find " + WATERMARK_FILE + " for replica " + this);
        return this.cachedWatermark;
    } catch (WatermarkMetadataUtil.WatermarkMetadataMulFormatException e) {
        log.warn("Can not create watermark from " + WATERMARK_FILE + " for replica " + this);
        return this.cachedWatermark;
    }
}

From source file:com.db.comserv.main.utilities.servlet.ServletUtil.java

public static String buildBody(final HttpServletRequest request) throws IOException {
    return CharStreams.toString(request.getReader());
}

From source file:io.macgyver.core.Bootstrap.java

public static String getBannerText() {
    // Spring boot doesn't support alternate banner until 1.1.x
    String bannerText = "\n";
    try {/*from   w  w w . j av a2 s.  c om*/
        URL url = ServerMain.class.getResource("/banner_alt.txt");
        if (url != null) {
            try (InputStreamReader reader = new InputStreamReader(url.openStream(), Charsets.UTF_8)) {
                String text = CharStreams.toString(reader);

                bannerText += text;
            }
        }

        url = null;
        url = ServerMain.class.getResource("/macgyver-core-revision.properties");
        if (url != null) {
            Properties p = new Properties();
            try (InputStream x = url.openStream()) {
                p.load(x);
            }

            bannerText += String.format("\n\n                      (v%s rev:%s)\n", p.getProperty("version"),
                    p.getProperty("gitShortCommitId"));
        }

    } catch (Exception e) {
        logger.warn("could not load banner");
    }
    return bannerText;
}

From source file:com.palantir.gerrit.gerritci.servlets.ConfigServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    if (currentUser.get().getCapabilities().canAdministrateServer() == false) {
        res.setStatus(403);//w  w  w  . ja  v  a2s  . co  m
        return;
    }

    /*
     * The actual parameters we send are encoded into a JSON object such
     * that they are contained in an object under the entry "f". The other
     * top-level keys seem to be useless. In addition, each key in the
     * parameters object has ":" prefixed to whatever it is the key is
     * actually named. Thus, by stripping the first character away from each
     * key, we arrive at a sane JSONObject of request parameters. Example:
     * {"b": [], "f": {":projectName": "name", ":verifyBranchRegex": *
     * ".*"}}
     */
    JsonObject requestBody = (JsonObject) (new JsonParser()).parse(CharStreams.toString(req.getReader()));
    requestBody = requestBody.get("f").getAsJsonObject();
    File confFile = new File(sitePaths.etc_dir, "gerrit-ci.config");
    FileBasedConfig cfg = new FileBasedConfig(confFile, FS.DETECTED);
    try {
        cfg.load();
    } catch (ConfigInvalidException e) {
        logger.error("Received PUT request. Error loading gerrit-ci.config file:", e);
    }
    cfg.clear();

    for (Entry<String, JsonElement> entry : requestBody.entrySet()) {
        // substring(1) removes the ':' character that precedes each key in the requestBody
        cfg.setString("Settings", "Jenkins", entry.getKey().substring(1), entry.getValue().getAsString());
    }
    cfg.save();
    // the gerrit-ci.config file starts off with permissions -rw-rw-r--
    cfg.getFile().setReadOnly();
    // make unwritable by making file read only for everyone -r--r--r--
    cfg.getFile().setReadable(false, false);
    // Make the file unreadable (readable=false and ownerOnly=false)
    cfg.getFile().setReadable(true, true);
    // Sets the file as readable for only the owner (readable=true and ownerOnly=true) -r--------
    res.setStatus(200);
    res.setContentType("text/plain");
}

From source file:org.codice.ddf.registry.transformer.RegistryTransformer.java

@Override
public Metacard transform(InputStream inputStream, String id) throws IOException, CatalogTransformerException {

    MetacardImpl metacard;/*  w ww.  j a  v a 2 s.  c  o m*/

    try (TemporaryFileBackedOutputStream fileBackedOutputStream = new TemporaryFileBackedOutputStream()) {

        try {
            IOUtils.copy(inputStream, fileBackedOutputStream);

        } catch (IOException e) {
            throw new CatalogTransformerException(
                    "Unable to transform from CSW RIM Service Record to Metacard. Error reading input stream.",
                    e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }

        try (InputStream inputStreamCopy = fileBackedOutputStream.asByteSource().openStream()) {
            metacard = (MetacardImpl) unmarshal(inputStreamCopy);
        } catch (ParserException e) {
            throw new CatalogTransformerException(
                    "Unable to transform from CSW RIM Service Record to Metacard. Parser exception caught", e);
        } catch (RegistryConversionException e) {
            throw new CatalogTransformerException(
                    "Unable to transform from CSW RIM Service Record to Metacard. Conversion exception caught",
                    e);
        }

        if (metacard == null) {
            throw new CatalogTransformerException(
                    "Unable to transform from CSW RIM Service Record to Metacard.");
        } else if (StringUtils.isNotEmpty(id)) {
            metacard.setAttribute(Metacard.ID, id);
        }

        String xml;
        try (Reader reader = fileBackedOutputStream.asByteSource().asCharSource(Charsets.UTF_8).openStream()) {
            xml = CharStreams.toString(reader);
        }

        metacard.setAttribute(Metacard.METADATA, xml);
        metacard.setTags(Collections.singleton(RegistryConstants.REGISTRY_TAG));

    } catch (IOException e) {
        throw new CatalogTransformerException(
                "Unable to transform from CSW RIM Service Record to Metacard. Error using file-backed stream.",
                e);
    }

    return metacard;
}

From source file:org.opendaylight.netconf.mdsal.connector.MdsalNetconfOperationServiceFactory.java

private static Optional<YangModuleCapability> moduleToCapability(final Module module,
        final SchemaSourceProvider<YangTextSchemaSource> rootSchemaSourceProviderDependency) {

    final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
            (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.<String>absent()
                    : Optional.of(SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()))));

    InputStream sourceStream = null;
    String source;//from  ww  w  .j  a v  a2s. co m
    try {
        sourceStream = rootSchemaSourceProviderDependency.getSource(moduleSourceIdentifier).checkedGet()
                .openStream();
        source = CharStreams.toString(new InputStreamReader(sourceStream, Charsets.UTF_8));
    } catch (IOException | SchemaSourceException e) {
        LOG.warn("Ignoring source for module {}. Unable to read content", moduleSourceIdentifier, e);
        source = null;
    }

    try {
        if (sourceStream != null) {
            sourceStream.close();
        }
    } catch (IOException e) {
        LOG.warn("Error closing yang source stream {}. Ignoring", moduleSourceIdentifier, e);
    }

    if (source != null) {
        return Optional.of(new YangModuleCapability(module, source));
    } else {
        LOG.warn("Missing source for module {}. This module will not be available from netconf server",
                moduleSourceIdentifier);
    }
    return Optional.absent();
}

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

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

        String payload = "payload=" + object.toString();
        try {//w w w . j ava2  s.c om
            HttpURLConnection connection = (HttpURLConnection) new URL(slackHookUrl).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(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!");
        }
    });
}