Example usage for com.google.common.io CharStreams readLines

List of usage examples for com.google.common.io CharStreams readLines

Introduction

In this page you can find the example usage for com.google.common.io CharStreams readLines.

Prototype

public static List<String> readLines(Readable r) throws IOException 

Source Link

Document

Reads all of the lines from a Readable object.

Usage

From source file:org.kurento.test.grid.GridHandler.java

protected GridHandler() {
    String nodesListProp = System.getProperty(SELENIUM_NODES_LIST_PROPERTY);
    String nodesListFileProp = System.getProperty(SELENIUM_NODES_FILE_LIST_PROPERTY);
    String nodesListUrlProp = System.getProperty(SELENIUM_NODES_URL_PROPERTY);

    if (nodesListUrlProp != null) {
        if (nodeList == null) {
            nodeList = new ArrayList<>();
            try {
                log.trace("Reading node list from URL {}", nodesListUrlProp);
                String contents = readContents(nodesListUrlProp);
                Pattern p = Pattern.compile(IPS_REGEX);
                Matcher m = p.matcher(contents);
                while (m.find()) {
                    nodeList.add(m.group());
                }//from  ww  w  .j  a v  a  2  s  .c  o m
            } catch (IOException e) {
                Assert.fail("Exception reading URL " + nodesListUrlProp + " : " + e.getMessage());
            }
        }

    } else if (nodesListFileProp != null) {
        log.trace("Reading node list from file {}", nodesListFileProp);
        try {
            nodeList = FileUtils.readLines(new File(nodesListFileProp), Charset.defaultCharset());
        } catch (IOException e) {
            Assert.fail("Exception reading node list file: " + e.getMessage());
        }

    } else if (nodesListProp != null) {
        log.trace("Reading node list from property {}", nodesListProp);
        nodeList = new ArrayList<>(Arrays.asList(nodesListProp.split(";")));

    } else {
        log.trace("Using default node list {}", SELENIUM_NODES_LIST_DEFAULT);
        InputStream inputStream = PerformanceTest.class.getClassLoader()
                .getResourceAsStream(SELENIUM_NODES_LIST_DEFAULT);

        try {
            nodeList = CharStreams.readLines(new InputStreamReader(inputStream, Charsets.UTF_8));
        } catch (IOException e) {
            Assert.fail("Exception reading node-list.txt: " + e.getMessage());
        }
    }
}

From source file:org.caleydo.core.util.impute.KNNImpute.java

public static void main(String[] args) throws IOException {
    ImmutableList.Builder<Gene> b = ImmutableList.builder();
    List<String> lines = CharStreams
            .readLines(new InputStreamReader(KNNImpute.class.getResourceAsStream("khan.csv")));
    lines = lines.subList(1, lines.size());
    int j = 0;//from  w  w  w.  j  a  v  a2s.com
    for (String line : lines) {
        String[] l = line.split(";");
        float[] d = new float[l.length];
        int nans = 0;
        for (int i = 0; i < l.length; ++i) {
            if ("NA".equals(l[i])) {
                nans++;
                d[i] = Float.NaN;
            } else {
                d[i] = Float.parseFloat(l[i]);
            }
        }
        b.add(new Gene(j++, nans, d));
    }
    final KNNImputeDescription desc2 = new KNNImputeDescription();
    desc2.setMaxp(100000);
    KNNImpute r = new KNNImpute(desc2, b.build());
    ForkJoinPool p = new ForkJoinPool();
    p.invoke(r);
    try (PrintWriter w = new PrintWriter("khan.imputed.csv")) {
        w.println(StringUtils.repeat("sample", ";", r.samples));
        for (Gene g : r.genes) {
            float[] d = g.data;
            int nan = 0;
            w.print(Float.isNaN(d[0]) ? g.nanReplacements[nan++] : d[0]);
            for (int i = 1; i < d.length; ++i)
                w.append(';').append(String.valueOf(Float.isNaN(d[i]) ? g.nanReplacements[nan++] : d[i]));
            w.println();
        }
    }
}

From source file:pl.llp.aircasting.util.http.HttpBuilder.java

private <T> HttpResult<T> doRequest(HttpUriRequest request, Type target) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResult<T> result = new HttpResult<T>();
    Reader reader = null;/*from ww  w . j ava2s. c o m*/
    InputStream content = null;

    // scoped so high for debugging connectivity in devMode
    String fullJson = null;
    try {
        client.addRequestInterceptor(preemptiveAuth(), 0);

        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 204) {
            result.setStatus(Status.SUCCESS);
            return result;
        }

        content = response.getEntity().getContent();

        reader = new InputStreamReader(content);

        if (Constants.isDevMode()) {
            List<String> strings = CharStreams.readLines(reader);
            fullJson = Joiner.on("\n").join(strings);
            reader = new StringReader(fullJson);
            Logger.i("Full http json: " + fullJson);
        }

        if (response.getStatusLine().getStatusCode() < 300) {
            result.setStatus(Status.SUCCESS);

            T output = gson.fromJson(reader, target);
            result.setContent(output);
        } else {
            result.setStatus(Status.FAILURE);

            Type type = new TypeToken<Map<String, String[]>>() {
            }.getType();
            Map<String, String[]> output = gson.fromJson(reader, type);
            result.setErrors(output);
        }
    } catch (Exception e) {
        Logger.e("Http request failed", e);
        result.setStatus(Status.ERROR);

        return result;
    } finally {
        closeQuietly(content);
        closeQuietly(reader);
        client.getConnectionManager().shutdown();
    }

    return result;
}

From source file:org.akraievoy.couch.CouchDao.java

public List<String> fileLines(final Squab squab, final String fileName) throws IOException {
    return CharStreams.readLines(
            CharStreams.newReaderSupplier(couchFileGet(squab.getCouchPath(), fileName), Charsets.UTF_8));
}

From source file:org.geogig.geoserver.config.LogStoreInitializer.java

private static List<String> parseStatements(URL script) {
    List<String> lines;
    try {//  w  w w.ja v  a  2  s.c  o  m
        OutputStream to = new ByteArrayOutputStream();
        Resources.copy(script, to);
        String scriptContents = to.toString();
        lines = CharStreams.readLines(new StringReader(scriptContents));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    List<String> statements = new ArrayList<String>();
    StringBuilder sb = new StringBuilder();

    for (String line : lines) {
        line = line.trim();
        if (line.startsWith("#") || line.startsWith("-") || line.isEmpty()) {
            continue;
        }
        sb.append(line).append('\n');
        if (line.endsWith(";")) {
            statements.add(sb.toString());
            sb.setLength(0);
        }
    }

    return statements;
}

From source file:com.google.devtools.build.lib.vfs.FileSystem.java

/**
 * Returns the type of the file system path belongs to.
 *
 * <p>The string returned is obtained directly from the operating system, so
 * it's a best guess in absence of a guaranteed api.
 *
 * <p>This implementation uses <code>/proc/mounts</code> to determine the
 * file system type./* w  w  w .j a v a 2 s .co  m*/
 */
public String getFileSystemType(Path path) {
    String fileSystem = "unknown";
    int bestMountPointSegmentCount = -1;
    try {
        Path canonicalPath = path.resolveSymbolicLinks();
        Path mountTable = path.getRelative("/proc/mounts");
        try (InputStreamReader reader = new InputStreamReader(mountTable.getInputStream(), ISO_8859_1)) {
            for (String line : CharStreams.readLines(reader)) {
                String[] words = line.split("\\s+");
                if (words.length >= 3) {
                    if (!words[1].startsWith("/")) {
                        continue;
                    }
                    Path mountPoint = path.getFileSystem().getPath(words[1]);
                    int segmentCount = mountPoint.asFragment().segmentCount();
                    if (canonicalPath.startsWith(mountPoint) && segmentCount > bestMountPointSegmentCount) {
                        bestMountPointSegmentCount = segmentCount;
                        fileSystem = words[2];
                    }
                }
            }
        }
    } catch (IOException e) {
        // pass
    }
    return fileSystem;
}

From source file:com.streamsets.pipeline.lib.parser.shaded.org.aicer.grok.dictionary.GrokDictionary.java

private void addDictionaryAux(Reader reader) throws IOException {

    for (String currentFileLine : CharStreams.readLines(reader)) {

        final String currentLine = currentFileLine.trim();

        if (currentLine.length() == 0 || currentLine.startsWith("#")) {
            continue;
        }/*from ww w .j  ava 2 s  . c  om*/

        int entryDelimiterPosition = currentLine.indexOf(" ");

        if (entryDelimiterPosition < 0) {
            throw new GrokCompilationException(
                    "Dictionary entry (name and value) must be space-delimited: " + currentLine);
        }

        if (entryDelimiterPosition == 0) {
            throw new GrokCompilationException("Dictionary entry must contain a name. " + currentLine);
        }

        final String dictionaryEntryName = currentLine.substring(0, entryDelimiterPosition);
        final String dictionaryEntryValue = currentLine
                .substring(entryDelimiterPosition + 1, currentLine.length()).trim();

        if (dictionaryEntryValue.length() == 0) {
            throw new GrokCompilationException("Dictionary entry must contain a value: " + currentLine);
        }

        regexDictionary.put(dictionaryEntryName, dictionaryEntryValue);
    }
}

From source file:com.google.api.codegen.config.ApiConfig.java

private static ImmutableList<String> getResourceLines(String resourceFileName) throws IOException {
    InputStream fileStream = ConfigProto.class.getResourceAsStream(resourceFileName);
    InputStreamReader fileReader = new InputStreamReader(fileStream, Charsets.UTF_8);
    return ImmutableList.copyOf(CharStreams.readLines(fileReader));
}

From source file:net.sourceforge.jwbf.core.actions.HttpActionClient.java

private String toString(BufferedReader br) throws IOException {
    return Joiner.on("\n").join(CharStreams.readLines(br)) + "\n"; // TODO
                                                                   // remove
                                                                   // trailing
                                                                   // newline
}

From source file:com.sos.jobnet.graph.JobNetGraphBuilder.java

private List<String> readIndexContent(File targetFile) {
    List<String> lines = null;
    try {//w  w w  .j a  va  2  s. c  o m
        if (targetFile.exists()) {
            lines = Files.readLines(targetFile, Charset.defaultCharset());
        } else {
            InputStream in = this.getClass().getResourceAsStream(htmlIndexTemplate);
            lines = CharStreams.readLines(new InputStreamReader(in, Charset.defaultCharset()));
        }
    } catch (IOException e) {
        String msg = "Error creating file " + targetFile.getAbsolutePath();
        logger.error(msg, e);
        throw new JobSchedulerException(msg, e);
    }
    return lines;
}