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.openremote.beehive.configuration.www.UsersAPI.java

private void removeTemporaryFiles(java.nio.file.Path directory) {
    if (directory == null) {
        return;//ww w . j  a  v  a  2  s .co m
    }
    try {
        Files.walkFileTree(directory, new SimpleFileVisitor<java.nio.file.Path>() {
            @Override
            public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs)
                    throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException exc)
                    throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.error("Could not clean-up temporary folder used to create openremote.zip file", e);
    }
}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

@Override
public void doDump(OutputStream out) throws IOException {
    final ZipOutputStream zout = new ZipOutputStream(out);
    final int cutLength = this.repositoryRoot.toString().length() + 1;

    Files.walkFileTree(this.repositoryRoot, new SimpleFileVisitor<Path>() {

        @Override/*  ww  w  . jav  a2s .  c  om*/
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            if (dir.endsWith(".git")) {
                return FileVisitResult.SKIP_SUBTREE;
            } else {
                return FileVisitResult.CONTINUE;
            }
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            String name = file.toString().substring(cutLength);
            ZipEntry ze = new ZipEntry(name);
            try {
                ze.setTime(Files.getLastModifiedTime(file).toMillis());
                ze.setSize(Files.size(file));
                zout.putNextEntry(ze);
                Files.copy(file, zout);
                zout.closeEntry();
            } catch (IOException e) {
                FilebasedRepository.logger.debug(e.getMessage());
            }
            return FileVisitResult.CONTINUE;
        }
    });
    zout.close();
}

From source file:org.apache.openaz.xacml.std.pap.StdEngine.java

@Override
public void removeGroup(PDPGroup group, PDPGroup newGroup) throws PAPException, NullPointerException {
    if (group == null) {
        throw new NullPointerException();
    }//from   w  w  w  .  j a v  a2s.  c o m
    //
    // Does this group exist?
    //
    if (!this.groups.contains(group)) {
        logger.error("This group doesn't exist.");
        throw new PAPException("The group '" + group.getId() + "' does not exist");
    }
    //
    // Is it the default group?
    //
    if (group.isDefaultGroup()) {
        throw new PAPException("You cannot delete the default group.");
    }
    Set<PDP> pdps = group.getPdps();
    //
    // Are there PDPs? If so, then we need a target group
    //
    if (!pdps.isEmpty() && newGroup == null) {
        throw new NullPointerException(
                "Group targeted for deletion has PDPs, you must provide a new group for them.");
    }
    //
    // Move the PDPs
    //
    if (!pdps.isEmpty()) {
        if (!(newGroup instanceof StdPDPGroup)) {
            throw new PAPException("Unexpected class for newGroup: " + newGroup.getClass().getCanonicalName());
        }
        // The movePDP function will modify the set of PDPs in the group.
        // To avoid concurrent modification exceptions we need to duplicate the list before calling that
        // function.
        List<PDP> pdpList = new ArrayList<PDP>();
        for (PDP pdp : pdps) {
            pdpList.add(pdp);
        }
        // now we can use the PDPs from the list without having ConcurrentAccessExceptions
        for (PDP pdp : pdpList) {
            this.movePDP(pdp, newGroup);
        }
    }
    //
    // remove the directory for the group
    //
    String id = group.getId();
    Path groupPath = Paths.get(this.repository.toString(), id);
    //
    // If it exists already
    //
    if (!Files.exists(groupPath)) {
        logger.warn("removeGroup " + id + " directory does not exist" + groupPath.toString());
    } else {
        try {
            Files.walkFileTree(groupPath, new SimpleFileVisitor<Path>() {

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

            });
            //
            // delete the directory
            //
            Files.delete(groupPath);
        } catch (IOException e) {
            logger.error("Failed to delete " + groupPath + ": " + e);
            throw new PAPException("Failed to delete " + id);
        }
    }

    // remove the group from the set of all groups
    groups.remove(group);

    //
    // Save changes
    //
    changed();
    this.doSave();
}

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  va  2  s  .  c  om*/
@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;
    }/* ww w  .j  a  va 2s .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 ww.  j a v a2  s.  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;//from  ww  w.  j  a  va 2 s .co 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  w w . jav a 2s .c  o  m
        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:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java

protected void deleteSubDomain(final File subdomain) {
    String message = "Are you sure you want to delete subdomain\n" + subdomain.getName()
            + "\nThis will remove <B>ALL</B> of its subdomains and policy files.";
    ConfirmDialog dialog = ConfirmDialog.getFactory().create("Confirm SubDomain Deletion", message, "Delete",
            "Cancel");
    dialog.setContentMode(ContentMode.HTML);
    dialog.show(getUI(), new ConfirmDialog.Listener() {
        private static final long serialVersionUID = 1L;

        @Override/*from   w w w .  j  a v a  2 s. com*/
        public void onClose(ConfirmDialog dialog) {
            if (dialog.isConfirmed()) {
                //
                // Iterate the subdomain
                //
                try {
                    Files.walkFileTree(Paths.get(subdomain.getAbsolutePath()), new SimpleFileVisitor<Path>() {
                        @Override
                        public FileVisitResult visitFile(Path deleteFile, BasicFileAttributes attrs)
                                throws IOException {
                            try {
                                boolean removeFromTree = deleteFile.getFileName().toString().endsWith(".xml");
                                Files.delete(deleteFile);
                                if (removeFromTree) {
                                    self.treeWorkspace.removeItem(deleteFile.toFile());
                                }
                                if (logger.isDebugEnabled()) {
                                    logger.debug("Deleted file: " + deleteFile.toString());
                                }
                            } catch (IOException e) {
                                logger.error("Failed to delete file: " + deleteFile.toString(), e);
                                return FileVisitResult.TERMINATE;
                            }
                            return super.visitFile(deleteFile, attrs);
                        }

                        @Override
                        public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                                throws IOException {
                            try {
                                Files.delete(dir);
                                self.treeWorkspace.removeItem(dir.toFile());
                                if (logger.isDebugEnabled()) {
                                    logger.debug("Deleted dir: " + dir.toString());
                                }
                            } catch (IOException e) {
                                logger.error("Failed to delete directory: " + dir.toString(), e);
                                return FileVisitResult.TERMINATE;
                            }
                            return super.postVisitDirectory(dir, exc);
                        }

                    });
                } catch (IOException e) {
                    logger.error("Failed to walk subdomain: " + subdomain.getAbsolutePath(), e);
                }
            }
        }

    }, true);

}

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 a  va  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();
}