Example usage for java.nio.file SimpleFileVisitor SimpleFileVisitor

List of usage examples for java.nio.file SimpleFileVisitor SimpleFileVisitor

Introduction

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

Prototype

protected SimpleFileVisitor() 

Source Link

Document

Initializes a new instance of this class.

Usage

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * Update file and dir permissions.//from   ww w. j  av  a  2 s  .  c o m
 *
 * @param path
 * @param filePermissions
 * @param dirPermissions
 * @throws RuntimeIOException
 */
private static void chmodAddPermissions(@Nonnull Path path,
        @Nonnull final Set<PosixFilePermission> filePermissions,
        @Nonnull final Set<PosixFilePermission> dirPermissions) throws RuntimeIOException {
    if (!Files.exists(path)) {
        throw new IllegalArgumentException("Given path " + path + " does not exist");
    }

    SimpleFileVisitor<Path> setReadOnlyFileVisitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (Files.isDirectory(file)) {
                throw new IllegalStateException("No dir expected here: " + file);
            } else {
                Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(file);
                Files.setPosixFilePermissions(file, Sets.union(existingPermissions, filePermissions));
            }
            return super.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            Set<PosixFilePermission> existingPermissions = Files.getPosixFilePermissions(dir);
            Files.setPosixFilePermissions(dir, Sets.union(existingPermissions, dirPermissions));
            return super.preVisitDirectory(dir, attrs);
        }
    };
    try {
        Files.walkFileTree(path, setReadOnlyFileVisitor);
    } catch (IOException e) {
        throw new RuntimeIOException("Exception setting permissions file permissions to " + filePermissions
                + " and folder permissions to " + dirPermissions + " on " + path, e);
    }
}

From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java

public static void recursiveDelete(Path directory) throws IOException {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override/*from w w  w . ja v a 2  s . co m*/
        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;
        }

    });
}

From source file:net.sourceforge.pmd.docs.RuleDocGenerator.java

private String getRuleClassSourceFilepath(String ruleClass) throws IOException {
    final String relativeSourceFilename = ruleClass.replaceAll("\\.", Matcher.quoteReplacement(File.separator))
            + ".java";
    final List<Path> foundPathResult = new LinkedList<>();

    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
        @Override/*from w  w w  .jav  a2 s.  c  o m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String path = file.toString();
            if (path.contains("src") && path.endsWith(relativeSourceFilename)) {
                foundPathResult.add(file);
                return FileVisitResult.TERMINATE;
            }
            return super.visitFile(file, attrs);
        }
    });

    if (!foundPathResult.isEmpty()) {
        Path foundPath = foundPathResult.get(0);
        foundPath = root.relativize(foundPath);
        return FilenameUtils.normalize(foundPath.toString(), true);
    }

    return FilenameUtils.normalize(relativeSourceFilename, true);
}

From source file:org.kurento.test.services.KmsService.java

private void deleteFolderAndContent(Path folder) throws IOException {
    if (folder != null) {
        Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
            @Override//w  w  w .  j ava  2s  . co  m
            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;
            }
        });
    }
}

From source file:org.fao.geonet.api.records.formatters.FormatterApi.java

public synchronized Element getPluginLocResources(final ServiceContext context, Path formatDir)
        throws Exception {
    final String formatDirPath = formatDir.toString();
    Element allLangResources = this.pluginLocs.get(formatDirPath);
    if (isDevMode(context) || allLangResources == null) {
        allLangResources = new Element("loc");
        Path baseLoc = formatDir.resolve("loc");
        if (Files.exists(baseLoc)) {
            final Element finalAllLangResources = allLangResources;
            Files.walkFileTree(baseLoc, new SimpleFileVisitor<Path>() {
                private void addTranslations(String locDirName, Element fileElements) {
                    if (locDirName != null && !locDirName.isEmpty()) {
                        Element resources = finalAllLangResources.getChild(locDirName);
                        if (resources == null) {
                            resources = new Element(locDirName);
                            finalAllLangResources.addContent(resources);
                        }/*from   www .  ja v  a 2 s. c o  m*/
                        resources.addContent(fileElements);
                    }
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (file.getFileName().toString().toLowerCase().endsWith(".xml")) {
                        try {
                            final Element fileElements = Xml.loadFile(file);
                            final String fileName = getNameWithoutExtension(file.getFileName().toString());
                            fileElements.setName(fileName);
                            final String locDirName = getNameWithoutExtension(
                                    file.getParent().getFileName().toString());
                            addTranslations(locDirName, fileElements);
                        } catch (JDOMException e) {
                            throw new RuntimeException(e);
                        }
                    } else if (file.getFileName().toString().toLowerCase().endsWith(".json")) {
                        try {
                            final String fileName = getNameWithoutExtension(file.getFileName().toString());
                            final String[] nameParts = fileName.split("-", 2);
                            IsoLanguagesMapper isoLanguagesMapper = context.getBean(IsoLanguagesMapper.class);
                            String lang = isoLanguagesMapper.iso639_1_to_iso639_2(nameParts[0].toLowerCase(),
                                    nameParts[0]);
                            final JSONObject json = new JSONObject(
                                    new String(Files.readAllBytes(file), Constants.CHARSET));
                            Element fileElements = new Element(nameParts[1]);
                            final Iterator keys = json.keys();
                            while (keys.hasNext()) {
                                String key = (String) keys.next();
                                fileElements.addContent(new Element(key).setText(json.getString(key)));
                            }
                            addTranslations(lang, fileElements);
                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    return super.visitFile(file, attrs);
                }
            });
        }

        this.pluginLocs.put(formatDirPath, allLangResources);
    }
    return allLangResources;
}

From source file:fr.pilato.elasticsearch.crawler.fs.test.integration.FsCrawlerImplAllParametersIT.java

/**
 * Test case for #95: https://github.com/dadoonet/fscrawler/issues/95 : Folder index is not getting delete on delete of folder
 *///  ww w  .j a v a 2s .co m
@Test
public void test_remove_folder_deleted_enabled() throws Exception {
    Fs fs = startCrawlerDefinition().setRemoveDeleted(true).build();
    startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);

    // We should have 7 docs first
    countTestHelper(getCrawlerName(), null, 7, currentTestResourceDir);

    logContentOfDir(currentTestResourceDir, Level.DEBUG);

    // We remove a directory
    logger.info("  ---> Removing dir subdir1");
    Files.walkFileTree(currentTestResourceDir.resolve("subdir1"), 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;
        }
    });

    logContentOfDir(currentTestResourceDir, Level.DEBUG);

    // We expect to have 4 docs now
    countTestHelper(getCrawlerName(), null, 4, currentTestResourceDir);
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * Modifies given allFiles object to include all files given by the incl pattern
 * //www .  j  a v a2  s .  co  m
 * Semantics: Add all files from localRoot to allFiles matching the pattern
 */
private void handleInclude(final Include incl, final Path localRoot, final Set<Path> allFiles) {
    final PathMatcher pathMatcher = localRoot.getFileSystem().getPathMatcher("glob:" + incl.getPattern());
    try {
        Files.walkFileTree(localRoot, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path relFile = localRoot.relativize(file);
                if (pathMatcher.matches(relFile)) {
                    allFiles.add(file);
                }
                return CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (pathMatcher.matches(dir)) {
                    Set<Path> filesToAdd = CSARImporter.this.getAllFiles(dir);
                    allFiles.addAll(filesToAdd);
                    return SKIP_SUBTREE;
                } else {
                    return CONTINUE;
                }
            }
        });
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * Lists all files contained in the given path
 *//*from   www .  ja  v  a 2  s  . c om*/
private Set<Path> getAllFiles(Path startPath) {
    final Set<Path> res = new HashSet<>();
    try {
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                res.add(file);
                return CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    return res;
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * Unzips the specified zip file to the specified destination directory. Replaces any files in the destination, if they already exist.
 * //from  w ww .  ja v  a  2s  . c o  m
 * @param zipFile
 *          the name of the zip file to extract
 * @param destDir
 *          the directory to unzip to
 * @throws IOException
 */
public static void unzip(Path zipFile, final Path destDir) {
    Map<String, String> env = new HashMap<>();

    try {
        // if the destination doesn't exist, create it
        if (!Files.exists(destDir)) {
            Files.createDirectories(destDir);
        }

        // check if file exists
        env.put("create", String.valueOf(!Files.exists(zipFile)));
        // use a Zip filesystem URI
        URI fileUri = zipFile.toUri(); // here
        URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);

        try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) {
            final Path root = zipfs.getPath("/");

            // walk the zip file tree and copy files to the destination
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    final Path destFile = Paths.get(destDir.toString(), file.toString());
                    LOGGER.debug("Extracting file {} to {}", file, destFile);
                    Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    final Path dirToCreate = Paths.get(destDir.toString(), dir.toString());
                    if (!Files.exists(dirToCreate)) {
                        LOGGER.debug("Creating directory {}", dirToCreate);
                        Files.createDirectory(dirToCreate);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } catch (Exception e) {
        LOGGER.error("Failed to create zip file!" + e.getMessage());
    }
}