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 <T> T readLines(Readable readable, LineProcessor<T> processor) throws IOException 

Source Link

Document

Streams lines from a Readable object, stopping when the processor returns false or all lines have been read and returning the result produced by the processor.

Usage

From source file:edu.cmu.cs.lti.ark.util.FileUtil.java

public static int countLines(InputSupplier<InputStreamReader> inputSupplier) throws IOException {
    return CharStreams.readLines(inputSupplier, LINE_COUNTER);
}

From source file:com.github.lukaszkusek.xml.comparator.document.XMLDocument.java

private Collection<XPathLine> extractXPathLines(String xml, boolean ignoreNamespace)
        throws IOException, TransformerException {

    return CharStreams.readLines(
            new StringInputSupplier(new StringReader(XMLToXPathsTransformer.translate(xml))),
            new XPathLineProcessor(ignoreNamespace));
}

From source file:org.nmdp.validation.tools.ValidateLdGlstrings.java

static ListMultimap<String, SubjectMug> read(final File file) throws IOException {
    BufferedReader reader = null;
    final ListMultimap<String, SubjectMug> subjectmugs = ArrayListMultimap.create();
    final SubjectMug.Builder builder = SubjectMug.builder();
    try {// www  . j av  a 2s.c o  m
        reader = reader(file);
        CharStreams.readLines(reader, new LineProcessor<Void>() {
            private int count = 0;

            @Override
            public boolean processLine(final String line) throws IOException {
                String[] tokens = line.split("\t");
                if (tokens.length < 2) {
                    throw new IOException("illegal format, expected at least 2 columns, found " + tokens.length
                            + "\nline=" + line);
                }

                String fullyQualified = GLStringUtilities.fullyQualifyGLString(tokens[1]);
                MultilocusUnphasedGenotype mug = GLStringUtilities.convertToMug(fullyQualified);
                DetectedLinkageFindings findings = LinkageDisequilibriumAnalyzer.detectLinkages(mug);
                Float minimumDifference = findings.getMinimumDifference(Locus.FIVE_LOCUS);
                minimumDifference = minimumDifference == null ? 0 : minimumDifference;
                SubjectMug subjectMug = builder.reset().withSample(tokens[0]).withGlstring(tokens[1])
                        .withMug(mug).withFindings(findings).withMinimumDifference(minimumDifference).build();

                subjectmugs.put(subjectMug.sample(), subjectMug);
                count++;
                return true;
            }

            @Override
            public Void getResult() {
                return null;
            }
        });

        return subjectmugs;
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

From source file:com.google.devtools.build.lib.skyframe.BlacklistedPackagePrefixesFunction.java

@Nullable
@Override//from   w  w w .j a  v a2  s.  c  o m
public SkyValue compute(SkyKey key, Environment env) throws SkyFunctionException, InterruptedException {
    PathPackageLocator pkgLocator = PrecomputedValue.PATH_PACKAGE_LOCATOR.get(env);
    PathFragment patternsFile = PrecomputedValue.BLACKLISTED_PACKAGE_PREFIXES_FILE.get(env);
    if (env.valuesMissing()) {
        return null;
    }

    if (patternsFile.equals(PathFragment.EMPTY_FRAGMENT)) {
        return new BlacklistedPackagePrefixesValue(ImmutableSet.<PathFragment>of());
    }

    for (Path packagePathEntry : pkgLocator.getPathEntries()) {
        RootedPath rootedPatternFile = RootedPath.toRootedPath(packagePathEntry, patternsFile);
        FileValue patternFileValue = (FileValue) env.getValue(FileValue.key(rootedPatternFile));
        if (patternFileValue == null) {
            return null;
        }
        if (patternFileValue.isFile()) {
            try {
                try (InputStreamReader reader = new InputStreamReader(
                        rootedPatternFile.asPath().getInputStream(), StandardCharsets.UTF_8)) {
                    return new BlacklistedPackagePrefixesValue(
                            CharStreams.readLines(reader, new PathFragmentLineProcessor()));
                }
            } catch (IOException e) {
                String errorMessage = e.getMessage() != null ? "error '" + e.getMessage() + "'" : "an error";
                throw new BlacklistedPatternsFunctionException(new InconsistentFilesystemException(
                        rootedPatternFile.asPath() + " is not readable because: " + errorMessage
                                + ". Was it modified mid-build?"));
            }
        }
    }

    return new BlacklistedPackagePrefixesValue(ImmutableSet.<PathFragment>of());
}

From source file:io.macgyver.core.scheduler.CrontabExpressionExtractor.java

public Optional<ObjectNode> extractCronExpression(Resource r) {
    try (StringReader sr = new StringReader(r.getContentAsString())) {
        List<ObjectNode> scheduleNodes = CharStreams.readLines(sr, new CrontabLineProcessor());
        for (ObjectNode n : scheduleNodes) {
            JsonNode envNode = n.path("env");
            if (envNode.isMissingNode() || profile.startsWith(envNode.asText())) {
                return Optional.of(n);
            }// w  w  w  .  jav a 2 s  .  c om
        }
        return Optional.absent();
    } catch (IOException | RuntimeException e) {
        try {
            logger.warn("unable to extract cron expression: ", r.getContentAsString());
        } catch (Exception IGNORE) {
            logger.warn("unable to extract cron expression");
        }
    }
    return Optional.absent();
}

From source file:eu.numberfour.n4js.analysis.PositiveAnalyser.java

private String withLineNumbers(String code) {
    try {//w w w. ja  va 2  s .  c om
        return CharStreams.readLines(new StringReader(code), new LineProcessor<String>() {

            private final StringBuilder lines = new StringBuilder();
            private int lineNo = 1;

            @Override
            public boolean processLine(String line) throws IOException {
                lines.append(Strings.padStart(String.valueOf(lineNo++), 3, ' ')).append(": ").append(line)
                        .append("\n");
                return true;
            }

            @Override
            public String getResult() {
                return lines.toString();
            }
        });
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage());
    }
}

From source file:reflex.DefaultReflexIOHandler.java

@Override
public ReflexValue forEachLine(ReflexStreamValue fileValue, final IReflexLineCallback iReflexLineCallback) {
    InputStream is = null;/*from  w ww  .j av a2s .co  m*/
    InputStreamReader isr = null;
    final ReflexValue ret = new ReflexVoidValue();
    try {
        is = fileValue.getInputStream();
        isr = new InputStreamReader(is, fileValue.getEncoding());
        CharStreams.readLines(isr, new LineProcessor<String>() {

            @Override
            public boolean processLine(String line) throws IOException {
                ReflexValue v = iReflexLineCallback.callback(line);
                if (v.getValue() == ReflexValue.Internal.BREAK) {
                    return false;
                }
                return true;
            }

            @Override
            public String getResult() {
                return null;
            }

        });

    } catch (FileNotFoundException e) {

    } catch (IOException e) {

    } finally {
        if (is != null) {
            try {
                is.close();
                isr.close();
            } catch (Exception e) {

            }
        }
    }
    return ret;
}

From source file:com.facebook.buck.android.relinker.Symbols.java

private static void runObjdump(ProcessExecutor executor, Tool objdump, SourcePathResolver resolver, Path lib,
        ImmutableList<String> flags, LineProcessor<Void> lineProcessor)
        throws IOException, InterruptedException {
    ImmutableList<String> args = ImmutableList.<String>builder().addAll(objdump.getCommandPrefix(resolver))
            .addAll(flags).add(lib.toString()).build();

    ProcessExecutorParams params = ProcessExecutorParams.builder().setCommand(args)
            .setRedirectError(ProcessBuilder.Redirect.INHERIT).build();
    ProcessExecutor.LaunchedProcess p = executor.launchProcess(params);
    BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
    CharStreams.readLines(output, lineProcessor);
    ProcessExecutor.Result result = executor.waitForLaunchedProcess(p);

    if (result.getExitCode() != 0) {
        throw new RuntimeException(result.getMessageForUnexpectedResult("Objdump"));
    }// w  w  w .  j  a v a 2s . c om
}

From source file:io.takari.m2e.jdt.core.internal.JavaConfigurator.java

protected static Collection<String> parseExportPackage(InputStream is) throws IOException {
    LineProcessor<List<String>> processor = new LineProcessor<List<String>>() {
        final List<String> result = new ArrayList<String>();

        @Override/*w w w  .  j a v  a2 s  .c o m*/
        public boolean processLine(String line) throws IOException {
            result.add(line.replace('.', '/'));
            return true; // keep reading
        }

        @Override
        public List<String> getResult() {
            return result;
        }
    };
    return CharStreams.readLines(new InputStreamReader(is, Charsets.UTF_8), processor);
}

From source file:org.nmdp.ngs.tools.ValidateInterpretation.java

static ListMultimap<String, Interpretation> read(final File file) throws IOException {
    BufferedReader reader = null;
    final ListMultimap<String, Interpretation> interpretations = ArrayListMultimap.create();
    final Interpretation.Builder builder = Interpretation.builder();
    try {//  w w  w  .ja  va  2s  .c om
        reader = reader(file);
        CharStreams.readLines(reader, new LineProcessor<Void>() {
            private int count = 0;

            @Override
            public boolean processLine(final String line) throws IOException {
                String[] tokens = line.split("\t");
                if (tokens.length < 6) {
                    throw new IOException("illegal interpretation format, expected at least 6 columns, found "
                            + tokens.length + "\nline=" + line);
                }
                Interpretation interpretation = builder.reset().withSample(tokens[0]).withLocus(tokens[1])
                        .withGeneFamily(tokens[2]).withAlleleDb(tokens[3]).withAlleleVersion(tokens[4])
                        .withGlstring(tokens[5]).withConsensus(tokens.length > 6 ? tokens[6] : null).build();

                interpretations.put(interpretation.sample(), interpretation);
                count++;
                return true;
            }

            @Override
            public Void getResult() {
                return null;
            }
        });

        return interpretations;
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            // ignore
        }
    }
}