Example usage for java.nio.file FileVisitResult CONTINUE

List of usage examples for java.nio.file FileVisitResult CONTINUE

Introduction

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

Prototype

FileVisitResult CONTINUE

To view the source code for java.nio.file FileVisitResult CONTINUE.

Click Source Link

Document

Continue.

Usage

From source file:org.niord.core.batch.BatchService.java

/**
 * Called every hour to clean up the batch job "[jobName]/execution" folders for expired files
 *//*from   w  ww.  j  a v  a 2s.com*/
@Schedule(persistent = false, second = "30", minute = "42", hour = "*/1")
protected void cleanUpExpiredBatchJobFiles() {

    long t0 = System.currentTimeMillis();

    // Resolve the list of batch job "execution" folders
    List<Path> executionFolders = getBatchJobSubFolders("execution");

    // Compute the expiry time
    Calendar expiryDate = Calendar.getInstance();
    expiryDate.add(Calendar.DATE, -batchFileExpiryDays);

    // Clean up the files
    executionFolders.forEach(folder -> {
        try {
            Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    if (isDirEmpty(dir)) {
                        log.debug("Deleting batch job directory :" + dir);
                        Files.delete(dir);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (FileUtils.isFileOlder(file.toFile(), expiryDate.getTime())) {
                        log.debug("Deleting batch job file      :" + file);
                        Files.delete(file);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            log.error("Failed cleaning up " + folder + " batch job directory: " + e.getMessage(), e);
        }
    });

    log.debug(String.format("Cleaned up expired batch job files in %d ms", System.currentTimeMillis() - t0));
}

From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java

private Path find(String bucketName, final String key) {
    final Path bucket = find(bucketName);
    if (bucket == null || !Files.exists(bucket)) {
        return null;
    }//from   w  w  w.  j a  va2 s .com
    try {
        final String fileKey = key.replaceAll("/", "%2F");
        final List<Path> matches = new ArrayList<Path>();
        Files.walkFileTree(bucket, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                String relativize = bucket.relativize(dir).toString();
                if (relativize.equals(fileKey)) {
                    matches.add(dir);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String relativize = bucket.relativize(file).toString();
                if (relativize.equals(fileKey)) {
                    matches.add(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });
        if (!matches.isEmpty())
            return matches.iterator().next();
    } catch (IOException e) {
        throw new AmazonServiceException("Problem getting mock S3Element: ", e);
    }

    return null;
}

From source file:com.facebook.buck.io.ProjectFilesystemTest.java

@Test
public void ignoredPathsShouldBeIgnoredWhenWalkingTheFilesystem() throws IOException {
    Config config = ConfigBuilder.createFromText("[project]", "ignore = **/*.orig");

    ProjectFilesystem filesystem = new ProjectFilesystem(tmp.getRoot(), config);
    Files.createDirectories(tmp.getRoot().resolve("foo/bar"));
    filesystem.touch(Paths.get("foo/bar/cake.txt"));
    filesystem.touch(Paths.get("foo/bar/cake.txt.orig"));

    final ImmutableSet.Builder<String> allPaths = ImmutableSet.builder();

    filesystem.walkRelativeFileTree(tmp.getRoot(), new SimpleFileVisitor<Path>() {
        @Override/*from   w  w w  .j av a2s . co  m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            allPaths.add(file.toString());
            return FileVisitResult.CONTINUE;
        }
    });

    ImmutableSet<String> found = allPaths.build();
    assertTrue(found.contains(Paths.get("foo/bar/cake.txt").toString()));
    assertFalse(found.contains(Paths.get("foo/bar/cake.txt.orig").toString()));
}

From source file:org.hawk.orientdb.OrientDatabase.java

private static void deleteRecursively(File f) throws IOException {
    if (!f.exists())
        return;// w  w w  .j  ava  2  s . c  o  m

    Files.walkFileTree(f.toPath(), 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;
        }

    });
}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java

@Test
public void ignoredPathsShouldBeIgnoredWhenWalkingTheFilesystem() throws IOException {
    Config config = ConfigBuilder.createFromText("[project]", "ignore = **/*.orig");

    ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tmp.getRoot(), config);
    Files.createDirectories(tmp.getRoot().resolve("foo/bar"));
    filesystem.touch(Paths.get("foo/bar/cake.txt"));
    filesystem.touch(Paths.get("foo/bar/cake.txt.orig"));

    ImmutableSet.Builder<String> allPaths = ImmutableSet.builder();

    filesystem.walkRelativeFileTree(tmp.getRoot(), new SimpleFileVisitor<Path>() {
        @Override/*from   w  ww.  jav  a 2s  . c om*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            allPaths.add(file.toString());
            return FileVisitResult.CONTINUE;
        }
    });

    ImmutableSet<String> found = allPaths.build();
    assertTrue(found.contains(Paths.get("foo/bar/cake.txt").toString()));
    assertFalse(found.contains(Paths.get("foo/bar/cake.txt.orig").toString()));
}

From source file:jduagui.Controller.java

public static long getSize(String startPath, Map<String, Long> dirs, Map<String, Long> files)
        throws IOException {
    final AtomicLong size = new AtomicLong(0);
    final AtomicLong subdirs = new AtomicLong(0);
    final AtomicLong fs = new AtomicLong(0);
    final File f = new File(startPath);
    final String str = "";
    Path path = Paths.get(startPath);

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override/*from  w ww . j ava  2s .  co  m*/
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            subdirs.incrementAndGet();
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            fs.incrementAndGet();
            size.addAndGet(attrs.size());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            fs.incrementAndGet();
            return FileVisitResult.CONTINUE;
        }
    });
    if (subdirs.decrementAndGet() == -1)
        subdirs.incrementAndGet();

    if (f.isDirectory()) {
        dirs.put(startPath, subdirs.get());
        files.put(startPath, fs.get());
    }
    return size.get();
}

From source file:jduagui.Controller.java

public static void getExtensions(String startPath, Map<String, Extension> exts) throws IOException {
    final AtomicReference<String> extension = new AtomicReference<>("");
    final File f = new File(startPath);
    final String str = "";
    Path path = Paths.get(startPath);

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override/*w w w  . ja v  a 2  s .com*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            storageCache.put(file.toAbsolutePath().toString(), attrs.size());
            extension.set(FilenameUtils.getExtension(file.toAbsolutePath().toString()));

            if (extension.get().equals(str)) {
                if (exts.containsKey(noExt)) {
                    exts.get(noExt).countIncrement();
                    exts.get(noExt).increaseSize(attrs.size());
                } else {
                    exts.put(noExt, new Extension(new AtomicLong(1), new AtomicLong(attrs.size())));
                }
            } else {

                if (exts.containsKey(extension.get())) {
                    exts.get(extension.get()).countIncrement();
                    exts.get(extension.get()).increaseSize(attrs.size());
                } else {
                    exts.put(extension.get(), new Extension(new AtomicLong(1), new AtomicLong(attrs.size())));
                }
            }
            return FileVisitResult.CONTINUE;
        }

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

From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java

@Override
public void deleteBucket(String bucketName) throws AmazonClientException {
    try {// w  w  w . j  a  v a  2  s . c  om
        Path bucket = base.resolve(bucketName);
        Files.walkFileTree(bucket, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

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

From source file:org.olat.core.util.ZipUtil.java

/**
 * Add the content of a directory to a zip stream.
 * /*from  w w  w. j  a  v a 2 s  . c  om*/
 * @param path
 * @param dirName
 * @param zout
 */
public static void addDirectoryToZip(final Path path, final String baseDirName, final ZipOutputStream zout) {
    try {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (!attrs.isDirectory()) {
                    Path relativeFile = path.relativize(file);
                    String names = baseDirName + "/" + relativeFile.toString();
                    zout.putNextEntry(new ZipEntry(names));

                    try (InputStream in = Files.newInputStream(file)) {
                        FileUtils.copy(in, zout);
                    } catch (Exception e) {
                        log.error("", e);
                    }

                    zout.closeEntry();
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.error("", e);
    }
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * If requested by the user, this method walks the script directory discovering, loading, compiling, and initialing an .js javascript files it finds in the specified directory or it's children.
 * @param baseScriptDirectory   The contents of this directory should be structured in the same layout as the url's we wish to interfere with.
 * @param watchScriptDirectory   If true, a watch will be placed on <code>baseScriptDirectory</code> and any javascript file modifications (cud) will be dynamically rebuilt and reflected in the running server. 
 * @return   True if all scripts were successfully loaded.
 *//*w ww .  j  a va  2s  .  c o m*/
protected boolean configureScripts(final List<Path> jsLibs, final HierarchicalConfiguration scriptConfig,
        final Path baseScriptDirectory, boolean watchScriptDirectory) {
    // Our unit test has verified that CompiledScripts can produce objects (endpoints) that can be executed from ANY thread (and even concurrently execute immutable methods).
    // However we have not validated that Nashorn can compile *and* recompile scripts from multiple threads.
    //TODO: Write unit test to see if we can use all available processors to compile discovered javascript files.
    ScriptCompilationExecutor = Executors.newSingleThreadScheduledExecutor();
    // This is done to make sure the engine is allocated in the same thread that will be doing the compiling.
    Callable<Boolean> compileScriptsTask = new Callable<Boolean>() {
        @Override
        public Boolean call() {
            Nashorn = new ScriptEngineManager().getEngineByName("nashorn");

            if (jsLibs != null)
                for (Path lib : jsLibs)
                    if (!loadScriptLibrary(lib))
                        return false;

            // Recursively discover javascript files, compile, load, and setup any that are found.
            EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
            try {
                Files.walkFileTree(baseScriptDirectory, opts, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        if (Files.isDirectory(dir) && dir.getFileName().toString().startsWith("#"))
                            return FileVisitResult.SKIP_SUBTREE;
                        return super.preVisitDirectory(dir, attrs);
                    }

                    @Override
                    public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                        if (Files.isRegularFile(path)) {
                            if (path.toString().toLowerCase().endsWith(".js")) {
                                MakeJavaScriptEndPointDescriptor(baseScriptDirectory, path, scriptConfig,
                                        new NewEndpointSetupCallback());
                            }
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
            } catch (IOException e) {
                Logger.error("Unable recursively load scripts", e);
                return false;
            }
            return true;
        }
    };
    // Walk the root directory recursively compiling all discovered javascript files (does not return until all endpoint files have been setup).
    try {
        if (!ScriptCompilationExecutor.submit(compileScriptsTask).get())
            return false;
    } catch (Throwable e) {
        Logger.error("Unable to compile scripts", e);
        return false;
    }
    if (watchScriptDirectory) {
        try {
            // Establish a watch on the root
            ScriptDirectoryWatcher.establishWatch(baseScriptDirectory, new DirectoryWatchEventListener() {
                // Internal Callable task to load, compile, and initialize a javascript file endpoint.
                final class CreateEndpointTask implements Callable<Void> {
                    public CreateEndpointTask(Path file, EndpointSetupCompleteCallback callback) {
                        this.file = file;
                        this.callback = callback;
                    }

                    private final Path file;
                    private final EndpointSetupCompleteCallback callback;

                    @Override
                    public Void call() {
                        MakeJavaScriptEndPointDescriptor(baseScriptDirectory, file, scriptConfig, callback);
                        return null;
                    }
                }

                // Internal Callable task that gives us the ability to schedule a delayed unload of a deleted or obsoleted endpoint.
                // By delaying for a period of time longer than twice the socket timeout, we can safely call the endpoint's teardown method.
                final class DecommisionEndpointTask implements Callable<Void> {
                    private DecommisionEndpointTask(ScriptObjectMirror endpoint) {
                        this.endpoint = endpoint;
                    }

                    private final ScriptObjectMirror endpoint;

                    @Override
                    public Void call() {
                        if (endpoint.hasMember("teardown"))
                            endpoint.callMember("teardown");
                        return null;
                    }
                }

                /**
                 * Called by the WatchService when the contents of the script directory have changed.
                 */
                @Override
                public void onWatchEvent(Path watchDir, final Path oldFile, final Path newFile,
                        FileChangeType change) {
                    if (change == FileChangeType.eRenamed) {
                        // If it was changed to something that does *not* end .js then it should no longer be considered an endpoint.
                        if (oldFile.toString().toLowerCase().endsWith(".js"))
                            if (!newFile.toString().toLowerCase().endsWith(".js"))
                                change = FileChangeType.eDeleted;
                    }
                    if (change == FileChangeType.eModified || change == FileChangeType.eRenamed) {
                        // Decommission the obsolete and load the update.
                        try {
                            assert newFile.toString().toLowerCase().endsWith(".js"); // Will be true because of the 'rename' check at the top of this method.
                            ScriptCompilationExecutor
                                    .submit(new CreateEndpointTask(newFile, new NewEndpointSetupCallback() {
                                        @Override
                                        public ScriptObjectMirror setupComplete(JavaScriptEndPoint endpoint) {
                                            ScriptObjectMirror old = super.setupComplete(endpoint);
                                            assert old != null;
                                            // Yeah, it's hincky, but it won't be in use this long after we remove it from the Map.
                                            ScriptCompilationExecutor.schedule(new DecommisionEndpointTask(old),
                                                    6, TimeUnit.MINUTES);
                                            return null;
                                        }
                                    }));
                        } catch (Throwable e) {
                            Logger.error("Unable to compile modified script found at "
                                    + newFile.toAbsolutePath().toString(), e);
                        }
                    } else if (change == FileChangeType.eCreated) {
                        // This is the easy one.  If a javascript file was created, load it.
                        if (newFile.toString().toLowerCase().endsWith(".js")) {
                            try {
                                ScriptCompilationExecutor.submit(
                                        new CreateEndpointTask(newFile, new NewEndpointSetupCallback()));
                            } catch (Throwable e) {
                                Logger.error("Unable to compile new script found at "
                                        + newFile.toAbsolutePath().toString(), e);
                            }
                        }
                    } else if (change == FileChangeType.eDeleted) {
                        // Endpoint should be decommisioned.
                        if (oldFile.toString().toLowerCase().endsWith(".js")) {
                            String uriKey = FileToUriKey(baseScriptDirectory, oldFile);
                            ScriptObjectMirror desc = scripts.remove(uriKey);
                            if (desc != null) {
                                // Yeah, it's hincky, but it won't be in use this long after we remove it from the Map.
                                ScriptCompilationExecutor.schedule(new DecommisionEndpointTask(desc), 6,
                                        TimeUnit.MINUTES);
                            }
                        }
                    }
                }
            });
        } catch (IOException e) {
            Logger.error("Unable to establish a real time watch on the script directory.", e);
        }
    } else // Not watching for changes, so we are done with the Executor.
        ScriptCompilationExecutor.shutdown();
    return true;
}