Example usage for java.nio.file Files lines

List of usage examples for java.nio.file Files lines

Introduction

In this page you can find the example usage for java.nio.file Files lines.

Prototype

public static Stream<String> lines(Path path) throws IOException 

Source Link

Document

Read all lines from a file as a Stream .

Usage

From source file:nl.mpi.oai.harvester.control.FileSynchronization.java

private static Stream<String> getAsStream(final File file) {

    Stream<String> fileStream = null;

    try {//from ww  w . j  a  v  a 2 s .  c o m
        fileStream = Files.lines(Paths.get(file.toURI()));
    } catch (IOException ex) {
        logger.error("No File " + file + ": ", ex);
    }
    return fileStream;
}

From source file:it.serverSystem.ClusterTest.java

private static void expectWriteOperations(Orchestrator orchestrator, boolean expected) throws IOException {
    try (Stream<String> lines = Files.lines(orchestrator.getServer().getWebLogs().toPath())) {
        List<String> writeOperations = lines.filter(ClusterTest::isWriteOperation).collect(Collectors.toList());
        if (expected) {
            assertThat(writeOperations).isNotEmpty();
        } else {// w ww .j  a  v  a 2 s  . c  o m
            assertThat(writeOperations)
                    .as("Unexpected write operations: " + Joiner.on('\n').join(writeOperations)).isEmpty();

        }
    }
}

From source file:notaql.performance.PerformanceTest.java

private static List<JSONObject> readArray(Path path) throws IOException {
    final String input = Files.lines(path).collect(Collectors.joining());
    final JSONArray jsonArray = new JSONArray(input);

    final List<JSONObject> elements = new LinkedList<>();
    for (int i = 0; i < jsonArray.length(); i++) {
        final Object element = jsonArray.get(i);
        if (!(element instanceof JSONObject))
            throw new IOException("Expecting an array of objects as input.");
        elements.add((JSONObject) element);
    }//from  www . j  a  v a  2s  .c o m

    return elements;
}

From source file:org.openthinclient.pkgmgr.UpdateDatabase.java

/**
 * Parse the changelog file/*from   w  w  w  .  j a v  a 2 s . c om*/
 *
 * @param source the package source
 * @param pkg    the package
 * @return a list with parsed lines
 */
private List<String> parseChangelogFile(Source source, Package pkg) {
    try {
        Path changelogFile = directoryStructure.changelogFileLocation(source, pkg);
        LOG.trace("changelogFile: {}", changelogFile);
        return Files.lines(changelogFile).collect(Collectors.toList());
    } catch (IOException e) {
        LOG.error("Cannot read changelogFile for package " + pkg.toStringWithNameAndVersion());
        return Collections.emptyList();
    }
}

From source file:uk.org.cinquin.mutinack.tests.FunctionalTestRerun.java

@Test
public void test() throws InterruptedException, IOException {
    if (run == null) {
        run = testRuns.get(testName);/*from   w  w  w.  ja v a2s  .c  o  m*/
        //TODO Switch to throwing TestRunFailure
        Assert.isNonNull(run, "Could not find parameters for test %s within %s", testName,
                testRuns.keySet().stream().collect(Collectors.joining("\t")));
        Assert.isNonNull(run.parameters.referenceOutput, "No reference output specified for test GenericTest");
        run.parameters.terminateImmediatelyUponError = false;
        if (suppressAlignmentOutput) {
            run.parameters.outputAlignmentFile = Collections.emptyList();
        }
    }

    String referenceOutputDirectory = new File(run.parameters.referenceOutput).getParent();

    final boolean useCustomScript;
    if (new File(referenceOutputDirectory + "/custom_check_script").exists()) {
        useCustomScript = true;
    } else {
        useCustomScript = false;
        Assert.isTrue(new File(run.parameters.referenceOutput).exists(), "File %s does not exist",
                new File(run.parameters.referenceOutput).getAbsolutePath());
    }

    Path referenceOutputPath = Paths.get(run.parameters.referenceOutput);
    String auxOutputFileBaseName = Files.createTempDirectory("functional_test_").toString();
    run.parameters.auxOutputFileBaseName = auxOutputFileBaseName + '/';

    run.parameters.jsonFilePathExtraPrefix = ManagementFactory.getRuntimeMXBean().getName() + this.hashCode();

    try {
        try (ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                ByteArrayOutputStream errStream = new ByteArrayOutputStream()) {

            StaticStuffToAvoidMutating.instantiateThreadPools(64);

            //Only one test should run at a time, so it's OK to use a static variable
            try (PrintStream outPS = new PrintStream(outStream);
                    PrintStream errPS = new PrintStream(errStream)) {
                MutinackGroup.forceKeeperType = duplexKeeperType;
                Mutinack.realMain1(run.parameters, outPS, errPS);
            } finally {
                MutinackGroup.forceKeeperType = null;
            }

            if (useCustomScript) {
                ProcessBuilder pb = new ProcessBuilder("./custom_check_script",
                        run.parameters.jsonFilePathExtraPrefix).directory(new File(referenceOutputDirectory))
                                .redirectErrorStream(true);
                Process process = pb.start();
                try (DataInputStream processOutput = new DataInputStream(process.getInputStream())) {
                    process.waitFor();
                    if (process.exitValue() != 0) {
                        byte[] processBytes = new byte[processOutput.available()];
                        processOutput.readFully(processBytes);
                        throw new FunctionalTestFailed(testName + '\n' + new String(processBytes));
                    }
                }
                return;
            } else {
                final String out = outStream.toString();
                try (Stream<String> referenceOutputLines = Files.lines(referenceOutputPath)) {
                    checkOutput(out, referenceOutputLines);
                }
            }
        }

        File baseOutputDir = referenceOutputPath.getParent().toFile();
        for (String expectedOutputBaseName : baseOutputDir.list((file, name) -> name.startsWith("expected_")
                && !name.equals("expected_run.out") && !name.equals("expected_output.txt"))) {
            File actualOutputFile = new File(
                    auxOutputFileBaseName + '/' + expectedOutputBaseName.replace("expected_", ""));
            if (!actualOutputFile.exists()) {
                throw new FunctionalTestFailed(
                        "Output file " + actualOutputFile.getAbsolutePath() + " was not created");
            }
            //Files.lines needs to be explicitly closed, or else the
            //underlying file does not get closed (apparently even
            //after the stream gets read to the end)
            try (Stream<String> linesToLookFor = Files
                    .lines(Paths.get(baseOutputDir.getAbsolutePath() + '/' + expectedOutputBaseName))) {
                checkOutput(FileUtils.readFileToString(actualOutputFile), linesToLookFor);
            }
        }
    } finally {
        FileUtils.deleteDirectory(new File(auxOutputFileBaseName));
        String prefix = run.parameters.jsonFilePathExtraPrefix;
        if (!prefix.isEmpty()) {
            for (File f : referenceOutputPath.getParent().toFile()
                    .listFiles((dir, name) -> name.startsWith(run.parameters.jsonFilePathExtraPrefix))) {
                f.delete();
            }
        }
    }
}

From source file:org.hawkular.metrics.clients.ptrans.fullstack.CollectdITest.java

private void waitForCollectdValues() throws Exception {
    long c;/* w  w  w.j a  v  a 2s.  c  o m*/
    do {
        Thread.sleep(MILLISECONDS.convert(1, SECONDS));
        c = Files.lines(collectdOut.toPath()).filter(l -> l.startsWith("PUTVAL")).collect(counting());
    } while (c < 1);
}

From source file:org.hawkular.metrics.clients.ptrans.fullstack.CollectdITest.java

private List<Point> getExpectedData() throws Exception {
    return Files.lines(collectdOut.toPath()).filter(l -> l.startsWith("PUTVAL")).map(this::collectdLogToPoint)
            .sorted(Comparator.comparing(Point::getType).thenComparing(Point::getTimestamp)).collect(toList());
}

From source file:com.github.blindpirate.gogradle.util.IOUtils.java

@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE")
public static long countLines(Path path) {
    try (Stream<String> lines = Files.lines(path)) {
        return lines.count();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }//from  w ww  . ja v a 2 s. com
}

From source file:schemacrawler.tools.integration.maven.SchemaCrawlerMojo.java

/**
 * {@inheritDoc}/*from  ww  w .j  a  va 2 s. c  o m*/
 *
 * @see org.apache.maven.reporting.AbstractMavenReport#executeReport(java.util.Locale)
 */
@Override
protected void executeReport(final Locale locale) throws MavenReportException {
    final Log logger = getLog();

    try {
        fixClassPath();

        final Sink sink = getSink();
        logger.info(sink.getClass().getName());

        final Path outputFile = executeSchemaCrawler();

        final Consumer<? super String> outputLine = line -> {
            sink.rawText(line);
            sink.rawText("\n");
            sink.flush();
        };

        final OutputFormat outputFormat = getOutputFormat();

        sink.comment("BEGIN SchemaCrawler Report");
        if (outputFormat == TextOutputFormat.html || outputFormat == GraphOutputFormat.htmlx) {
            Files.lines(outputFile).forEach(outputLine);
        } else if (outputFormat instanceof TextOutputFormat) {
            sink.rawText("<pre>");
            Files.lines(outputFile).forEach(outputLine);
            sink.rawText("</pre>");
        } else if (outputFormat instanceof GraphOutputFormat) {
            final Path graphFile = Paths.get(getReportOutputDirectory().getAbsolutePath(),
                    "schemacrawler." + outputFormat.getFormat());
            Files.move(outputFile, graphFile, StandardCopyOption.REPLACE_EXISTING);

            sink.figure();
            sink.figureGraphics(graphFile.getFileName().toString());
            sink.figure_();
        }
        sink.comment("END SchemaCrawler Report");

        sink.flush();
    } catch (final Exception e) {
        throw new MavenReportException("Error executing SchemaCrawler command " + command, e);
    }
}

From source file:com.gitpitch.services.OfflineService.java

private int processMarkdown(PitchParams pp, Path zipRoot, Optional<SlideshowModel> ssmo) {

    int status = STATUS_UNDEF;

    String consumed = null;/*from  w ww . j  av a2  s.  c o  m*/
    Path mdOnlinePath = zipRoot.resolve(PITCHME_ONLINE_PATH);
    File mdOnlineFile = mdOnlinePath.toFile();

    if (mdOnlineFile.exists()) {

        GRSService grsService = grsManager.getService(grsManager.get(pp));

        MarkdownRenderer mrndr = MarkdownRenderer.build(pp, ssmo, grsService, diskService);

        MarkdownModel markdownModel = (MarkdownModel) markdownModelFactory.create(mrndr);

        try (Stream<String> stream = Files.lines(mdOnlinePath)) {

            consumed = stream.map(md -> {
                return markdownModel.offline(md);
            }).collect(Collectors.joining("\n"));

            Path mdOfflinePath = zipRoot.resolve(PITCHME_OFFLINE_PATH);
            Files.write(mdOfflinePath, consumed.getBytes());

            fetchOnlineAssets(pp, zipRoot);

            status = STATUS_OK;

        } catch (Exception mex) {
            log.warn("processMarkdown: ex={}", mex);
        }

    } else {
        log.warn("processMarkdown: mdOnline not found={}", mdOnlineFile);
    }

    log.debug("processMarkdown: returning status={}", status);
    return status;
}