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.fao.geonet.api.mapservers.GeoFile.java

/**
 * Returns the names of the vector layers (Shapefiles) in the geographic file.
 *
 * @param onlyOneFileAllowed Return exception if more than one shapefile found
 * @return a collection of layer names/* w w w  .j  ava 2 s  . com*/
 * @throws IllegalArgumentException If more than on shapefile is found and onlyOneFileAllowed is
 *                                  true or if Shapefile name is not equal to zip file base
 *                                  name
 */
public Collection<String> getVectorLayers(final boolean onlyOneFileAllowed) throws IOException {
    final LinkedList<String> layers = new LinkedList<String>();
    if (zipFile != null) {
        for (Path path : zipFile.getRootDirectories()) {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String fileName = file.getFileName().toString();
                    if (fileIsShp(fileName)) {
                        String base = getBase(fileName);

                        if (onlyOneFileAllowed) {
                            if (layers.size() > 1)
                                throw new IllegalArgumentException("Only one shapefile per zip is allowed. "
                                        + layers.size() + " shapefiles found.");

                            if (base.equals(getBase(fileName))) {
                                layers.add(base);
                            } else
                                throw new IllegalArgumentException("Shapefile name (" + base
                                        + ") is not equal to ZIP file name (" + file.getFileName() + ").");
                        } else {
                            layers.add(base);
                        }
                    }
                    if (fileIsSld(fileName)) {
                        _containsSld = true;
                        _sldBody = fileName;
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
        if (_containsSld) {
            ZipFile zf = new ZipFile(new File(this.file.toString()));
            InputStream is = zf.getInputStream(zf.getEntry(_sldBody));
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String line;
            _sldBody = "";
            while ((line = br.readLine()) != null) {
                _sldBody += line;
            }
            br.close();
            is.close();
            zf.close();
        }
    }

    return layers;
}

From source file:fr.ortolang.diffusion.client.cmd.CheckBagCommand.java

private void checkSnapshotMetadata(Path root) {
    Path metadata = Paths.get(root.toString(), "metadata");
    try {/* w w w  .j a v  a2 s  .  c  o  m*/
        Files.walkFileTree(metadata, new FileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path target = Paths.get(root.toString(), "objects",
                        metadata.relativize(file.getParent()).toString());
                if (!Files.exists(target)) {
                    errors.append("-> unexisting target for metadata: ").append(file).append("\r\n");
                    if (fix) {
                        try {
                            Files.delete(file);
                            fixed.append("-> deleted metadata: ").append(file).append("\r\n");
                        } catch (IOException e) {
                            errors.append("-> unable to fix: ").append(e.getMessage()).append("\r\n");
                        }
                    }
                } else if (file.endsWith("ortolang-item-json")) {
                    checkOrtolangItemJson(file);
                }
                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 (IOException e) {
        System.out.println("Unable to walk file tree: " + e.getMessage());
    }
}

From source file:io.anserini.index.IndexClueWeb09b.java

static List<Path> discoverWarcFiles(Path p) {

    final List<Path> warcFiles = new ArrayList<>();

    FileVisitor<Path> fv = new SimpleFileVisitor<Path>() {
        @Override/*from  ww  w. j a  v a2s  .c om*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

            Path name = file.getFileName();
            if (name != null && matcher.matches(name))
                warcFiles.add(file);
            return FileVisitResult.CONTINUE;
        }
    };

    try {
        Files.walkFileTree(p, fv);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return warcFiles;
}

From source file:com.aol.advertising.qiao.injector.file.watcher.QiaoFileManager.java

private void preStart() {
    FileFinder finder = new FileFinder(filesPatternForRenameOnInit);
    finder.setMaxFiles(-1);//from ww w  . j  a v a 2s .c  om

    finder.reset();
    try {
        Files.walkFileTree(srcDirPath, finder);

        List<Path> files = finder.getMatchedFiles();
        for (Path f : files) {
            long checksum = CommonUtils.checksumOptionalylUseFileLength(f.toFile(), checksumByteLength);

            if (!doneFileHandler.nameContainsChecksum(f, checksum)) {
                Path new_path = doneFileHandler.renameFileToIncludeChecksum(f, checksum);
                logger.info("renamed " + f.toString() + " to " + new_path.toString());
            }
        }
    } catch (IOException e) {
        logger.warn("error in preStart: " + e.getMessage(), e);
    } catch (InterruptedException e) {
    }

}

From source file:org.jboss.as.test.manualmode.logging.SizeAppenderRestartTestCase.java

private Iterable<Path> listLogFiles() throws IOException {
    final Collection<Path> names = new ArrayList<>();
    Files.walkFileTree(logFile.getParent(), new SimpleFileVisitor<Path>() {
        @Override/*  www.j a  v  a  2  s.c  o m*/
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            names.add(file);
            return super.visitFile(file, attrs);
        }
    });
    return names;
}

From source file:org.talend.dataprep.cache.file.FileSystemContentCacheTest.java

@Test
public void testJanitor() throws Exception {

    // given some cache entries
    List<ContentCacheKey> keys = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        keys.add(new DummyCacheKey("janitor me " + i + 1));
    }/*  w  w  w  .  j a  v a  2s .  com*/
    for (ContentCacheKey key : keys) {
        addCacheEntry(key, "janitor content", ContentCache.TimeToLive.DEFAULT);
        Assert.assertThat(cache.has(key), is(true));
    }

    // when eviction is performed and the janitor is called
    for (ContentCacheKey key : keys) {
        cache.evict(key);
    }
    janitor.janitor();

    // then no file in the cache should be left
    Files.walkFileTree(Paths.get(TEST_DIRECTORY), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (!StringUtils.contains(file.toFile().getName(), ".nfs")) {
                Assert.fail("file " + file + " was not cleaned by the janitor");
            }
            return super.visitFile(file, attrs);
        }
    });
}

From source file:org.ng200.openolympus.FileAccess.java

public static void walkFileTree(final Path directory, final FileVisitor<Path> visitor) throws IOException {
    Files.walkFileTree(directory, visitor);
}

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

@Override
protected void doUninstall() throws Exception {
    SolrClient sc = solrSimilarityService.getSolrClient();
    if (sc != null)
        sc.close();//from w  w w.j ava 2  s. c  o m
    Files.walkFileTree(solrHomeFolder, new TreeDelete());
}

From source file:com.rhythm.louie.pbcompiler.PBCompilerMojo.java

@Override
public void execute() throws MojoExecutionException {
    if (!cppgen && !pygen && !javagen) {
        getLog().warn("PB Compiler had nothing to run!");
        return;// w  w w  .  j  ava2s.  com
    }

    //adjust directories according to basedir, and create if necessary
    if (javagen) {
        javadir = basedirectory + "/" + javadir;
        makeDir(javadir);
    }
    if (pygen) {
        pythondir = basedirectory + "/" + pythondir;
        makeDir(pythondir);
    }
    if (cppgen) {
        cppdir = basedirectory + "/" + cppdir;
        makeDir(cppdir);
    }

    List<String> args = new ArrayList<>();
    args.add(compiler);
    args.add("--proto_path=" + basedirectory + "/" + protosrc);

    if (compilerInclude != null && compilerInclude.length > 0) {
        for (String dir : compilerInclude) {
            args.add("--proto_path=" + dir);
        }
    } else {
        // Try to find the google include in some known include dirs
        for (String dir : includeDirs) {
            File libdir = new File(dir + "/google");
            if (libdir.exists()) {
                args.add("--proto_path=" + dir);
            }
        }
    }

    String archivePath = builddirectory + "/" + mavenSharedDir;
    File sharedArchive = new File(archivePath);
    if (sharedArchive.exists()) {
        args.add("--proto_path=" + archivePath);
    }
    if (javagen)
        args.add("--java_out=" + javadir);
    if (pygen)
        args.add("--python_out=" + pythondir);
    if (cppgen)
        args.add("--cpp_out=" + cppdir);

    //Find the proto files 
    File dir = new File(basedirectory + "/" + protosrc);
    IOFileFilter filter = new WildcardFileFilter("**.proto");
    Iterator<File> files = FileUtils.iterateFiles(dir, filter, TrueFileFilter.INSTANCE);
    while (files.hasNext()) {
        args.add(files.next().toString());
    }

    try {
        execProtoCompile(args);
    } catch (IOException ex) {
        throw new MojoExecutionException(ex.toString());
    }

    if (pygen) {
        //Generate __init__ files throughout tree where necessary
        Path pybase = Paths.get(pythondir);
        PlacePyInit pf = new PlacePyInit();
        pf.start = pybase;
        try {
            Files.walkFileTree(pybase, pf);
        } catch (IOException ex) {
            getLog().error(ex.toString());
        }
    }

    if (javagen) {
        //Add the gen'ed java dir back into maven resources
        getLog().debug("Injecting the Java PB dir into the compile time source root");
        project.addCompileSourceRoot(javadir);
    }

}

From source file:org.roda.core.storage.fs.FSUtils.java

private static void moveRecursively(final Path sourcePath, final Path targetPath, final boolean replaceExisting)
        throws GenericException {
    final CopyOption[] copyOptions = replaceExisting ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
            : new CopyOption[] {};

    try {//from  w  w  w.ja va2s  .co m
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path sourceDir, BasicFileAttributes attrs)
                    throws IOException {
                Path targetDir = targetPath.resolve(sourcePath.relativize(sourceDir));
                LOGGER.trace("Creating target directory {}", targetDir);
                Files.createDirectories(targetDir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path sourceFile, BasicFileAttributes attrs) throws IOException {
                Path targetFile = targetPath.resolve(sourcePath.relativize(sourceFile));
                LOGGER.trace("Moving file from {} to {}", sourceFile, targetFile);
                Files.move(sourceFile, targetFile, copyOptions);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path sourceFile, IOException exc) throws IOException {
                LOGGER.trace("Deleting source directory {}", sourceFile);
                Files.delete(sourceFile);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new GenericException(
                "Error while moving (recursively) directory from " + sourcePath + " to " + targetPath, e);
    }

}