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:org.mycore.common.MCRUtils.java

/**
 * Extracts files in a tar archive. Currently works only on uncompressed tar files.
 * // w  w  w  .  j a va 2 s. co m
 * @param source
 *            the uncompressed tar to extract
 * @param expandToDirectory
 *            the directory to extract the tar file to
 * @throws IOException
 *             if the source file does not exists
 */
public static void untar(Path source, Path expandToDirectory) throws IOException {
    try (TarArchiveInputStream tain = new TarArchiveInputStream(Files.newInputStream(source))) {
        TarArchiveEntry tarEntry;
        FileSystem targetFS = expandToDirectory.getFileSystem();
        HashMap<Path, FileTime> directoryTimes = new HashMap<>();
        while ((tarEntry = tain.getNextTarEntry()) != null) {
            Path target = MCRPathUtils.getPath(targetFS, tarEntry.getName());
            Path absoluteTarget = expandToDirectory.resolve(target).normalize().toAbsolutePath();
            if (tarEntry.isDirectory()) {
                Files.createDirectories(expandToDirectory.resolve(absoluteTarget));
                directoryTimes.put(absoluteTarget,
                        FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
            } else {
                if (Files.notExists(absoluteTarget.getParent())) {
                    Files.createDirectories(absoluteTarget.getParent());
                }
                Files.copy(tain, absoluteTarget, StandardCopyOption.REPLACE_EXISTING);
                Files.setLastModifiedTime(absoluteTarget,
                        FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
            }
        }
        //restore directory dates
        Files.walkFileTree(expandToDirectory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Path absolutePath = dir.normalize().toAbsolutePath();
                Files.setLastModifiedTime(absolutePath, directoryTimes.get(absolutePath));
                return super.postVisitDirectory(dir, exc);
            }
        });
    }
}

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/*from www. java2s . c  o m*/
        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:org.jenkinsci.plugins.workflow.support.steps.ExecutorStepTest.java

@Initializer(before = InitMilestone.JOB_LOADED)
public static void replaceWorkspacePath() throws Exception {
    final File prj = new File(Jenkins.getInstance().getRootDir(), "jobs/p");
    final File workspace = new File(prj, "workspace");
    final String ORIG_WS = "/space/tmp/AbstractStepExecutionImpl-upgrade/jobs/p/workspace";
    final String newWs = workspace.getAbsolutePath();
    File controlDir = new File(workspace, ".eb6272d3");
    if (!controlDir.isDirectory()) {
        return;//from w w w  .  j a v a  2  s . c om
    }
    System.err.println("Patching " + controlDir);
    RiverReader.customResolver = new ObjectResolver() {
        @Override
        public Object readResolve(Object replacement) {
            Class<?> c = replacement.getClass();
            //System.err.println("replacing " + c.getName());
            while (c != Object.class) {
                for (Field f : c.getDeclaredFields()) {
                    if (f.getType() == String.class) {
                        try {
                            f.setAccessible(true);
                            Object v = f.get(replacement);
                            if (ORIG_WS.equals(v)) {
                                //System.err.println("patching " + f);
                                f.set(replacement, newWs);
                                patchedFields.add(f.toString());
                            } else if (newWs.equals(v)) {
                                //System.err.println(f + " was already patched, somehow?");
                            } else {
                                //System.err.println("some other value " + v + " for " + f);
                            }
                        } catch (Exception x) {
                            x.printStackTrace();
                        }
                    }
                }
                c = c.getSuperclass();
            }
            return replacement;
        }

        @Override
        public Object writeReplace(Object original) {
            throw new IllegalStateException();
        }
    };
    Files.walkFileTree(prj.toPath(), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            File f = file.toFile();
            String name = f.getName();
            if (name.equals("program.dat")) {
                /* TODO could not get this to work; stream appeared corrupted:
                patchedFiles.add(name);
                String origContent = FileUtils.readFileToString(f, StandardCharsets.ISO_8859_1);
                String toReplace = String.valueOf((char) Protocol.ID_STRING_SMALL) + String.valueOf((char) ORIG_WS.length()) + ORIG_WS;
                int newLen = newWs.length();
                String replacement = String.valueOf((char) Protocol.ID_STRING_MEDIUM) +
                                 String.valueOf((char) (newLen & 0xff00) >> 8) +
                                 String.valueOf((char) newLen & 0xff) +
                                 newWs; // TODO breaks if not ASCII
                String replacedContent = origContent.replace(toReplace, replacement);
                assertNotEquals("failed to replace " + toReplace + "", replacedContent, origContent);
                FileUtils.writeStringToFile(f, replacedContent, StandardCharsets.ISO_8859_1);
                */
            } else {
                String origContent = FileUtils.readFileToString(f, StandardCharsets.ISO_8859_1);
                String replacedContent = origContent.replace(ORIG_WS, newWs);
                if (!replacedContent.equals(origContent)) {
                    patchedFiles.add(name);
                    FileUtils.writeStringToFile(f, replacedContent, StandardCharsets.ISO_8859_1);
                }
            }
            return super.visitFile(file, attrs);
        }
    });
    FilePath controlDirFP = new FilePath(controlDir);
    controlDirFP.child("jenkins-result.txt").write("0", null);
    FilePath log = controlDirFP.child("jenkins-log.txt");
    log.write(log.readToString() + "simulated later output\n", null);
}

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

@Override
public void deleteBucket(String bucketName) throws AmazonClientException {
    try {/*from   w  ww  . ja  v a  2  s .  com*/
        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 ava 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.
 *//*  ww  w . j  a  v a2s. 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;
}

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

/**
 * Update file and dir permissions./*from   w ww  .  j  av a2  s .  c o  m*/
 *
 * @param path
 * @param filePermissions
 * @param dirPermissions
 * @throws RuntimeIOException
 */
private static void chmodOverwritePermissions(@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 {
                Files.setPosixFilePermissions(file, filePermissions);
            }
            return super.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            Files.setPosixFilePermissions(dir, 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:com.upplication.s3fs.util.AmazonS3ClientMock.java

public void clear() {
    try {//  w  w  w  .ja  v  a2s .  com
        Files.walkFileTree(base, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (dir != base)
                    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) {
        e.printStackTrace();
    }
}

From source file:org.mycore.common.xml.MCRXMLFunctions.java

/**
 * Method returns the amount of space consumed by the files contained in the
 * derivate container. The returned string is already formatted meaning it
 * has already the optimal measurement unit attached (e.g. 142 MB, ).
 *
 * @param derivateId/*from w w  w .  j a  v  a 2 s.c  o  m*/
 *            the derivate id for which the size should be returned
 * @return the size as formatted string
 */
public static String getSize(String derivateId) throws IOException {
    MCRPath rootPath = MCRPath.getPath(derivateId, "/");
    final AtomicLong size = new AtomicLong();
    Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            size.addAndGet(attrs.size());
            return super.visitFile(file, attrs);
        }

    });
    return MCRUtils.getSizeFormatted(size.get());
}

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

/**
 * Searches for the source file of the given ruleset. This provides the information
 * for the "editme" link./*from  ww w .j  a  va 2s . c  o  m*/
 *
 * @param ruleset the ruleset to search for.
 * @return
 * @throws IOException
 */
private String getRuleSetSourceFilepath(RuleSet ruleset) throws IOException {
    final String rulesetFilename = FilenameUtils.normalize(StringUtils.chomp(ruleset.getFileName()));
    final List<Path> foundPathResult = new LinkedList<>();

    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String path = file.toString();
            if (path.contains("src") && path.endsWith(rulesetFilename)) {
                foundPathResult.add(file);
                return FileVisitResult.TERMINATE;
            }
            return super.visitFile(file, attrs);
        }
    });

    if (!foundPathResult.isEmpty()) {
        Path foundPath = foundPathResult.get(0);
        foundPath = root.relativize(foundPath);
        // Note: the path is normalized to unix path separators, so that the editme link
        // uses forward slashes
        return FilenameUtils.normalize(foundPath.toString(), true);
    }

    return StringUtils.chomp(ruleset.getFileName());
}