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:org.nuxeo.ecm.jsf2.migration.MigrationToJSF2.java

/**
 * @param args Path to the directory to analyze.
 *//*from   w  ww.ja  v a 2  s . co 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.curecomp.primefaces.migrator.PrimefacesMigration.java

public static void main(String[] args) throws Exception {
    // Let's use some colors :)
    //        AnsiConsole.systemInstall();
    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = null;//  w  ww .j  a v  a  2s  .com
    try {
        cli = cliParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        printHelp();
    }
    if (!cli.hasOption("s")) {
        printHelp();
    }

    String sourcePattern;
    if (cli.hasOption("p")) {
        sourcePattern = cli.getOptionValue("p");
    } else {
        sourcePattern = DEFAULT_SOURCE_PATTERN;
    }

    String defaultAnswer;
    if (cli.hasOption("default-answer")) {
        defaultAnswer = cli.getOptionValue("default-answer");
    } else {
        defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER;
    }

    boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y");
    boolean quiet = cli.hasOption("q");
    boolean testWrite = cli.hasOption("t");
    Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath();
    // Since we use IO we will have some blocking threads hanging around
    int threadCount = Runtime.getRuntime().availableProcessors() * 2;
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
    BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();

    findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> {
        // We can't really find usages of widget vars that use EL expressions :(
        if (widgetVarLocation.widgetVar.contains("#")) {
            unusedOrAmbiguous.add(widgetVarLocation);
            return;
        }

        try {
            FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern,
                    sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> {
                        findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages,
                                unusedOrAmbiguous);
                        return null;
                    })));

            Files.walkFileTree(sourceDirectory, visitor);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    awaitAll(futures);

    new TreeSet<>(skippedUsages).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col "
                + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'");
        System.out.println("\t" + previous);
    });

    Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>();

    new TreeSet<>(foundUsages).forEach(widgetUsage -> {
        WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null);
        List<WidgetVarLocation> writtenList = written.get(key);
        int existing = writtenList == null ? 0 : writtenList.size();
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED)
                .a("PF('" + widgetUsage.widgetVar + "')").reset().toString());
        System.out
                .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + next);
        System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: ");

        String input;

        if (quiet) {
            input = "";
            System.out.println();
        } else {
            try {
                do {
                    input = in.readLine();
                } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input)
                        && !"n".equalsIgnoreCase(input));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        if (input == null) {
            System.out.println("Aborted!");
        } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) {
            System.out.println("Replaced!");
            System.out.print("\t");
            if (writtenList == null) {
                writtenList = new ArrayList<>();
                written.put(key, writtenList);
            }

            writtenList.add(widgetUsage);
            List<String> lines;
            try {
                lines = Files.readAllLines(widgetUsage.location);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            try (OutputStream os = testWrite ? new ByteArrayOutputStream()
                    : Files.newOutputStream(widgetUsage.location);
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
                String line;

                for (int i = 0; i < lines.size(); i++) {
                    int lineNr = i + 1;
                    line = lines.get(i);

                    if (lineNr == widgetUsage.lineNr) {
                        int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6);
                        int end = begin + widgetUsage.widgetVar.length();
                        String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')",
                                false);

                        if (testWrite) {
                            System.out.println(newLine);
                        } else {
                            pw.println(newLine);
                        }
                    } else {
                        if (!testWrite) {
                            pw.println(line);
                        }
                    }
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            System.out.println("Skipped!");
        }
    });

    new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr
                + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + previous);
    });

    threadPool.shutdown();
}

From source file:com.netease.hearttouch.hthotfix.patch.PatchSoHelper.java

/**
 * ??so?hash//from  w ww  . j  a va2 s .  c om
 * @param project
 * @param soDir
 */
public static void hashSoFiles(final Project project, ArrayList<String> soDir) {
    final HashMap<String, String> hashMap = new HashMap<>();
    final String projectDir = project.getProjectDir().toString();

    try {
        for (String dirPath : soDir) {
            File dir = new File(dirPath);
            if (!dir.exists())
                continue;
            Files.walkFileTree(dir.toPath(), new SopathVisitor() {
                @Override
                protected void visitSo(Path path, byte[] bytecode) {
                    String soFilePath = path.toString();
                    soFilePath = soFilePath.replace(projectDir, "");
                    String sha1Hex = DigestUtils.shaHex(bytecode);
                    hashMap.put(soFilePath, sha1Hex);
                }
            });
        }

        if (!hashMap.isEmpty()) {
            isSoExist = true;

            HashFileHelper.generate(hashMap, Constants.getHotfixPath(project, Constants.HOTFIX_SO_HASH),
                    project.getLogger(), "PatchSoHelper generate error");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

static public void deleteRecursively(final Path path) throws IOException {
    if (!Files.exists(path)) {
        return;// w  w  w  .  j av  a 2  s. c o  m
    }

    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.wavemaker.commons.util.WMFileUtils.java

public static Collection<String> findMatchedRelativePaths(String pattern, String basePath) {
    FilePatternMatchVisitor filePatternMatchVisitor = new FilePatternMatchVisitor(pattern, basePath);
    try {//from   w  ww . j  a  v  a2s  .  c  o m
        Files.walkFileTree(Paths.get(basePath), filePatternMatchVisitor);
        Collection<Path> matchedFiles = filePatternMatchVisitor.getMatchedPaths();
        List<String> matchedFilePaths = new ArrayList<>(matchedFiles.size());
        for (Path path : matchedFiles) {
            matchedFilePaths.add(path.toString());
        }
        return matchedFilePaths;
    } catch (IOException e) {
        throw new WMRuntimeException("Failed to find matched ignore patterns for " + pattern, e);
    }
}

From source file:org.apdplat.superword.tools.JavaCodeAnalyzer.java

public static Map<String, AtomicInteger> parseDir(String dir) {
    LOGGER.info("?" + dir);
    Map<String, AtomicInteger> data = new HashMap<>();
    try {//w  w  w . j a va2 s.c  o  m
        Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Map<String, AtomicInteger> r = parseFile(file.toFile().getAbsolutePath());
                r.keySet().forEach(k -> {
                    data.putIfAbsent(k, new AtomicInteger());
                    data.get(k).addAndGet(r.get(k).get());
                });
                r.clear();
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        LOGGER.error("?", e);
    }
    return data;
}

From source file:com.excelsiorjet.api.util.Utils.java

public static void cleanDirectory(File f) throws IOException {
    Files.walkFileTree(f.toPath(), new FileVisitor<Path>() {
        @Override/*w w w  . ja  v  a2 s .  c om*/
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return FileVisitResult.CONTINUE;
        }

        private void deleteFile(File f) throws IOException {
            if (!f.delete()) {
                if (f.exists()) {
                    throw new IOException(Txt.s("JetApi.UnableToDelete.Error", f.getAbsolutePath()));
                }
            }
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            deleteFile(file.toFile());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            if (file.toFile().exists()) {
                throw new IOException(Txt.s("JetApi.UnableToDelete.Error", f.getAbsolutePath()));
            }
            return FileVisitResult.CONTINUE;
        }

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

From source file:org.sonarsource.commandlinezip.ZipUtils7.java

public static void zipDir(final Path srcDir, Path zip) throws IOException {

    try (final OutputStream out = FileUtils.openOutputStream(zip.toFile());
            final ZipOutputStream zout = new ZipOutputStream(out)) {
        Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
            @Override//from www. j  av  a  2  s.  co m
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try (InputStream in = new BufferedInputStream(new FileInputStream(file.toFile()))) {
                    String entryName = srcDir.relativize(file).toString();
                    ZipEntry entry = new ZipEntry(entryName);
                    zout.putNextEntry(entry);
                    IOUtils.copy(in, zout);
                    zout.closeEntry();
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (dir.equals(srcDir)) {
                    return FileVisitResult.CONTINUE;
                }

                String entryName = srcDir.relativize(dir).toString();
                ZipEntry entry = new ZipEntry(entryName);
                zout.putNextEntry(entry);
                zout.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

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

public static List<String> findAdditionalRulesets(Path basePath) {
    try {/*  w ww .j a  va2  s  .  co  m*/
        List<String> additionalRulesets = new ArrayList<>();
        Pattern rulesetPattern = Pattern.compile("^.+" + Pattern.quote(File.separator) + "pmd-\\w+"
                + Pattern.quote(FilenameUtils.normalize("/src/main/resources/rulesets/")) + "\\w+"
                + Pattern.quote(File.separator) + "\\w+.xml$");
        Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (rulesetPattern.matcher(file.toString()).matches()) {
                    additionalRulesets.add(file.toString());
                }

                return FileVisitResult.CONTINUE;
            }
        });
        return additionalRulesets;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.yqboots.fss.util.ZipUtils.java

/**
 * Compresses the specified directory to a zip file
 *
 * @param dir the directory to compress/*from   ww  w. j av  a 2s .  co m*/
 * @return the compressed file
 * @throws IOException
 */
public static Path compress(Path dir) throws IOException {
    Assert.isTrue(Files.exists(dir), "The directory does not exist: " + dir.toAbsolutePath());
    Assert.isTrue(Files.isDirectory(dir), "Should be a directory: " + dir.toAbsolutePath());

    Path result = Paths.get(dir.toAbsolutePath() + FileType.DOT_ZIP);
    try (final ZipOutputStream out = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(result.toFile())))) {
        // out.setMethod(ZipOutputStream.DEFLATED);
        final byte data[] = new byte[BUFFER];
        // get a list of files from current directory
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs)
                    throws IOException {
                final File file = path.toFile();

                // compress to relative directory, not absolute
                final String root = StringUtils.substringAfter(file.getParent(), dir.toString());
                try (final BufferedInputStream origin = new BufferedInputStream(new FileInputStream(file),
                        BUFFER)) {
                    final ZipEntry entry = new ZipEntry(root + File.separator + path.getFileName());
                    out.putNextEntry(entry);
                    int count;
                    while ((count = origin.read(data, 0, BUFFER)) != -1) {
                        out.write(data, 0, count);
                    }
                }

                return FileVisitResult.CONTINUE;
            }
        });
    }

    return result;
}