Example usage for java.nio.file Files walkFileTree

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

Introduction

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

Prototype

public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException 

Source Link

Document

Walks a file tree.

Usage

From source file:org.apache.tika.eval.TikaEvalCLITest.java

@Test
public void testComparisonReports() throws Exception {
    CachingFileVisitor v = new CachingFileVisitor();
    Files.walkFileTree(compareReportsDir, v);
    int cnt = 0;//www. j  a  va 2 s . c o  m
    for (Path report : v.getPaths()) {
        if (report.getFileName().toString().endsWith(".xlsx")) {
            cnt++;
        }
    }
    assertTrue(cnt > 33);

}

From source file:org.phenotips.variantstore.input.exomiser6.tsv.Exomiser6TSVManager.java

@Override
public List<String> getAllIndividuals() {
    final List<String> list = new ArrayList<>();

    try {/*from  w  ww.  ja  v a2  s.  c  o m*/
        Files.walkFileTree(this.path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (attrs.isDirectory()) {
                    return FileVisitResult.CONTINUE;
                }
                String filename = file.getFileName().toString();
                String id = StringUtils.removeEnd(filename, suffix);
                list.add(id);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        logger.error("Error getting all individuals", e);
    }

    return list;
}

From source file:org.apdplat.superword.tools.WordClassifierForWebster.java

public static void parseZip(String zipFile) {
    LOGGER.info("?ZIP" + zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile),
            WordClassifierForWebster.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override//from  w  w w .j  av a 2s.  c o m
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/origin-html-temp.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    parseFile(temp.toFile().getAbsolutePath());
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?", e);
    }
}

From source file:com.reactive.hzdfs.dll.JarModuleLoader.java

private Set<File> walkDirectory(Path directory) {
    final Set<File> walkedFiles = new LinkedHashSet<File>();
    try {/*from  w  ww .j a va2 s . c o m*/
        registerWatch(directory);
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.preVisitDirectory(dir, attrs);
                registerWatch(dir);
                return fileVisitResult;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.visitFile(file, attrs);
                if (isJarFile(file.toFile()))
                    walkedFiles.add(file.toFile());

                return fileVisitResult;
            }

        });
    } catch (IOException e) {
        log.error("Failed to walk directory: " + directory.toString(), e);
    }
    return walkedFiles;
}

From source file:org.application.backupsync.PathName.java

public List<PathName> walk() throws IOException {
    final List<PathName> result;

    result = new ArrayList<>();

    if (Files.isReadable(this.path)) {
        Files.walkFileTree(this.path, new SimpleFileVisitor<Path>() {

            @Override//from   ww  w  . j  a v a2s  .c o m
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                result.add(new PathName(file));
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException ex) {
                result.add(new PathName(dir));
                return FileVisitResult.CONTINUE;
            }
        });
    } else {
        throw new IllegalArgumentException("Directory cannot be read: " + this.path.toString());
    }
    return result;
}

From source file:com.yahoo.bard.webservice.util.Utils.java

/**
 * Delete files or directories in the specified path.
 *
 * @param path  The pathname/*from w  w w .  j ava  2  s  . c  om*/
 */
public static void deleteFiles(String path) {
    Path directory = Paths.get(path);

    try {
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apdplat.superword.tools.WordClassifierForOxford.java

public static void parseZip(String zipFile) {
    LOGGER.info("?ZIP" + zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile),
            WordClassifierForOxford.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override//from   w  ww. jav a  2 s .c  o m
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/origin-html-temp.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    parseFile(temp.toFile().getAbsolutePath());
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?", e);
    }
}

From source file:fr.ortolang.diffusion.runtime.engine.task.ImportReferentialEntityTask.java

@Override
public void executeTask(DelegateExecution execution) throws RuntimeEngineTaskException {
    checkParameters(execution);//from  w  ww .  j  a va2 s.c  o  m
    String referentialPathParam = execution.getVariable(REFERENTIAL_PATH_PARAM_NAME, String.class);
    report = new StringBuilder();

    File referentialPathFile = new File(referentialPathParam);
    if (referentialPathFile.exists()) {

        final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.{json}");
        final Path referentialPath = Paths.get(referentialPathParam);
        try {
            Files.walkFileTree(referentialPath, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path filepath, BasicFileAttributes attrs) throws IOException {
                    Path filename = filepath.getFileName();
                    if (filename != null && matcher.matches(filename)) {

                        File jsonFile = filepath.toFile();
                        String content = StreamUtils.getContent(jsonFile);
                        if (content == null) {
                            //                           LOGGER.log(Level.SEVERE, "Referential entity content is empty for file " + jsonFile);
                            report.append(" - referential entity content is empty for file ").append(jsonFile)
                                    .append("\r\n");
                            partial = true;
                            return FileVisitResult.CONTINUE;
                        }

                        String type = extractField(content, "type");
                        if (type == null) {
                            //                           LOGGER.log(Level.SEVERE, "Referential entity type unknown for file " + jsonFile);
                            report.append(" - referential entity type unknown for file ").append(jsonFile)
                                    .append("\r\n");
                            partial = true;
                            return FileVisitResult.CONTINUE;
                        }

                        String name = jsonFile.getName().substring(0, jsonFile.getName().length() - 5);
                        try {
                            boolean exist = exists(name);

                            if (!exist) {
                                createReferentialEntity(name, type, content);
                                report.append(" + referential entity created : ").append(name).append("\r\n");
                            } else {
                                updateReferentialEntity(name, type, content);
                                report.append(" + referential entity updated : ").append(name).append("\r\n");
                            }
                        } catch (RuntimeEngineTaskException e) {
                            //                           LOGGER.log(Level.SEVERE, "  unable to import referential entity ("+type+") named "+name, e);
                            report.append(" - unable to import referential entity '").append(name)
                                    .append("' : ").append(e.getMessage()).append("\r\n");
                            partial = true;
                            return FileVisitResult.CONTINUE;
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

            });
        } catch (Exception e) {
            //            LOGGER.log(Level.SEVERE, "  unable to import referential : " + referentialPathFile, e);
            report.append("Enable to import referential ").append(referentialPathFile).append(" caused by : ")
                    .append(e.getMessage()).append("\r\n");
            partial = true;
        }

    } else {
        //         LOGGER.log(Level.SEVERE, "Referential folder doesn't exists : " + referentialPathFile);
        report.append("Referential folder doesn't exists at ").append(referentialPathFile).append("\r\n");
        partial = true;
    }

    if (partial) {
        throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(),
                "Some entities has not been imported (see trace for detail)"));
    } else {
        throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(),
                "All entities imported succesfully"));
    }
    throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessTraceEvent(execution.getProcessBusinessKey(),
            "Report: \r\n" + report.toString(), null));
}

From source file:org.easyrec.plugin.profilesolr.SolrSimilarityGenerator.java

@Override
protected void doInstall() throws Exception {

    logger.info("Using plugin folder: " + pluginFolder.getURL());
    logger.info("Using solr folder: " + solrFolder.getURL().toString());

    String t = solrFolder.getURI().getRawSchemeSpecificPart().substring(0,
            solrFolder.getURI().getRawSchemeSpecificPart().lastIndexOf("!"));

    File target = pluginFolder.getFile();
    logger.info(target.isDirectory());//from   w w  w. ja v  a  2s . co  m
    File source = null;
    for (File f : target.listFiles()) {
        logger.info(f.getName());
        if (t.contains(f.getName().replaceAll(" ", "%20"))) {
            source = f;
            break;
        }
    }

    Path p = Paths.get(source.toURI());

    FileSystem fs = FileSystems.newFileSystem(p, null);
    Path solr = fs.getPath("/solr");

    solrHomeFolder = Paths.get(target.getPath(), "solr");
    TreeCopy tc = new TreeCopy(solr, solrHomeFolder);
    Files.walkFileTree(solr, tc);

    //        EmbeddedSolrServer solrServer = new EmbeddedSolrServer(solrHomeFolder,"easyrec");

    //        String urlString = "http://localhost:8983/solr/easyrec";
    //        SolrClient solrClient = new HttpSolrClient(urlString);
    //        if (solrServer == null) throw new Exception("Could not initialized Solr server!");
    //        solrSimilarityService.setSolrClient(solrServer);

}

From source file:org.craftercms.commons.mongo.MongoScriptRunner.java

private void runScriptsWithMongoClient() {
    List<String> toExecute = new ArrayList<>();

    try {//from w w w.  j  a va2  s.c o  m
        for (Resource scriptPath : scriptPaths) {
            if (scriptPath.getFile().isDirectory()) {
                Files.walkFileTree(scriptPath.getFile().toPath(), new JSFileVisitor(toExecute));
            } else {
                toExecute.add(scriptPath.getFile().getAbsolutePath());
            }
        }
        final Path allScripsFile = Files.createTempFile("ScriptRunner", ".js");
        StringBuilder builder = new StringBuilder();
        for (String path : toExecute) {
            builder.append(String.format("load('%s');\n", path));
        }
        FileUtils.writeStringToFile(allScripsFile.toFile(), builder.toString(), "UTF-8");
        runScript(allScripsFile);
        Files.deleteIfExists(allScripsFile);
    } catch (IOException | MongoDataException ex) {
        logger.error("Unable to run script using MongoClient", ex);
    }
}