Example usage for java.nio.file Files walkFileTree

List of usage examples for java.nio.file Files walkFileTree

Introduction

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

Prototype

public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException 

Source Link

Document

Walks a file tree.

Usage

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceChecksumServiceTest.java

private String calculateChecksum(Path path) throws Exception {
    if (Files.isDirectory(path)) {
        fileVisitor.clearChecksums();/*from w  ww  .j ava 2 s .c o  m*/
        Files.walkFileTree(path, fileVisitor);
        return fileVisitor.getChecksum(path).orElse(null);
    }
    return calculateFileChecksum(path);
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceImpl.java

private OwncloudLocalQuotaImpl calculateUsedSpace(String username, Path baseLocation) {
    Path userBaseLocation = baseLocation.resolve(username);

    if (Files.notExists(userBaseLocation)) {
        return OwncloudLocalQuotaImpl.builder().username(username).location(baseLocation).build();
    }// w w w . j  av  a2 s.c  o m

    try {
        OwncloudLocalQuotaImpl quota = OwncloudLocalQuotaImpl.builder().username(username)
                .location(userBaseLocation).build();
        log.debug("Calculate the Space used by User {}", username);
        Files.walkFileTree(userBaseLocation, new UsedSpaceFileVisitor(quota::increaseUsed));
        return quota;
    } catch (IOException e) {
        String logMessage = "IOException while calculating the used Space of Location "
                + userBaseLocation.toAbsolutePath().normalize().toString();
        log.error(logMessage);
        throw new OwncloudLocalResourceException(logMessage, e);
    }
}

From source file:com.dotcms.content.elasticsearch.business.ESIndexHelper.java

/**
 * Finds file within the directory named "snapshot-"
 * @param snapshotDirectory/*from  ww  w .j ava 2  s  . c o m*/
 * @return
 * @throws IOException
 */
public String findSnapshotName(File snapshotDirectory) throws IOException {
    String name = null;
    if (snapshotDirectory.isDirectory()) {
        class SnapshotVisitor extends SimpleFileVisitor<Path> {
            private String fileName;

            public String getFileName() {
                return fileName;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().startsWith(SNAPSHOT_PREFIX)) {
                    fileName = file.getFileName().toString();
                    return FileVisitResult.TERMINATE;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        }
        Path directory = Paths.get(snapshotDirectory.getAbsolutePath());
        SnapshotVisitor snapshotVisitor = new SnapshotVisitor();
        Files.walkFileTree(directory, snapshotVisitor);

        String fullName = snapshotVisitor.getFileName();
        if (fullName != null) {
            name = fullName.replaceFirst(SNAPSHOT_PREFIX, "");
        }
    }
    return name;
}

From source file:org.cryptomator.webdav.jackrabbit.resources.EncryptedDir.java

@Override
public void removeMember(DavResource member) throws DavException {
    final Path memberPath = ResourcePathUtils.getPhysicalPath(member);
    try {//from   w w w. ja  v a 2 s . c om
        Files.walkFileTree(memberPath, new DeletingFileVisitor());
    } catch (SecurityException e) {
        throw new DavException(DavServletResponse.SC_FORBIDDEN, e);
    } catch (IOException e) {
        throw new IORuntimeException(e);
    }
}

From source file:fr.ortolang.diffusion.client.cmd.CopyCommand.java

private void copy(Path localPath, String workspace, String remotePath) {
    try {//from   w ww.  ja v a  2s  .  c om
        Files.walkFileTree(localPath, new FileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                switch (mode) {
                case "objects":
                    String remoteDir = remotePath + localPath.getParent().relativize(dir).toString();
                    System.out.println("Copying dir " + dir + " to " + workspace + ":" + remoteDir);
                    try {
                        client.writeCollection(workspace, remoteDir, "");
                    } catch (OrtolangClientException | OrtolangClientAccountException e) {
                        e.printStackTrace();
                        errors.append("-> Unable to copy dir ").append(dir).append(" to ").append(remoteDir)
                                .append("\r\n");
                        return FileVisitResult.TERMINATE;
                    }
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                switch (mode) {
                case "objects":
                    String remoteFile = remotePath + localPath.getParent().relativize(file).toString();
                    System.out.println("Copying file " + file + " to " + workspace + ":" + remoteFile);
                    try {
                        client.writeDataObject(workspace, remoteFile, "", file.toFile(), null);
                    } catch (OrtolangClientException | OrtolangClientAccountException e) {
                        e.printStackTrace();
                        errors.append("-> Unable to copy file ").append(file).append(" to ").append(remoteFile)
                                .append("\r\n");
                        return FileVisitResult.TERMINATE;
                    }
                    break;
                case "metadata":
                    String remoteDir = remotePath
                            + localPath.getParent().relativize(file).getParent().toString();
                    System.out.println("Creating metadata file " + file + " to " + workspace + ":" + remoteDir);
                    String name = file.getFileName().toString();
                    try {
                        client.writeMetaData(workspace, remoteDir, name, null, file.toFile());
                    } catch (OrtolangClientException | OrtolangClientAccountException e) {
                        e.printStackTrace();
                        errors.append("-> Unable to copy file ").append(file).append(" to ").append(remoteDir)
                                .append("\r\n");
                        return FileVisitResult.TERMINATE;
                    }
                    break;
                }
                return FileVisitResult.CONTINUE;
            }

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

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

        });
    } catch (IOException e) {
        System.out.println("Unable to walk file tree: " + e.getMessage());
    }
}

From source file:junit.org.rapidpm.microdao.HsqlDBBaseTestUtils.java

private boolean deleteDirectory(final String path) {
    final File indexDirectory = new File(path);
    if (indexDirectory.exists()) {
        try {//from  w  w  w.  j  a v a  2 s. com
            Files.walkFileTree(indexDirectory.toPath(), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
                        throws IOException {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    return false;
}

From source file:at.ac.tuwien.infosys.util.ImageUtil.java

public void clean() {
    if (imageTempDir != null && imageTempDir.toFile().exists()) {
        try {//from  ww  w  .  j  av a 2 s  . c  o  m
            Files.walkFileTree(imageTempDir, new RemoveFileVisitor());
        } catch (IOException e) {
            // e.printStackTrace();
        }
    }
    if (zipUtil != null)
        zipUtil.clean();
}

From source file:edu.mit.lib.handbag.Controller.java

public void initialize() {

    Image wfIm = new Image(getClass().getResourceAsStream("/SiteMap.png"));
    workflowLabel.setGraphic(new ImageView(wfIm));
    workflowLabel.setContentDisplay(ContentDisplay.BOTTOM);

    workflowChoiceBox.addEventHandler(ActionEvent.ACTION, event -> {
        if (workflowChoiceBox.getItems().size() != 0) {
            return;
        }/*from   w  ww.j a v  a 2  s .  co m*/
        ObservableList<Workflow> wflowList = FXCollections.observableArrayList(loadWorkflows());
        workflowChoiceBox.setItems(wflowList);
        workflowChoiceBox.getSelectionModel().selectedIndexProperty().addListener((ov, value, new_value) -> {
            int newVal = (int) new_value;
            if (newVal != -1) {
                Workflow newSel = workflowChoiceBox.getItems().get(newVal);
                if (newSel != null) {
                    workflowLabel.setText(newSel.getName());
                    generateBagName(newSel.getBagNameGenerator());
                    bagLabel.setText(bagName);
                    sendButton.setText(newSel.getDestinationName());
                    setMetadataList(newSel);
                }
            }
        });
    });

    Image bagIm = new Image(getClass().getResourceAsStream("/Bag.png"));
    bagLabel.setGraphic(new ImageView(bagIm));
    bagLabel.setContentDisplay(ContentDisplay.BOTTOM);

    Image sendIm = new Image(getClass().getResourceAsStream("/Cabinet.png"));
    sendButton.setGraphic(new ImageView(sendIm));
    sendButton.setContentDisplay(ContentDisplay.BOTTOM);
    sendButton.setDisable(true);
    sendButton.setOnAction(e -> transmitBag());

    Image trashIm = new Image(getClass().getResourceAsStream("/Bin.png"));
    trashButton.setGraphic(new ImageView(trashIm));
    trashButton.setContentDisplay(ContentDisplay.BOTTOM);
    trashButton.setDisable(true);
    trashButton.setOnAction(e -> reset(false));

    TreeItem<PathRef> rootItem = new TreeItem<>(new PathRef("", Paths.get("data")));
    rootItem.setExpanded(true);
    payloadTreeView.setRoot(rootItem);
    payloadTreeView.setOnDragOver(event -> {
        if (event.getGestureSource() != payloadTreeView && event.getDragboard().getFiles().size() > 0) {
            event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
        }
        event.consume();
    });
    payloadTreeView.setOnDragDropped(event -> {
        Dragboard db = event.getDragboard();
        boolean success = false;
        if (db.getFiles().size() > 0) {
            for (File dragFile : db.getFiles()) {
                if (dragFile.isDirectory()) {
                    // explode directory and add expanded relative paths to tree
                    relPathSB = new StringBuilder();
                    try {
                        Files.walkFileTree(dragFile.toPath(), new SimpleFileVisitor<Path>() {
                            @Override
                            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                                    throws IOException {
                                relPathSB.append(dir.getFileName()).append("/");
                                return FileVisitResult.CONTINUE;
                            }

                            @Override
                            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                    throws IOException {
                                payloadTreeView.getRoot().getChildren()
                                        .add(new TreeItem<>(new PathRef(relPathSB.toString(), file)));
                                bagSize += Files.size(file);
                                return FileVisitResult.CONTINUE;
                            }
                        });
                    } catch (IOException ioe) {
                    }
                } else {
                    payloadTreeView.getRoot().getChildren()
                            .add(new TreeItem<>(new PathRef("", dragFile.toPath())));
                    bagSize += dragFile.length();
                }
            }
            bagSizeLabel.setText(scaledSize(bagSize, 0));
            success = true;
            updateButtons();
        }
        event.setDropCompleted(success);
        event.consume();
    });

    metadataPropertySheet.setModeSwitcherVisible(false);
    metadataPropertySheet.setDisable(false);
    metadataPropertySheet.addEventHandler(KeyEvent.ANY, event -> {
        checkComplete(metadataPropertySheet.getItems());
        event.consume();
    });
}

From source file:com.bekwam.resignator.commands.UnsignCommand.java

private void registerCleanup() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override/*from   w  ww .ja v  a 2 s  .  c o  m*/
        public void run() {
            if (logger.isDebugEnabled()) {
                logger.debug("[UNSIGN] shutting down unsign jar command");
            }
            if (tempDir != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("[UNSIGN] tempDir is not null");
                }
                try {
                    Files.walkFileTree(tempDir, new SimpleFileVisitor<Path>() {
                        @Override
                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                throws IOException {
                            if (logger.isDebugEnabled()) {
                                logger.debug("[UNSIGN] deleting file={}", file.getFileName());
                            }
                            Files.delete(file);
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                                throws IOException {
                            if (exc == null) {
                                if (logger.isDebugEnabled()) {
                                    logger.debug("[UNSIGN] deleting dir={}", dir.getFileName());
                                }
                                Files.delete(dir);
                                return FileVisitResult.CONTINUE;
                            } else {
                                // directory iteration failed
                                throw exc;
                            }
                        }
                    });
                } catch (Exception exc) {
                    logger.error("error removing tempDir=" + tempDir, exc);
                }
            }
        }
    });
}

From source file:org.eclipse.vorto.remoterepository.internal.dao.FilesystemModelDAO.java

private void walkDirectoryTree(final ModelFoundHandler handler) {
    try {//from w ww.j  a va  2 s .  c  o  m
        Files.walkFileTree(Paths.get(getRepositoryBaseDirectory()), new SimpleFileVisitor<Path>() {
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                handler.handle(file);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new RuntimeException("An I/O error was thrown", e);
    }
}