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.android.build.gradle.internal.incremental.fixture.ClassEnhancement.java

private static Map<String, List<String>> findEnhancedClasses(final Map<String, File> compileOutputFolders) {
    final Context context = InstrumentationRegistry.getContext();
    return Maps.transformEntries(compileOutputFolders, new Maps.EntryTransformer<String, File, List<String>>() {
        @Override/*  w ww .  j  av  a 2  s .c o m*/
        public List<String> transformEntry(@Nullable String patch, @Nullable File outputFolder) {

            try {
                InputStream classesIS = context.getAssets().open(outputFolder.getPath() + "/classes.txt");
                try {
                    Iterable<String> classPaths = Splitter.on('\n').omitEmptyStrings()
                            .split(CharStreams.toString(new InputStreamReader(classesIS, Charsets.UTF_8)));
                    return Lists.newArrayList(Iterables.transform(classPaths, new Function<String, String>() {
                        @Override
                        public String apply(@Nullable String relativePath) {
                            return relativePath.substring(0, relativePath.length() - 6 /*.class */).replace('/',
                                    '.');
                        }
                    }));
                } finally {
                    classesIS.close();
                }
            } catch (IOException e) {
                throw new IllegalArgumentException("Could not open patch classes.dex", e);
            }
        }
    });
}

From source file:com.axelor.text.StringTemplates.java

@Override
public Template from(Reader reader) throws IOException {
    return fromText(CharStreams.toString(reader));
}

From source file:org.opendaylight.netconf.test.tool.ScaleUtil.java

private static void stopKaraf(final Runtime runtime, final TesttoolParameters params)
        throws IOException, InterruptedException {
    root.info("Stopping karaf and sleeping for 10 sec..");
    String controllerPid = "";
    do {//from www .  j  a  va2s .  com

        final Process pgrep = runtime.exec("pgrep -f org.apache.karaf.main.Main");

        controllerPid = CharStreams.toString(new BufferedReader(new InputStreamReader(pgrep.getInputStream())));
        root.warn(controllerPid);
        runtime.exec("kill -9 " + controllerPid);

        Thread.sleep(10000l);
    } while (!controllerPid.isEmpty());
    deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
}

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

/**
 * Upload ontology content on specified dataset. Graph used is the default
 * one except if specified/*from  ww w .  java 2s . co m*/
 * 
 * @param ontology
 * @param datasetName
 * @param graphName
 * @throws IOException
 * @throws HttpException
 */
public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName)
        throws IOException, HttpException {
    graphName = Strings.emptyToNull(graphName);

    logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName));

    boolean createGraph = (graphName != null) ? true : false;
    String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8");
    String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null;

    URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : ""));

    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

    String boundary = "------------------" + System.currentTimeMillis()
            + Long.toString(Math.round(Math.random() * 1000));

    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConnection.setRequestProperty("Connection", "keep-alive");
    httpConnection.setRequestProperty("Cache-Control", "no-cache");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write(BOUNDARY_DECORATOR + boundary + EOL);
    out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL);
    out.write("Content-Type: application/octet-stream" + EOL + EOL);
    out.write(CharStreams.toString(new InputStreamReader(ontology)));
    out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL);
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_CREATED:
        checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }

}

From source file:oculus.aperture.config.DefaultServerConfigModule.java

@Override
protected void configure() {

    InputStream inp = null;/*from  w w w .  j a va2  s.  c  o m*/

    try {
        /*
         * Load default property values
         */
        inp = ResourceHelper.getStreamForPath("res:///default.properties", null);

        Properties properties = new Properties();
        properties.load(inp);

        try {
            inp.close();
        } catch (IOException ioe) {
            logger.warn("Failed to close properties input stream.", ioe);
        }

        String build = properties.getProperty("aperture.buildnumber");

        // Output build number
        if (build != null) {
            logger.info("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
            logger.info("Aperture version: " + build);
            logger.info("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
        }

        /*
         * Override Properties
         */
        logger.info("Loading app properties...");

        final LinkedList<String> filenames = new LinkedList<String>();

        // Read the property from web.xml or override-web.xml
        final String filename = context.getInitParameter("apertureConfigDefaults");
        final String filename2 = context.getInitParameter("apertureConfig");
        final String filename3 = context.getInitParameter("apertureConfigOverrides");

        // Set up all filenames.
        appendCSV(filename, filenames);
        appendCSV(filename2, filenames);
        appendCSV(filename3, filenames);

        // default default
        if (filenames.isEmpty()) {
            filenames.add("res:///aperture-app.properties");
        }

        // Attempt to load as many as we have.
        while (!filenames.isEmpty()) {
            inp = ResourceHelper.getStreamForPath(filenames.pop(), null);

            if (inp != null) {
                Properties defaults = properties;
                properties = new Properties();
                properties.putAll(defaults); // can't use the built in defaults if merging more than two.
                properties.load(inp);

                try {
                    inp.close();
                } catch (IOException ioe) {
                    logger.warn("Failed to close properties input stream.", ioe);
                }
                inp = null;
            }
        }

        build = properties.getProperty("app.buildnumber");

        // Output build number
        if (build != null) {
            logger.info("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
            logger.info("Application version: " + build);
            logger.info("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
        }

        // trace
        if (logger.isDebugEnabled()) {
            properties.list(System.out);
        }

        // wrap with aperture spi
        UtilProperties aprops = new UtilProperties(properties);

        // bind the set of properties in guice
        bind(oculus.aperture.spi.common.Properties.class).annotatedWith(Names.named("aperture.server.config"))
                .toInstance(aprops);

        // Optionally bind all properties to named annotations (also in guice)
        if (aprops.getBoolean("aperture.server.config.bindnames", false)) {
            Names.bindProperties(this.binder(), properties);
        }

        // Output all properties values to log
        if (logger.isDebugEnabled()) {
            for (Object key : properties.keySet()) {
                logger.debug("System Setting - " + key + ": " + properties.get(key));
            }
        }

        logger.info("Checking for REST supplied aperture.client.configfile...");

        // If client config is to be served by REST (typically used to grab it from an editable file)...
        inp = ResourceHelper.getStreamForPath(aprops.getString("aperture.client.configfile", null), null);

        String json = null;

        if (inp != null) {
            try {
                json = CharStreams
                        .toString(new BufferedReader(new InputStreamReader(inp, Charset.forName("UTF-8"))));
            } finally {
                try {
                    inp.close();
                } catch (IOException ioe) {
                    logger.warn("Failed to close properties input stream.", ioe);
                }
            }
        }

        // bind result in guice.
        Names.bindProperties(this.binder(),
                ImmutableMap.of("aperture.client.config", json != null ? json : "{}"));

    } catch (IOException e) {
        // Failed to load properties, error
        addError(e);

        if (inp != null) {
            try {
                inp.close();
            } catch (IOException ioe) {
                logger.warn("Failed to close properties input stream.", ioe);
            }
        }
    }

}

From source file:com.google.devtools.j2objc.FileProcessor.java

protected void processJarFile(String filename) {
    File f = new File(filename);
    if (!f.exists() || !f.isFile()) {
        ErrorUtil.error("No such file: " + filename);
        return;// w w  w.  j  a v  a  2  s  .  c o m
    }
    String jarDir = "";
    if (Options.useSourceDirectories()) {
        // Prepend the relative directory of the jar file to each entry.
        jarDir = f.getParent() + File.separator;
    }
    try {
        ZipFile zfile = new ZipFile(f);
        try {
            Enumeration<? extends ZipEntry> enumerator = zfile.entries();
            while (enumerator.hasMoreElements()) {
                ZipEntry entry = enumerator.nextElement();
                String path = entry.getName();
                if (path.endsWith(".java")) {
                    Reader in = new InputStreamReader(zfile.getInputStream(entry));
                    String jarURL = String.format("jar:file:%s!%s", f.getPath(), jarDir + path);
                    processSource(jarURL, CharStreams.toString(in));
                }
            }
        } finally {
            zfile.close(); // Also closes input stream.
        }
    } catch (IOException e) {
        ErrorUtil.error(e.getMessage());
    }
}

From source file:org.eclipse.packagedrone.repo.adapter.maven.internal.MavenHandler.java

private String loadResource(final String name) throws IOException {
    try (InputStream is = MavenHandler.class.getResourceAsStream(name);
            Reader r = new InputStreamReader(is, StandardCharsets.UTF_8)) {
        return CharStreams.toString(r);
    }/* w  w w. j a  va2  s  . c  om*/
}

From source file:com.cloudera.flume.handlers.hive.MarkerStore.java

public boolean sendESQuery(String elasticSearchUrl, String sb) {
    boolean success = true;
    LOG.info("sending batched stringentities");
    LOG.info("elasticSearchUrl: " + elasticSearchUrl);
    try {//from  w  ww.  j a  v a  2s.  c om

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(elasticSearchUrl);
        StringEntity se = new StringEntity(sb);

        httpPost.setEntity(se);
        HttpResponse hr = httpClient.execute(httpPost);

        LOG.info("HTTP Response: " + hr.getStatusLine());
        LOG.info("Closing httpConnection");
        httpClient.getConnectionManager().shutdown();
        LOG.info("booooooo: " + CharStreams.toString(new InputStreamReader(se.getContent())));
    } catch (IOException e) {
        e.printStackTrace();
        success = false;
    } finally {
        if (!success) {
            LOG.info("ESQuery wasn't successful, writing to markerfolder");
            writeElasticSearchToMarkerFolder(new StringBuilder(sb));
        }
    }
    LOG.info("ESQuery was successful, yay!");
    return success;

}

From source file:org.kuali.ole.web.LicenseRestServlet.java

private String updateLicense(HttpServletRequest req) throws IOException {
    DocstoreService ds = BeanLocator.getDocstoreService();
    String requestBody = CharStreams.toString(req.getReader());

    License license = new License();
    License licenseObj = (License) license.deserialize(requestBody);
    ds.updateLicense(licenseObj);/*  www .j  a va  2 s .  co m*/
    return responseUrl + licenseObj.getId();

}

From source file:org.assertj.examples.data.neo4j.DragonBallGraph.java

private Collection<String> statements(InputStreamReader reader) throws IOException {
    return from(on(';').trimResults().omitEmptyStrings().split(CharStreams.toString(reader))).toList();
}