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:com.sothawo.taboo2.Taboo2UserService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional<User> optionalUser;
    synchronized (knownUsers) {
        optionalUser = Optional.ofNullable(knownUsers.get(username));
        if (!optionalUser.isPresent()) {
            // reload the data from users file
            log.debug("loading user data");
            knownUsers.clear();//  w ww  . j  a va 2s . c  om
            Optional.ofNullable(taboo2Configuration.getUsers()).ifPresent(filename -> {
                log.debug("user file: {}", filename);
                try {
                    Files.lines(Paths.get(filename)).map(String::trim).filter(line -> !line.isEmpty())
                            .filter(line -> !line.startsWith("#")).forEach(line -> {
                                String[] fields = line.split(":");
                                if (fields.length == 3) {
                                    String user = fields[0];
                                    String hashedPassword = fields[1];
                                    String[] roles = fields[2].split(",");
                                    if (roles.length < 1) {
                                        roles = new String[] { "undef" };
                                    }
                                    List<GrantedAuthority> authorities = new ArrayList<>();
                                    for (String role : roles) {
                                        authorities.add(new SimpleGrantedAuthority(role));
                                    }
                                    knownUsers.put(user, new User(user, hashedPassword, authorities));
                                }
                            });
                    log.debug("loaded {} user(s)", knownUsers.size());
                } catch (IOException e) {
                    log.debug("reading file", e);
                }
            });

            // search again after reload
            optionalUser = Optional.ofNullable(knownUsers.get(username));
        }
    }
    // need to return a copy as Spring security erases the password in the object after verification
    User user = optionalUser.orElseThrow(() -> new UsernameNotFoundException(username));
    return new User(user.getUsername(), user.getPassword(), user.getAuthorities());
}

From source file:pzalejko.iot.hardware.home.core.service.DefaultTemperatureService.java

private double loadTemperatureFromFile(String directory, String fileName) {
    final Path path = Paths.get(directory, fileName);
    if (path.toFile().exists()) {
        try (Stream<String> lines = Files.lines(path)) {
            // @formatter:off
            return lines.filter(s -> s.contains(TEMP_MARKER)).map(TEMPERATURE_VALUE_EXTRACTOR::apply)
                    .findFirst().orElse(Double.NaN);
            // @formatter:on
        } catch (final IOException | NumberFormatException e) {
            LOG.error(LogMessages.COULD_NOT_COLLECT_A_TEMPERATURE, e.getMessage(), e);
        }/*from ww  w.ja v a  2  s  . com*/
    } else {
        LOG.warn(LogMessages.COULD_NOT_COLLECT_TEMPERATURE_MISSING_SOURCE, path.toAbsolutePath());
    }

    return Double.NaN;
}

From source file:test.ExtensionsViewer.java

/**
 * @throws java.io.IOException//from   w w w. j a  va2s.  c  om
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
@Test
public void test() throws IOException {
    Process process = new ProcessBuilder()
            .command("git", "ls-files", "-z", "--", ":(glob,top,exclude).gitattributes")
            .redirectErrorStream(true).start();
    Map<String, List<Path>> map = Maps.newLinkedHashMap();
    try (InputStream is = process.getInputStream();
            InputStreamReader ir = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(ir)) {
        for (StringBuilder sb = new StringBuilder(20);;) {
            int x = br.read();
            if (x == -1) {
                break;
            }
            if (x != 0) {
                sb.append((char) x);
                continue;
            }
            Path path = Paths.get(sb.toString());
            String extension = getExtension(path);
            if (extension.isEmpty()) {
                continue;
            }
            map.computeIfAbsent(extension, __ -> Lists.newArrayList()).add(path);
            sb.setLength(0);
        }
    }

    String gitRoot = new String(IOUtils.toByteArray(
            new ProcessBuilder().command("git", "rev-parse", "--show-toplevel").start().getInputStream()),
            StandardCharsets.UTF_8).trim();

    map.keySet()
            .removeIf(Files.lines(Paths.get(gitRoot, ".gitattributes")).map(String::trim)
                    .filter(str -> str.startsWith("*.")).map(str -> str.replaceAll("^\\*\\.|\\s.+$", ""))
                    .collect(Collectors.toSet())::contains);
    System.out.println(map);
}

From source file:com.att.aro.core.settings.impl.JvmSettings.java

@Override
public String getAttribute(String name) {
    if (!StringUtils.equals("Xmx", name)) {
        throw new IllegalArgumentException("Not a valid property:" + name);
    }/*w  w  w  .  j a  va2 s . c o m*/
    Path path = Paths.get(CONFIG_FILE_PATH);
    if (!path.toFile().exists()) {
        return DEFAULT_MEM;
    }
    try (Stream<String> lines = Files.lines(path)) {
        List<String> values = lines.filter((line) -> StringUtils.contains(line, name))
                .collect(Collectors.toList());
        if (values == null || values.isEmpty()) {
            LOGGER.error("No xmx entries on vm options file");
            return DEFAULT_MEM;
        } else {
            return values.get(values.size() - 1).replace("-Xmx", "").replace("m", "");
        }
    } catch (IOException e) {
        String message = "Counldn't read vm options file";
        LOGGER.error(message, e);
        throw new ARORuntimeException(message, e);
    }
}

From source file:controllers.Index.java

static void createEmptyIndex(final Client aClient, final String aIndexName, final String aPathToIndexSettings)
        throws IOException {
    deleteIndex(aClient, aIndexName);/*from  w w  w  .j av  a2s  .  c  om*/
    CreateIndexRequestBuilder cirb = aClient.admin().indices().prepareCreate(aIndexName);
    if (aPathToIndexSettings != null) {
        String settingsMappings = Files.lines(Paths.get(aPathToIndexSettings)).collect(Collectors.joining());
        cirb.setSource(settingsMappings);
    }
    cirb.execute().actionGet();
    aClient.admin().indices().refresh(new RefreshRequest()).actionGet();
}

From source file:com.baeldung.file.FileOperationsTest.java

@Test
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
    String expectedData = "Hello World from fileTest.txt!!!";

    Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());

    StringBuilder data = new StringBuilder();
    Stream<String> lines = Files.lines(path);
    lines.forEach(line -> data.append(line).append("\n"));
    lines.close();/* w  w  w.  j a  va2 s. c  om*/

    Assert.assertEquals(expectedData, data.toString().trim());
}

From source file:com.baeldung.file.FileOperationsManualTest.java

@Test
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
    String expectedData = "Hello World from fileTest.txt!!!";

    Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());

    StringBuilder data = new StringBuilder();
    Stream<String> lines = Files.lines(path);
    lines.forEach(line -> data.append(line).append("\n"));
    lines.close();//from  www.  j a  va2s.  co m

    assertEquals(expectedData, data.toString().trim());
}

From source file:org.g_node.mergers.LktMergerJenaTest.java

@Test
public void testPlainMergeAndSave() throws Exception {
    final String useCase = "lkt";
    final Path outputFile = this.testFileFolder.resolve("out.ttl");

    final String[] cliArgs = new String[7];
    cliArgs[0] = useCase;/*from   w  ww  .  j  a v  a2s  .  c o  m*/
    cliArgs[1] = "-m";
    cliArgs[2] = this.testMainRdfFile.getAbsolutePath();
    cliArgs[3] = "-i";
    cliArgs[4] = this.testMergeRdfFile.getAbsolutePath();
    cliArgs[5] = "-o";
    cliArgs[6] = outputFile.toString();

    App.main(cliArgs);
    assertThat(Files.exists(outputFile)).isTrue();

    final Stream<String> fileStream = Files.lines(outputFile);
    final List<String> readFile = fileStream.collect(Collectors.toList());
    assertThat(readFile.size()).isEqualTo(5);
    fileStream.close();
}

From source file:uk.trainwatch.nrod.timetable.tools.TimeTableChecker.java

private Stream<String> lines(Path p) {
    try {/*from   w ww . jav  a2  s  . c o m*/
        return Files.lines(p);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex, () -> "Failed to parse " + p);
        return Stream.empty();
    }
}

From source file:com.gitpitch.models.MarkdownModel.java

@Inject
public MarkdownModel(ImageService imageService, VideoService videoService, GISTService gistService,
        @Nullable @Assisted MarkdownRenderer mrndr) {

    this.imageService = imageService;
    this.videoService = videoService;
    this.gistService = gistService;
    this.mrndr = mrndr;

    String consumed = null;//from  ww  w  .  j  a  va 2s  .  com

    if (mrndr != null) {

        String gitRawBase = mrndr.gitRawBase();
        Path mdPath = mrndr.filePath(PITCHME_MD);

        File mdFile = mdPath.toFile();

        if (mdFile.exists()) {

            Optional<SlideshowModel> ssmo = mrndr.ssm();

            final PitchParams pp = ssmo.isPresent() ? ssmo.get().params() : null;
            final YAMLOptions yOpts = ssmo.isPresent() ? ssmo.get().options() : null;

            if (yOpts != null) {
                hSlideDelim = yOpts.hasHorzDelim(pp) ? yOpts.fetchHorzDelim(pp) : HSLIDE_DELIM_DEFAULT;
                vSlideDelim = yOpts.hasVertDelim(pp) ? yOpts.fetchVertDelim(pp) : VSLIDE_DELIM_DEFAULT;
            }

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

                consumed = stream.map(md -> {
                    return process(md, pp, yOpts, gitRawBase);
                }).collect(Collectors.joining("\n"));

                consumed = postProcess(consumed, pp, yOpts, gitRawBase);

            } catch (Exception mex) {
                log.warn("Markdown processing ex={}", mex);
                consumed = "PITCHME.md could not be parsed.";
            }

        } else {
            log.warn("Markdown file does not exist, {}", mdFile);
        }

    }

    this.markdown = consumed;
}