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.axelor.common.VersionUtils.java

private static Version getVersion(String file) {
    try (InputStream is = ClassUtils.getResourceStream(file)) {
        String version = CharStreams.toString(new InputStreamReader(is));
        return new Version(version);
    } catch (Exception e) {
        throw new IllegalStateException("Unable to read version details.", e);
    }/*from w  w  w . j a  v  a  2s  .c om*/
}

From source file:foo.domaintest.email.EmailApiModule.java

/**
 * Provides parsed email headers from the "headers" param in a multipart/form-data request.
 * <p>//from w w w. j  av  a2 s.c om
 * Although SendGrid parses some headers for us, it doesn't parse "reply-to", so we need to do
 * this. Once we are doing it, it's easier to be consistent and use this as the sole source of
 * truth for information that originates in the headers.
 */
@Provides
@Singleton
InternetHeaders provideHeaders(FileItemIterator iterator) {
    try {
        while (iterator != null && iterator.hasNext()) {
            FileItemStream item = iterator.next();
            // SendGrid sends us the headers in the "headers" param.
            if (item.getFieldName().equals("headers")) {
                try (InputStream stream = item.openStream()) {
                    // SendGrid always sends headers in UTF-8 encoding.
                    return new InternetHeaders(new ByteArrayInputStream(
                            CharStreams.toString(new InputStreamReader(stream, UTF_8.name())).getBytes(UTF_8)));
                }
            }
        }
    } catch (MessagingException | FileUploadException | IOException e) {
        // If we fail parsing the headers fall through returning the empty header object below.
    }
    return new InternetHeaders(); // Parsing failed or there was no "headers" param.
}

From source file:edu.washington.cs.cupid.usage.internal.DataCollectorDialog.java

@Override
protected Control createDialogArea(final Composite parent) {
    GridLayout layout = new GridLayout();
    layout.numColumns = 1;/*from  w  w  w.  ja  va2s.com*/
    parent.setLayout(layout);

    Label text = new Label(parent, SWT.LEFT | SWT.WRAP);
    text.setText("You can review collected data and disable reporting on the Cupid preferences page.");

    GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
    data.heightHint = 30;
    text.setLayoutData(data);

    Browser consentText = new Browser(parent, SWT.BORDER);

    try {
        Bundle bundle = Activator.getDefault().getBundle();
        URL fileURL = bundle.getEntry(CONSENT_AGREEMENT_PATH);

        if (fileURL == null) {
            throw new RuntimeException("Unable to locate consent agreement at " + CONSENT_AGREEMENT_PATH);
        }

        InputStream inputStream = fileURL.openStream();
        String content = CharStreams.toString(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        consentText.setText(content);
    } catch (Exception ex) {
        Activator.getDefault().logError("Error loading consent form: " + ex.getLocalizedMessage(), ex);
        consentText.setText("Error loading consent form: " + ex.getLocalizedMessage());
    }

    data = new GridData(SWT.FILL, SWT.FILL, true, true);
    data.heightHint = 250;
    data.widthHint = 400;
    consentText.setLayoutData(data);

    return parent;
}

From source file:org.eclipse.wb.internal.core.DesignerPlugin.java

/**
 * Reads the contents of an {@link InputStreamReader} using the default
 * platform encoding and return it as a String. This method will close the
 * input stream.//from w w w  . j a v a  2s. c  o m
 *
 * @param inputStream the input stream to be read from
 * @param charset the charset to use
 * @return the String read from the stream, or null if there was an error
 */
public static String readFile(InputStream inputStream, Charset charset) {
    if (inputStream == null) {
        return null;
    }
    Closeable closeMe = inputStream;
    try {
        final InputStreamReader isr = new InputStreamReader(inputStream, charset);
        closeMe = isr;
        try {
            return CharStreams.toString(isr);
        } catch (Exception ioe) {
            // pass -- ignore files we can't read
            return null;
        }
    } finally {
        Closeables.closeQuietly(closeMe);
    }
}

From source file:com.kurento.kmf.test.services.RemoteHost.java

public String execAndWaitCommand(String... command) throws IOException {
    OverthereProcess process = connection.startProcess(CmdLine.build(command));
    return CharStreams.toString(new InputStreamReader(process.getStdout(), "UTF-8"));
}

From source file:org.apache.marmotta.ucuenca.wk.authors.webservices.AuthorWebService.java

/**
 * Add Endpoint Service//from w w w  .j  ava  2s .  co m
 *
 * @param resultType
 * @param request
 * @return
 */
@POST
@Path(ADD_ENDPOINT)
public Response addEndpointPost(@QueryParam("Endpoint") String resultType,
        @Context HttpServletRequest request) {
    try {
        String params = CharStreams.toString(request.getReader());
        log.debug("Adding Endpoint", params);
        return addEndpointImpl(params);
    } catch (IOException ex) {
        java.util.logging.Logger.getLogger(AuthorWebService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UpdateException ex) {
        java.util.logging.Logger.getLogger(AuthorWebService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:edu.cmu.lti.oaqa.bioasq.passage.PmcContentSetter.java

@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {
    int count = 0;
    for (Document doc : TypeUtil.getRankedDocuments(jcas)) {
        URL url;/*from  w w  w  .  j a va  2  s.  c o m*/
        try {
            url = new URL(String.format(urlFormat, doc.getDocId()));
        } catch (MalformedURLException e) {
            throw new AnalysisEngineProcessException(e);
        }
        String json;
        try {
            json = CharStreams.toString(new InputStreamReader(url.openStream()));
        } catch (IOException e) {
            LOG.error("Error access {}", url.toString());
            throw new AnalysisEngineProcessException(e);
        }
        if (json.isEmpty()) {
            continue;
        }
        List<String> sections;
        try {
            sections = gson.fromJson(json, PmcDocument.class).getSections();
        } catch (JsonSyntaxException | JsonIOException e) {
            throw new AnalysisEngineProcessException(e);
        }
        doc.setSections((StringArray) FSCollectionFactory.createStringArray(jcas, sections));
        List<String> sectionLabels = IntStream.range(0, sections.size()).mapToObj(i -> "sections." + i)
                .collect(toList());
        doc.setSectionLabels((StringArray) FSCollectionFactory.createStringArray(jcas, sectionLabels));
        count++;
    }
    LOG.info("Total pmc documents with content: {}", count);
}

From source file:com.dmdirc.addons.mediasource_windows.WindowsMediaSourceManager.java

/**
 * Get the output from GetMediaInfo.exe for the given player and method
 *
 * @param player Player to ask about//from w  ww .j  av a2s  . co  m
 * @param method Method to call
 *
 * @return a MediaInfoOutput with the results
 */
protected MediaInfoOutput getOutput(final String player, final String method) {
    try {
        final Process myProcess = Runtime.getRuntime()
                .exec(new String[] { filesHelper.getFilesDirString() + "GetMediaInfo.exe", player, method });
        StreamUtils.readStream(myProcess.getErrorStream());
        final String data = CharStreams.toString(new InputStreamReader(myProcess.getInputStream()));
        try {
            myProcess.waitFor();
        } catch (InterruptedException e) {
        }

        return new MediaInfoOutput(myProcess.exitValue(), data);
    } catch (SecurityException | IOException e) {
    }

    return new MediaInfoOutput(-1, "Error executing GetMediaInfo.exe");
}

From source file:org.whispersystems.claserver.PullRequestValidationServlet.java

/**
 * This is the endpoint for the github webhook
 *//*  ww  w  .jav a 2  s.  c o  m*/
protected void doPost(HttpServletRequest request, HttpServletResponse resp)
        throws ServletException, IOException {
    String xHubSig = request.getHeader("X-Hub-Signature");
    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, request.getParameterMap());
    String body = CharStreams.toString(request.getReader());
    GithubPullEvent event = mapper.readValue(mapper.getJsonFactory().createJsonParser(body),
            GithubPullEvent.class);

    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secret = new SecretKeySpec(config.githubSecret.getBytes("UTF-8"), "HmacSHA1");
        mac.init(secret);
        byte[] digest = mac.doFinal(body.getBytes());
        String hmac = String.format("sha1=%s", Hex.encodeHexString(digest));

        if (MessageDigest.isEqual(hmac.getBytes(), xHubSig.getBytes())) {
            updateStatus(config, event.pull_request);
        } else {
            logger.warning("Invalid request signature");
        }
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        e.printStackTrace();
    }
}

From source file:org.lobid.lodmill.JsonDecoder.java

private JsonToken parseJson(final Reader reader) throws IOException, JsonParseException {
    String text = CharStreams.toString(reader);
    this.jsonParser = new JsonFactory().createParser(text);
    JsonToken currentToken = null;// w w  w  . j  a  v a2  s.  c om
    try {
        currentToken = this.jsonParser.nextToken();
    } catch (final JsonParseException e) {
        // is it JSONP ?
        if (text.indexOf(JsonDecoder.JSON_START_CHAR) == -1) {
            LOG.info("No JSON(P) - ignoring");
            return null;
        }
        currentToken = handleJsonp(text);
    }
    while (JsonToken.START_OBJECT != currentToken) {
        this.jsonParser.nextToken();
    }
    return currentToken;
}