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:io.mangoo.build.Watcher.java

@SuppressWarnings("all")
private void registerAll(final Path path) throws IOException {
    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override// w ww . j  ava2 s .com
        public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) throws IOException {
            register(path);
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:de.thomasbolz.renamer.Renamer.java

/**
 * Step 1 of the renaming process:/*from w  w  w  .j  a  v  a 2  s.c o m*/
 * Analysis steps in the renaming process. Walks the whole file tree of the source directory and creates a CopyTask
 * for each file or directory that is found and does not match the exclusion list.
 * @return a list of all CopyTasks
 */
public Map<Path, List<CopyTask>> prepareCopyTasks() {

    try {
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {

                    /**
                     * If we find a directory create/copy it and add a counter
                     *
                     * @param dir
                     * @param attrs
                     * @return
                     * @throws java.io.IOException
                     */
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Path targetdir = target.resolve(source.relativize(dir));
                        copyTasks.put(dir, new ArrayList<CopyTask>());
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if (!file.getFileName().toString().toLowerCase().matches(EXLUSION_REGEX)) {
                            copyTasks.get(file.getParent()).add(new CopyTask(file, null));
                        } else {
                            excludedFiles.add(file);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    } catch (IOException e) {
        e.printStackTrace();
    }
    sortCopyTasks();
    //        generateTargetFilenames();
    return copyTasks;
}

From source file:org.apache.beam.sdk.extensions.sql.impl.schema.text.BeamTextCSVTableTest.java

@AfterClass
public static void teardownClass() throws IOException {
    Files.walkFileTree(tempFolder, new SimpleFileVisitor<Path>() {

        @Override/*  w w  w  . j a v a  2s  .c  o  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.neo4j.browser.CannedCypherExecutionTest.java

@Test
public void shouldBeAbleToExecuteAllTheCannedCypherQueriesContainedInStaticHtmlFiles() throws Exception {
    URL resourceLoc = getClass().getClassLoader().getResource("browser");
    assertNotNull(resourceLoc);//w w  w. j  av  a 2s  .  c o  m

    final AtomicInteger explainCount = new AtomicInteger(0);
    final AtomicInteger executionCount = new AtomicInteger(0);

    Files.walkFileTree(Paths.get(resourceLoc.toURI()), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
            final GraphDatabaseService database = new TestGraphDatabaseFactory().newImpermanentDatabase();

            String fileName = file.getFileName().toString();
            if (fileName.endsWith(".html")) {
                String content = FileUtils.readTextFile(file.toFile(), Charsets.UTF_8);
                Elements cypherElements = Jsoup.parse(content).select("pre.runnable")
                        .not(".standalone-example");
                for (Element cypherElement : cypherElements) {
                    String statement = replaceAngularExpressions(cypherElement.text());

                    if (!statement.startsWith(":")) {
                        if (shouldExplain(statement)) {
                            try (Transaction transaction = database.beginTx()) {
                                Iterable<Notification> actual = database.execute(prependExplain(statement))
                                        .getNotifications();
                                boolean skipKnownInefficientCypher = !cypherElement.parent().select(".warn")
                                        .isEmpty();
                                if (skipKnownInefficientCypher) {

                                    List<Notification> targetCollection = new ArrayList<Notification>();
                                    CollectionUtils.addAll(targetCollection, actual);
                                    CollectionUtils.filter(targetCollection,
                                            new org.apache.commons.collections4.Predicate<Notification>()

                                            {
                                                @Override
                                                public boolean evaluate(Notification notification) {
                                                    return notification.getDescription()
                                                            .contains(NotificationCode.CARTESIAN_PRODUCT
                                                                    .values().toString());
                                                }
                                            });

                                    assertThat(
                                            format("Query [%s] should only produce cartesian product "
                                                    + "notifications. [%s]", statement, fileName),
                                            targetCollection, empty());

                                    explainCount.incrementAndGet();
                                    transaction.success();

                                } else {
                                    assertThat(format("Query [%s] should produce no notifications. [%s]",
                                            statement, fileName), actual, is(emptyIterable()));
                                    explainCount.incrementAndGet();
                                    transaction.success();
                                }
                            } catch (QueryExecutionException e) {
                                throw new AssertionError(
                                        format("Failed to explain query [%s] in file [%s]", statement, file),
                                        e);
                            }
                        }
                        try (Transaction transaction = database.beginTx()) {
                            database.execute(statement);
                            executionCount.incrementAndGet();
                            transaction.success();
                        } catch (QueryExecutionException e) {
                            throw new AssertionError(
                                    format("Failed to execute query [%s] in file [%s]", statement, file), e);
                        }
                    }
                }
            }
            return FileVisitResult.CONTINUE;
        }
    });

    assertTrue("Static files should contain at least one valid cypher statement",
            executionCount.intValue() >= 1);
    System.out.printf("Explained %s cypher statements extracted from HTML files, with no notifications.%n",
            explainCount);
    System.out.printf("Executed %s cypher statements extracted from HTML files, with no errors.%n",
            executionCount);
}

From source file:org.dragoneronca.util.Configuration.java

/**
 * Init logger and configuration properties.
 * <p/>/*from   ww  w  . j  a v  a2  s.co m*/
 * The configuration directory should contain at least: <ul> <li>file
 * &quot;environment.properties&quot;</li> <li>file &quot;log4j.properties&quot;</li> <li>file
 * &quot;log4j-debug.properties&quot;</li> </ul>
 *
 * @param confDir path to the configuration directory
 */
public Configuration(Path confDir) {

    String productLogConfig = confDir.toAbsolutePath().toString() + File.separator + PRODUCT_LOG_CONFIG;
    String developLogConfig = confDir.toAbsolutePath().toString() + File.separator + DEVELOP_LOG_CONFIG;

    // default configuration for log4j
    LogManager.resetConfiguration();
    if (Files.exists(Paths.get(productLogConfig))) {
        PropertyConfigurator.configure(productLogConfig);
    } else {
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.INFO);
        LOG.warn("Impossible to load configuration for log4j: " + productLogConfig);
        LOG.warn("Using basic configuration for log4j");
    }

    try {
        Files.walkFileTree(confDir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Matcher confMatcher = CONF_PATTERN.matcher(file.getFileName().toString());
                if (confMatcher.matches()) {

                    LOG.info("Loading configuration file: " + file.toAbsolutePath().toString());

                    try {
                        configurationMap.put(confMatcher.group("name"),
                                new PropertiesConfiguration(file.toAbsolutePath().toString()));
                    } catch (ConfigurationException e) {
                        LOG.warn("Exception while loading: " + file.getFileName().toString());
                    }
                }
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        LOG.error("Impossible to load configuration files", e);
        System.exit(-1);
    }

    PropertiesConfiguration envConf = configurationMap.get(ENV_CONF);
    if (envConf != null) {
        String envVar = envConf.getString(ENV_VAR);
        if (envVar != null) {
            Environment tmpEnv = Environment.getByName(envVar);
            if (tmpEnv != null) {
                environment = tmpEnv;
            } else {
                environment = Environment.PRODUCTION;
                LOG.warn("Invalid value for the environment variable in configuration file: "
                        + "config/environment.properties "
                        + "- Only \"development\" and \"production\" are allowed");
            }
        } else {
            environment = Environment.PRODUCTION;
            LOG.warn("Missing environment variable in configuration file: " + "config/environment.properties");
        }
    } else {
        environment = Environment.PRODUCTION;
        LOG.warn("Missing environment configuration file, create: " + "config/environment.properties");
    }

    // advanced logger configuration
    if (environment.equals(Environment.DEVELOPMENT)) {
        LogManager.resetConfiguration();
        if (Files.exists(Paths.get(developLogConfig))) {
            PropertyConfigurator.configure(developLogConfig);
        } else {
            LOG.warn("Impossible to load development configuration for log4j: " + developLogConfig);
            LOG.warn("Using the previous configuration for log4j");
        }
    }
}

From source file:org.roda_project.commons_ip.utils.Utils.java

/**
 * Deletes a directory/file//from   w  ww.  j a  v a  2 s . c  o m
 * 
 * @param path
 *          path to the directory/file that will be deleted. in case of a
 *          directory, if not empty, everything in it will be deleted as well.
 *
 * @throws IOException
 */
public static void deletePath(Path path) throws IOException {
    if (path == null) {
        return;
    }

    try {
        Files.delete(path);

    } catch (DirectoryNotEmptyException e) {
        LOGGER.debug("Directory is not empty. Going to delete its content as well.");
        try {
            Files.walkFileTree(path, 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 e1) {
            throw e1;
        }
    } catch (IOException e) {
        throw e;
    }
}

From source file:fr.duminy.jbackup.core.archive.FileCollector.java

private long collect(final List<SourceWithPath> collectedFiles, final Path source,
        final IOFileFilter directoryFilter, final IOFileFilter fileFilter, final Cancellable cancellable)
        throws IOException {
    final long[] totalSize = { 0L };

    SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
        @Override/*w w  w. ja v  a 2s  . c  o m*/
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            super.preVisitDirectory(dir, attrs);
            if ((directoryFilter == null) || source.equals(dir) || directoryFilter.accept(dir.toFile())) {
                return CONTINUE;
            } else {
                return SKIP_SUBTREE;
            }
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if ((cancellable != null) && cancellable.isCancelled()) {
                return TERMINATE;
            }

            super.visitFile(file, attrs);

            if (!Files.isSymbolicLink(file)) {
                if ((fileFilter == null) || fileFilter.accept(file.toFile())) {
                    LOG.trace("visitFile {}", file.toAbsolutePath());
                    collectedFiles.add(new SourceWithPath(source, file));
                    totalSize[0] += Files.size(file);
                }
            }

            return CONTINUE;
        }
    };
    Files.walkFileTree(source, visitor);

    return totalSize[0];
}

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

public static void parseDirectory(Path dir) {
    try {//from  w ww .  ja  v a2 s .  c om
        long start = System.currentTimeMillis();
        LOGGER.info("?" + dir);
        List<String> fileNames = new ArrayList<>();
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String fileName = parseFile(file);
                if (StringUtils.isNotBlank(fileName)) {
                    fileNames.add(fileName);
                }
                return FileVisitResult.CONTINUE;
            }

        });
        Files.write(Paths.get("src/main/resources/it/manifest"), fileNames);
        long cost = System.currentTimeMillis() - start;
        LOGGER.info("?" + cost + "");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:it.infn.ct.futuregateway.apiserver.storage.LocalStorage.java

@Override
public final void removeAllFiles(final RESOURCE res, final String id) throws IOException {
    java.nio.file.Path filePath = Paths.get(path, res.name().toLowerCase(), id);
    if (Files.notExists(filePath)) {
        return;//from   ww w .j a v a2 s . com
    }
    if (Files.isDirectory(filePath)) {
        Files.walkFileTree(filePath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
                    throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                    throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    Files.delete(filePath);
}

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

public static void parseDir(String dir) {
    LOGGER.info("?" + dir);
    try {//from  ww w .  j  a v  a  2s.c om
        Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                parseFile(file.toFile().getAbsolutePath());
                return FileVisitResult.CONTINUE;
            }

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