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.jesterj.ingest.scanners.JdbcScanner.java

private byte[] getContentBytes(ResultSet rs) throws SQLException {
    byte[] rawBytes = null;

    // If the content column was specified
    if (StringUtils.isNotBlank(contentColumn)) {
        // Get its value.
        Object content = rs.getObject(contentColumn);

        if (content != null) {
            // Clob
            if (content instanceof Clob) {
                Clob clob = (Clob) content;
                try (Reader reader = clob.getCharacterStream()) {
                    rawBytes = CharStreams.toString(reader).getBytes();
                } catch (IOException ex) {
                    String msg = String.format("I/O error while reading value of content column '%s'.",
                            contentColumn);
                    log.error(msg, ex);/*from  ww w  .j  a va2 s  .  co m*/
                }
            }
            // Blob
            else if (content instanceof Blob) {
                Blob blob = (Blob) content;
                try (InputStream stream = blob.getBinaryStream()) {
                    rawBytes = IOUtils.toByteArray(stream);
                } catch (IOException ex) {
                    String msg = String.format("I/O error while reading value of content column '%s'.",
                            contentColumn);
                    log.error(msg, ex);
                }
            }
            // Date (unlikely, but)
            else if (content instanceof Date) {
                rawBytes = convertDateToString(content).getBytes();
            }
            // Anything else
            else {
                rawBytes = content.toString().getBytes();
            }
        }
    }
    return rawBytes;
}

From source file:org.kurento.test.services.SshConnection.java

public static boolean ping(final String ipAddress, int timeout) {
    final CountDownLatch latch = new CountDownLatch(1);

    Thread t = new Thread() {
        @Override//from  w  w w . j a  va  2  s .  c  o m
        public void run() {
            try {
                String[] command = { "ping", "-c", "1", ipAddress };
                Process p = new ProcessBuilder(command).redirectErrorStream(true).start();
                CharStreams.toString(new InputStreamReader(p.getInputStream(), "UTF-8"));
                latch.countDown();
            } catch (Exception e) {
            }
        }
    };
    t.setDaemon(true);
    t.start();

    boolean ping = false;
    try {
        ping = latch.await(timeout, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        log.error("Exception making ping to {} : {}", ipAddress, e.getClass());
    }
    if (!ping) {
        t.interrupt();
    }

    return ping;
}

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

/**
 * Author Load Service/*from  w  w  w  . jav  a2  s  .c  om*/
 *
 * @param resultType
 * @param request
 * @return
 */
@POST
@Path(AUTHOR_UPDATE)
public Response updateAuthorPost(@QueryParam("Endpoint") String resultType,
        @Context HttpServletRequest request) {
    try {
        String params = CharStreams.toString(request.getReader());
        log.debug("EndPoint & GraphURI: {}", params);
        return authorUpdate(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:org.lobid.lodmill.hadoop.IndexFromHdfsInElasticSearch.java

private static String config() {
    String res = null;/*from  w w  w. java  2s.  c  om*/
    try {
        final InputStream config = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("index-config.json");
        try (InputStreamReader reader = new InputStreamReader(config, "UTF-8")) {
            res = CharStreams.toString(reader);
        }
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    return res;
}

From source file:edu.washington.cs.cupid.scripting.java.wizards.JavaCapabilityWizard.java

private InputStream openContents(final String name, final String description, final Class<?> paramType,
        final Class<?> returnType, final String charSet) throws Exception {
    Bundle bundle = CupidScriptingPlugin.getDefault().getBundle();

    URL fileURL = bundle.getEntry("templates/LinearCapability.template");

    if (fileURL == null) {
        throw new IOException("Error locating linear capability script template");
    }//w  w w  .j  a  v  a2 s. c om

    String template = CharStreams
            .toString(new InputStreamReader(fileURL.openStream(), Charset.forName("UTF-8")));

    Engine engine = new Engine();
    Map<String, Object> model = new HashMap<String, Object>();

    model.put("CLASS", formClassName(name));
    model.put("NAME", name);
    model.put("DESCRIPTION", description);
    model.put("INPUT_TYPE", paramType.getSimpleName());
    model.put("OUTPUT_TYPE", returnType.getSimpleName());
    model.put("IMPORTS", Lists.newArrayList(paramType.getName(), returnType.getName()));

    String content = engine.transform(template, model);

    return new ByteArrayInputStream(content.getBytes(charSet));
}

From source file:org.apache.aurora.scheduler.storage.db.DbStorage.java

/**
 * Creates the SQL schema during service start-up.
 * Note: This design assumes a volatile database engine.
 *///  w  w w.  j  a v a 2 s  .c om
@Override
@Transactional
protected void startUp() throws IOException {
    Configuration configuration = sessionFactory.getConfiguration();
    String createStatementName = "create_tables";
    configuration.setMapUnderscoreToCamelCase(true);

    // The ReuseExecutor will cache jdbc Statements with equivalent SQL, improving performance
    // slightly when redundant queries are made.
    configuration.setDefaultExecutorType(ExecutorType.REUSE);

    addMappedStatement(configuration, createStatementName, CharStreams.toString(
            new InputStreamReader(DbStorage.class.getResourceAsStream("schema.sql"), StandardCharsets.UTF_8)));

    try (SqlSession session = sessionFactory.openSession()) {
        session.update(createStatementName);
    }

    enumBackfill.backfill();

    createPoolMetrics();
}

From source file:org.dcache.gridsite.AccessLoggerDelegation.java

private NetLoggerBuilder logCertChain(NetLoggerBuilder log, String certs) {
    try {/* ww  w. ja v  a2 s.  co  m*/
        Reader r = new StringReader(certs);
        InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(r).getBytes(UTF_8));
        X509Certificate[] certificates = CertificateUtils.loadCertificateChain(targetStream, PEM);
        for (int i = 0; i < certificates.length; i++) {
            X509Certificate cert = certificates[i];
            String prefix = "cert." + (i + 1) + ".";
            X500Principal subject = cert.getSubjectX500Principal();
            log.add(prefix + "dn", OpensslNameUtils.convertFromRfc2253(subject.getName(), true));
            log.add(prefix + "notBefore", TimeUtils.relativeTimestamp(cert.getNotBefore().toInstant()));
            log.add(prefix + "notAfter", TimeUtils.relativeTimestamp(cert.getNotAfter().toInstant()));
        }
    } catch (IOException e) {
        log.add("cert.error", e);
    }
    return log;
}

From source file:org.eclipse.jdt.ls.core.internal.contentassist.SignatureHelpRequestor.java

public String computeJavaDoc(CompletionProposal proposal) {
    try {//from   w  w  w.jav  a  2  s. c om
        IType type = unit.getJavaProject().findType(
                SignatureUtil.stripSignatureToFQN(String.valueOf(proposal.getDeclarationSignature())));
        if (type != null) {
            String[] parameters = Signature
                    .getParameterTypes(String.valueOf(SignatureUtil.fix83600(proposal.getSignature())));
            for (int i = 0; i < parameters.length; i++) {
                parameters[i] = getLowerBound(parameters[i]);
            }

            IMethod method = JavaModelUtil.findMethod(String.valueOf(proposal.getName()), parameters,
                    proposal.isConstructor(), type);

            if (method != null && method.exists()) {
                ICompilationUnit unit = type.getCompilationUnit();
                if (unit != null) {
                    unit.reconcile(ICompilationUnit.NO_AST, false, null, null);
                }

                String javadoc = null;
                try {
                    javadoc = new SimpleTimeLimiter().callWithTimeout(() -> {
                        Reader reader = JavadocContentAccess.getPlainTextContentReader(method);
                        return reader == null ? null : CharStreams.toString(reader);
                    }, 500, TimeUnit.MILLISECONDS, true);
                } catch (UncheckedTimeoutException tooSlow) {
                } catch (Exception e) {
                    JavaLanguageServerPlugin.logException("Unable to read documentation", e);
                }
                return javadoc;
            }
        }

    } catch (JavaModelException e) {
        JavaLanguageServerPlugin.logException("Unable to resolve signaturehelp javadoc", e);
    }
    return null;
}

From source file:es.usc.citius.composit.cli.CompositCli.java

public String getLogo() {
    try {//from   w  w  w  .  j  a va 2  s  .c o  m
        return CharStreams.toString(
                new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("logo.txt")));
    } catch (IOException e) {
        return "";
    }
}