Example usage for java.nio.file FileVisitResult SKIP_SUBTREE

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

Introduction

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

Prototype

FileVisitResult SKIP_SUBTREE

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

Click Source Link

Document

Continue without visiting the entries in this directory.

Usage

From source file:org.nuxeo.ecm.jsf2.migration.MigrationToJSF2.java

/**
 * @param args Path to the directory to analyze.
 *//* www .  jav a2s  .c o  m*/
public static void main(String[] args) throws Exception {

    // Parse command line
    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    options.addOption(Flags.MIGRATE);
    options.addOption(Flags.FORMAT);
    options.addOption(Flags.RECURSIVE);

    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.getArgs().length != 1) {
            throw new ParseException("Must specify project directory.");
        }
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        System.out.println(e.getMessage());
        formatter.printHelp("java -jar nuxeo-jsf2-migration-<version>.jar <path to project>", options);
        System.exit(-1);
    }

    // Get the parameters
    String path = cmd.getArgs()[0];
    final boolean migration = cmd.hasOption(Flags.MIGRATE.getOpt());
    final boolean format = cmd.hasOption(Flags.FORMAT.getOpt());
    boolean recursive = cmd.hasOption(Flags.RECURSIVE.getOpt());

    File file = new File(path);

    // Check if the file exists
    if (!file.exists()) {
        System.out.println("The file does not exist");
        return;
    }
    final boolean isDirectory = file.isDirectory();
    if (recursive && !isDirectory) {
        System.out.println("The file is not a directory");
        return;
    }
    if (!isDirectory) {
        if (!isValidXHTMLFile(path)) {
            System.out.println("The specified file is not xhtml file.");
            return;
        }
        processSingleXHTMLFile(file, migration, format);
    } else if (!recursive) {
        if (!isValidProjectDirectory(path)) {
            System.out.println("The specified directory is not a valid project directory.");
            return;
        }
        processDirectory(file.getAbsolutePath(), migration, format);
    } else {
        Path startingDir = Paths.get(path);
        Files.walkFileTree(startingDir, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return processDirectory(dir.toFile().getPath(), migration, format)
                        ? FileVisitResult.SKIP_SUBTREE
                        : FileVisitResult.CONTINUE;
            }
        });
    }
}

From source file:com.fizzed.stork.deploy.DeployHelper.java

static public void deleteRecursively(final Path path) throws IOException {
    if (!Files.exists(path)) {
        return;/*from ww  w.j a  va2  s.com*/
    }

    log.info("Deleting local {}", path);

    Files.walkFileTree(path, 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 ioe) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

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

    Files.deleteIfExists(path);
}

From source file:com.ejisto.util.visitor.ConditionMatchingCopyFileVisitor.java

@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
    if (options.srcRoot.compareTo(dir) < 0
            && options.copyType == CopyType.INCLUDE_ONLY_ROOT_MATCHING_RESOURCES) {
        return FileVisitResult.SKIP_SUBTREE;
    }/*from  w w w .j a  v  a 2  s .  c om*/
    Path dest = options.targetRoot.resolve(options.srcRoot.relativize(dir));
    if (!Files.exists(dest)) {
        Files.createDirectories(dest);
    }
    return FileVisitResult.CONTINUE;
}

From source file:ch.bender.evacuate.Helper.java

/**
 * Deletes a whole directory (recursively)
 * <p>//from ww  w . ja  v  a  2s  . c  o  m
 * @param aDir
 *        a folder to be deleted (must not be null)
 * @throws IOException
 */
public static void deleteDirRecursive(Path aDir) throws IOException {
    if (aDir == null) {
        throw new IllegalArgumentException("aDir must not be null");
    }

    if (Files.notExists(aDir)) {
        return;
    }

    if (!Files.isDirectory(aDir)) {
        throw new IllegalArgumentException("given aDir is not a directory");
    }

    Files.walkFileTree(aDir, new SimpleFileVisitor<Path>() {
        /**
         * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException)
         */
        @Override
        public FileVisitResult visitFileFailed(Path aFile, IOException aExc) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName().toString()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            throw aExc;
        }

        /**
         * @see java.nio.file.SimpleFileVisitor#preVisitDirectory(java.lang.Object, java.nio.file.attribute.BasicFileAttributes)
         */
        @Override
        public FileVisitResult preVisitDirectory(Path aFile, BasicFileAttributes aAttrs) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            return FileVisitResult.CONTINUE;
        }

        @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 {
            if (dir.isAbsolute() && dir.getRoot().equals(dir)) {
                myLog.debug("root cannot be deleted: " + dir.toString());
                return FileVisitResult.CONTINUE;
            }

            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

    });
}

From source file:de.fatalix.book.importer.CalibriImporter.java

public static void processBooks(Path root, String solrURL, String solrCore, final int batchSize)
        throws IOException, SolrServerException {
    final SolrServer solrServer = SolrHandler.createConnection(solrURL, solrCore);
    final List<BookEntry> bookEntries = new ArrayList<>();
    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

        @Override//from  w ww.java  2  s . co  m
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if (dir.toString().contains("__MACOSX")) {
                return FileVisitResult.SKIP_SUBTREE;
            }
            try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir)) {
                BookEntry bookEntry = new BookEntry().setUploader("admin");
                for (Path path : directoryStream) {
                    if (!Files.isDirectory(path)) {
                        if (path.toString().contains(".opf")) {
                            bookEntry = parseOPF(path, bookEntry);
                        }
                        if (path.toString().contains(".mobi")) {
                            bookEntry.setMobi(Files.readAllBytes(path)).setMimeType("MOBI");
                        }
                        if (path.toString().contains(".epub")) {
                            bookEntry.setEpub(Files.readAllBytes(path));
                        }
                        if (path.toString().contains(".jpg")) {
                            bookEntry.setCover(Files.readAllBytes(path));
                            ByteArrayOutputStream output = new ByteArrayOutputStream();
                            Thumbnails.of(new ByteArrayInputStream(bookEntry.getCover())).size(130, 200)
                                    .toOutputStream(output);
                            bookEntry.setThumbnail(output.toByteArray());
                            bookEntry.setThumbnailGenerated("done");
                        }
                    }
                }
                if (bookEntry.getMobi() != null || bookEntry.getEpub() != null) {
                    bookEntries.add(bookEntry);
                    if (bookEntries.size() > batchSize) {
                        System.out.println("Adding " + bookEntries.size() + " Books...");
                        try {
                            SolrHandler.addBeans(solrServer, bookEntries);
                        } catch (SolrServerException ex) {
                            System.out.println(ex.getMessage());
                            ex.printStackTrace();
                        }
                        bookEntries.clear();
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return super.preVisitDirectory(dir, attrs);
        }
    });
}

From source file:de.fatalix.bookery.bl.background.importer.CalibriImporter.java

private void processArchive(final Path zipFile, final int batchSize) throws IOException {
    try (FileSystem zipFileSystem = FileSystems.newFileSystem(zipFile, null)) {
        final List<BookEntry> bookEntries = new ArrayList<>();
        Path root = zipFileSystem.getPath("/");
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

            @Override/* w w  w  .j  a  va  2  s.c  om*/
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (dir.toString().contains("__MACOSX")) {
                    return FileVisitResult.SKIP_SUBTREE;
                }
                try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir)) {
                    BookEntry bookEntry = new BookEntry().setUploader("admin");
                    for (Path path : directoryStream) {
                        if (!Files.isDirectory(path)) {
                            if (path.toString().contains(".opf")) {
                                bookEntry = parseOPF(path, bookEntry);
                            }
                            if (path.toString().contains(".mobi")) {
                                bookEntry.setMobi(Files.readAllBytes(path)).setMimeType("MOBI");
                            }
                            if (path.toString().contains(".epub")) {
                                bookEntry.setEpub(Files.readAllBytes(path));
                            }
                            if (path.toString().contains(".jpg")) {
                                bookEntry.setCover(Files.readAllBytes(path));
                                ByteArrayOutputStream output = new ByteArrayOutputStream();
                                Thumbnails.of(new ByteArrayInputStream(bookEntry.getCover())).size(130, 200)
                                        .toOutputStream(output);
                                bookEntry.setThumbnail(output.toByteArray());
                                bookEntry.setThumbnailGenerated("done");
                            }
                        }
                    }
                    if (bookEntry.getMobi() != null || bookEntry.getEpub() != null) {
                        bookEntries.add(bookEntry);
                        if (bookEntries.size() > batchSize) {
                            logger.info("Adding " + bookEntries.size() + " Books...");
                            try {
                                solrHandler.addBeans(bookEntries);
                            } catch (SolrServerException ex) {
                                logger.error(ex, ex);
                            }
                            bookEntries.clear();
                        }
                    }
                } catch (IOException ex) {
                    logger.error(ex, ex);
                }
                return super.preVisitDirectory(dir, attrs);
            }
        });
        try {
            if (!bookEntries.isEmpty()) {
                logger.info("Adding " + bookEntries.size() + " Books...");
                solrHandler.addBeans(bookEntries);
            }
        } catch (SolrServerException ex) {
            logger.error(ex, ex);
        }
    } finally {
        Files.delete(zipFile);
    }
}

From source file:se.trixon.mapollage.FileVisitor.java

@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
    if (mExcludePatterns != null) {
        for (String excludePattern : mExcludePatterns) {
            if (IOCase.SYSTEM.isCaseSensitive()) {
                if (StringUtils.contains(dir.toString(), excludePattern)) {
                    return FileVisitResult.SKIP_SUBTREE;
                }//from  ww w.  j  av a  2  s  .  c  o  m
            } else {
                if (StringUtils.containsIgnoreCase(dir.toString(), excludePattern)) {
                    return FileVisitResult.SKIP_SUBTREE;
                }
            }
        }
    }

    String[] filePaths = dir.toFile().list();

    mOperationListener.onOperationLog(dir.toString());
    mOperationListener.onOperationProgress(dir.toString());

    if (filePaths != null && filePaths.length > 0) {
        if (mUseExternalDescription) {
            Properties p = new Properties(mDefaultDescProperties);

            try {
                File file = new File(dir.toFile(), mExternalFileValue);
                if (file.isFile()) {
                    p.load(new InputStreamReader(new FileInputStream(file), Charset.defaultCharset()));
                }
            } catch (IOException ex) {
                // nvm
            }

            mDirToDesc.put(dir.toFile().getAbsolutePath(), p);
        }

        for (String fileName : filePaths) {
            try {
                TimeUnit.NANOSECONDS.sleep(1);
            } catch (InterruptedException ex) {
                mInterrupted = true;
                return FileVisitResult.TERMINATE;
            }
            File file = new File(dir.toFile(), fileName);
            if (file.isFile() && mPathMatcher.matches(file.toPath().getFileName())) {
                boolean exclude = false;
                if (mExcludePatterns != null) {
                    for (String excludePattern : mExcludePatterns) {
                        if (StringUtils.contains(file.getAbsolutePath(), excludePattern)) {
                            exclude = true;
                            break;
                        }
                    }
                }

                if (!exclude) {
                    mFiles.add(file);
                }
            }
        }
    }

    return FileVisitResult.CONTINUE;
}

From source file:org.schedulesdirect.grabber.Auditor.java

private void auditScheds() throws IOException, JSONException, ParseException {
    final Map<String, JSONObject> stations = getStationMap();
    final SimpleDateFormat FMT = Config.get().getDateTimeFormat();
    final Path scheds = vfs.getPath("schedules");
    if (Files.isDirectory(scheds)) {
        Files.walkFileTree(scheds, new FileVisitor<Path>() {

            @Override//from  w w  w .j  a v a  2 s .c o  m
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return dir.equals(scheds) ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                boolean failed = false;
                String id = getStationIdFromFileName(file.getFileName().toString());
                JSONObject station = stations.get(id);
                StringBuilder msg = new StringBuilder(String.format("Inspecting %s (%s)... ",
                        station != null ? station.getString("callsign") : String.format("[UNKNOWN: %s]", id),
                        id));
                String input;
                try (InputStream ins = Files.newInputStream(file)) {
                    input = IOUtils.toString(ins, ZipEpgClient.ZIP_CHARSET.toString());
                }
                ObjectMapper mapper = Config.get().getObjectMapper();
                JSONArray jarr = mapper.readValue(
                        mapper.readValue(input, JSONObject.class).getJSONArray("programs").toString(),
                        JSONArray.class);
                for (int i = 1; i < jarr.length(); ++i) {
                    long start, prevStart;
                    JSONObject prev;
                    try {
                        start = FMT.parse(jarr.getJSONObject(i).getString("airDateTime")).getTime();
                        prev = jarr.getJSONObject(i - 1);
                        prevStart = FMT.parse(prev.getString("airDateTime")).getTime()
                                + 1000L * prev.getLong("duration");
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                    if (prevStart != start) {
                        msg.append(String.format("FAILED! [%s]", prev.getString("airDateTime")));
                        LOG.error(msg);
                        failed = true;
                        Auditor.this.failed = true;
                        break;
                    }
                }
                if (!failed) {
                    msg.append("PASSED!");
                    LOG.info(msg);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                LOG.error(String.format("Unable to process schedule file '%s'", file), exc);
                Auditor.this.failed = true;
                return FileVisitResult.CONTINUE;
            }

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

        });
    }
}

From source file:com.marklogic.hub.RestAssetLoader.java

/**
 * FileVisitor method that determines if we should visit the directory or not via the fileFilter.
 *///w ww.j  a  v a 2 s.co m
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attributes) throws IOException {
    logger.info("filename: " + path.toFile().getName());
    boolean accept = fileFilter.accept(path.toFile());
    if (accept) {
        if (logger.isDebugEnabled()) {
            logger.debug("Visiting directory: " + path);
        }
        return FileVisitResult.CONTINUE;
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Skipping directory: " + path);
        }
        return FileVisitResult.SKIP_SUBTREE;
    }
}

From source file:ch.bender.evacuate.Runner.java

/**
 * run/*  w w  w. j  a  va  2  s  .  c o  m*/
 * <p>
 * @throws Exception 
 */
public void run() throws Exception {
    checkDirectories();
    initExcludeMatchers();

    myEvacuateCandidates = new TreeMap<>();
    myFailedChainPreparations = Collections.synchronizedMap(new HashMap<>());
    myFutures = new HashSet<>();
    myExclusionDirCount = 0;
    myEvacuationDirCount = 0;
    myExclusionFileCount = 0;
    myEvacuationFileCount = 0;

    Files.walkFileTree(myBackupDir, new SimpleFileVisitor<Path>() {
        /**
         * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException)
         */
        @Override
        public FileVisitResult visitFileFailed(Path aFile, IOException aExc) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName().toString()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            throw aExc;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            return Runner.this.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if ("System Volume Information".equals((dir.getFileName()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            return Runner.this.preVisitDirectory(dir, attrs);
        }

    });

    if (myEvacuateCandidates.size() == 0) {
        myLog.info("No candidates for evacuation found");
    } else {
        StringBuilder sb = new StringBuilder("\nFound candidates for evacuation:");
        myEvacuateCandidates.keySet().forEach(p -> sb.append("\n    " + p.toString()));
        myLog.info(sb.toString());
    }

    if (myDryRun) {
        myLog.debug("DryRun flag is set. Doing nothing");
        return;
    }

    if (myFutures.size() > 0) {
        myLog.debug("Waiting for all async tasks to complete");
        CompletableFuture.allOf(myFutures.toArray(new CompletableFuture[myFutures.size()])).get();
    }

    if (myFailedChainPreparations.size() > 0) {
        for (Path path : myFailedChainPreparations.keySet()) {
            myLog.error("exception occured", myFailedChainPreparations.get(path));
        }

        throw new Exception("chain preparation failed. See above error messages");
    }

    for (Path src : myEvacuateCandidates.keySet()) {
        Path dst = myEvacuateCandidates.get(src);
        Path dstParent = dst.getParent();

        if (Files.notExists(dstParent)) {
            Files.createDirectories(dstParent); // FUTURE: overtake file attributes from src
        }

        if (myMove) {
            try {
                myLog.debug(
                        "Moving file system object \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
            } catch (AtomicMoveNotSupportedException e) {
                myLog.warn("Atomic move not supported. Try copy and then delete");

                if (Files.isDirectory(src)) {
                    myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                    FileUtils.copyDirectory(src.toFile(), dst.toFile());
                    myLog.debug("Delete folder \"" + src.toString() + "\"");
                    FileUtils.deleteDirectory(src.toFile());
                } else {
                    myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                    FileUtils.copyFile(src.toFile(), dst.toFile());
                    myLog.debug("Delete file \"" + src.toString() + "\"");
                    Files.delete(src);
                }
            }

        } else {
            if (Files.isDirectory(src)) {
                myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                FileUtils.copyDirectory(src.toFile(), dst.toFile());
            } else {
                myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                FileUtils.copyFile(src.toFile(), dst.toFile());
            }
        }
    }

    myLog.info("\nSuccessfully terminated." + "\n             Evacuated  Skipped" + "\n    Files  : "
            + StringUtils.leftPad("" + myEvacuationDirCount, 9)
            + StringUtils.leftPad("" + myExclusionDirCount, 9) + "\n    Folders: "
            + StringUtils.leftPad("" + myEvacuationFileCount, 9)
            + StringUtils.leftPad("" + myExclusionFileCount, 9));
}