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:uk.co.unclealex.executable.impl.MakeLinksCommandRunnerTest.java

protected Path copy(String testCase, String directoryName) throws IOException {
    Path sourceDir = rootDir.resolve(testCase).resolve(directoryName);
    Path target = tmpDir.resolve(directoryName);
    Files.createDirectories(target);
    if (Files.exists(sourceDir)) {
        FileUtils.copyDirectory(sourceDir.toFile(), target.toFile());
        FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
            @Override//from w w  w .  j a va 2s  .co m
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String name = file.getFileName().toString();
                for (Entry<String, Path> entry : symlinksByName.entrySet()) {
                    String suffix = entry.getKey();
                    Path symlink = entry.getValue();
                    if (name.endsWith(suffix)) {
                        Files.delete(file);
                        String newName = name.substring(0, name.length() - suffix.length());
                        Files.createSymbolicLink(file.resolveSibling(newName), symlink);
                        return FileVisitResult.CONTINUE;
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        };
        Files.walkFileTree(target, visitor);
    }
    return target;
}

From source file:com.amazonaws.codepipeline.jenkinsplugin.CompressionTools.java

public static List<File> addFilesToCompress(final Path pathToCompress, final BuildListener listener)
        throws IOException {
    final List<File> files = new ArrayList<>();

    if (pathToCompress != null) {
        Files.walkFileTree(pathToCompress, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {
                    @Override/*from   www  .j  ava  2 s.c  o  m*/
                    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                            throws IOException {
                        files.add(file.toFile());
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFileFailed(final Path file, final IOException e)
                            throws IOException {
                        if (e != null) {
                            LoggingHelper.log(listener, "Failed to visit file '%s'. Error: %s.",
                                    file.toString(), e.getMessage());
                            LoggingHelper.log(listener, e);
                            throw e;
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    }

    return files;
}

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 {/* www  . j a v  a 2 s .c  o m*/
            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: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;
        }//  ww w .j  a  v a  2  s  .c o 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   www  . j  a  va 2  s  .co 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 {/* w w w. j a  v a2  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);
    }
}

From source file:com.gitpitch.services.DiskService.java

public void copyDirectory(Path source, Path dest) {

    log.debug("copyDirectory: source={}, dest={}", source, dest);

    try {/* w w w.  j  a  v a  2 s.com*/

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

            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

                Path relative = source.relativize(dir);
                Path visitPath = Paths.get(dest.toString(), relative.toString());
                ensure(visitPath);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                Path copyTarget = Paths.get(dest.toString(), source.relativize(file).toString());
                if (!file.getFileName().toString().matches("\\..*")
                        && !copyTarget.getFileName().toString().matches("\\..*")) {
                    Files.copy(file, copyTarget);
                }
                return FileVisitResult.CONTINUE;
            }
        });

    } catch (Exception cex) {
        log.warn("copyDirectory: source={}, dest={}, ex={}", source, dest, cex);
    }
}

From source file:io.anserini.index.IndexClueWeb09b.java

static List<Path> discoverWarcFiles(Path p) {

    final List<Path> warcFiles = new ArrayList<>();

    FileVisitor<Path> fv = new SimpleFileVisitor<Path>() {
        @Override// w w  w  .  ja  v  a2  s.c o  m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

            Path name = file.getFileName();
            if (name != null && matcher.matches(name))
                warcFiles.add(file);
            return FileVisitResult.CONTINUE;
        }
    };

    try {
        Files.walkFileTree(p, fv);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return warcFiles;
}

From source file:sadl.modellearner.rtiplus.SimplePDRTALearner.java

private Path initStepsDir(String dir) throws IOException {

    if (dir != null) {
        final Path p = Paths.get(dir, "steps");
        if (Files.exists(directory) && Files.isDirectory(directory)) {
            Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
                @Override//from  w ww . j ava  2  s.  co m
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path d, IOException e) throws IOException {
                    if (e == null) {
                        Files.delete(d);
                        return FileVisitResult.CONTINUE;
                    } else {
                        throw e;
                    }
                }
            });
        }
        Files.createDirectories(directory);
        return p;
    } else {
        return null;
    }
}

From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java

private ArrayList<BuildInfo> loadBuildInfo(ServletContext servletContext) {
    final ArrayList<BuildInfo> res = new ArrayList<>();
    res.add(BuildInfo.readBuildInfo("au.edu.uq.cmm", "aclslib"));
    res.add(BuildInfo.readBuildInfo("au.edu.uq.cmm", "eccles"));
    try {//from  w  w w  . ja v a 2s  .  co  m
        Path start = FileSystems.getDefault().getPath(servletContext.getRealPath("/META-INF/maven"));
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().equals("pom.properties")) {
                    try (InputStream is = new FileInputStream(file.toFile())) {
                        res.add(BuildInfo.readBuildInfo(is));
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException ex) {
        LOG.error("Problem loading build info");
    }
    return res;
}