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:com.datazuul.iiif.presentation.api.ManifestGenerator.java

public static void main(String[] args)
        throws ParseException, JsonProcessingException, IOException, URISyntaxException {
    Options options = new Options();
    options.addOption("d", true, "Absolute file path to the directory containing the image files.");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("d")) {
        String imageDirectoryPath = cmd.getOptionValue("d");
        Path imageDirectory = Paths.get(imageDirectoryPath);
        final List<Path> files = new ArrayList<>();
        try {/*from   w  ww  .j a  v  a2 s.co m*/
            Files.walkFileTree(imageDirectory, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (!attrs.isDirectory()) {
                        // TODO there must be a more elegant solution for filtering jpeg files...
                        if (file.getFileName().toString().endsWith("jpg")) {
                            files.add(file);
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.sort(files, new Comparator() {
            @Override
            public int compare(Object fileOne, Object fileTwo) {
                String filename1 = ((Path) fileOne).getFileName().toString();
                String filename2 = ((Path) fileTwo).getFileName().toString();

                try {
                    // numerical sorting
                    Integer number1 = Integer.parseInt(filename1.substring(0, filename1.lastIndexOf(".")));
                    Integer number2 = Integer.parseInt(filename2.substring(0, filename2.lastIndexOf(".")));
                    return number1.compareTo(number2);
                } catch (NumberFormatException nfe) {
                    // alpha-numerical sorting
                    return filename1.compareToIgnoreCase(filename2);
                }
            }
        });

        generateManifest(imageDirectory.getFileName().toString(), files);
    } else {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ManifestGenerator", options);
    }
}

From source file:mcnutty.music.get.MusicGet.java

public static void main(String[] args) throws Exception {

    //print out music-get
    System.out.println("                     _                      _   ");
    System.out.println(" _ __ ___  _   _ ___(_) ___       __ _  ___| |_ ");
    System.out.println("| '_ ` _ \\| | | / __| |/ __|____ / _` |/ _ \\ __|");
    System.out.println("| | | | | | |_| \\__ \\ | (_|_____| (_| |  __/ |_ ");
    System.out.println("|_| |_| |_|\\__,_|___/_|\\___|     \\__, |\\___|\\__|");
    System.out.println("                                 |___/          \n");

    //these will always be initialised later (but the compiler doesn't know that)
    String directory = "";
    Properties prop = new Properties();

    try (InputStream input = new FileInputStream("config.properties")) {
        prop.load(input);//from w  w  w . ja  v a2  s . c  om
        if (prop.getProperty("directory") != null) {
            directory = prop.getProperty("directory");
        } else {
            System.out.println(
                    "Error reading config property 'directory' - using default value of /tmp/musicserver/\n");
            directory = "/tmp/musicserver/";
        }
        if (prop.getProperty("password") == null) {
            System.out.println("Error reading config property 'password' - no default value, exiting\n");
            System.exit(1);
        }
    } catch (IOException e) {
        System.out.println("Error reading config file");
        System.exit(1);
    }

    //create a queue object
    ProcessQueue process_queue = new ProcessQueue();

    try {
        if (args.length > 0 && args[0].equals("clean")) {
            Files.delete(Paths.get("queue.json"));
        }
        //load an existing queue if possible
        String raw_queue = Files.readAllLines(Paths.get("queue.json")).toString();
        JSONArray queue_state = new JSONArray(raw_queue);
        ConcurrentLinkedQueue<QueueItem> loaded_queue = new ConcurrentLinkedQueue<>();
        JSONArray queue = queue_state.getJSONArray(0);
        for (int i = 0; i < queue.length(); i++) {
            JSONObject item = ((JSONObject) queue.get(i));
            QueueItem loaded_item = new QueueItem();
            loaded_item.ip = item.getString("ip");
            loaded_item.real_name = item.getString("name");
            loaded_item.disk_name = item.getString("guid");
            loaded_queue.add(loaded_item);
        }
        process_queue.bucket_queue = loaded_queue;
        System.out.println("Loaded queue from disk\n");
    } catch (Exception ex) {
        //otherwise clean out the music directory and start a new queue
        try {
            Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }
            });
            Files.delete(Paths.get(directory));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Files.createDirectory(Paths.get(directory));
        System.out.println("Created a new queue\n");
    }

    //start the web server
    StartServer start_server = new StartServer(process_queue, directory);
    new Thread(start_server).start();

    //wit for the web server to spool up
    Thread.sleep(1000);

    //read items from the queue and play them
    while (true) {
        QueueItem next_item = process_queue.next_item();
        if (!next_item.equals(new QueueItem())) {
            //Check the timeout
            int timeout = 547;
            try (FileInputStream input = new FileInputStream("config.properties")) {
                prop.load(input);
                timeout = Integer.parseInt(prop.getProperty("timeout", "547"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Playing " + next_item.real_name);
            process_queue.set_played(next_item);
            process_queue.save_queue();
            Process p = Runtime.getRuntime().exec("timeout " + timeout
                    + "s mplayer -fs -quiet -af volnorm=2:0.25 " + directory + next_item.disk_name);

            try {
                p.waitFor(timeout, TimeUnit.SECONDS);
                Files.delete(Paths.get(directory + next_item.disk_name));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            process_queue.bucket_played.clear();
        }
        Thread.sleep(1000);
    }
}

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

/**
 * @param args Path to the directory to analyze.
 *///  w  w w. j a  v a 2s . com
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.github.houbin217jz.thumbnail.Thumbnail.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("s", "src", true,
            "????????????");
    options.addOption("d", "dst", true, "");
    options.addOption("r", "ratio", true, "/??, 30%???0.3????????");
    options.addOption("w", "width", true, "(px)");
    options.addOption("h", "height", true, "?(px)");
    options.addOption("R", "recursive", false, "???????");

    HelpFormatter formatter = new HelpFormatter();
    String formatstr = "java -jar thumbnail.jar " + "[-s/--src <path>] " + "[-d/--dst <path>] "
            + "[-r/--ratio double] " + "[-w/--width integer] " + "[-h/--height integer] " + "[-R/--recursive] ";

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*  www .  j  a  va  2 s .c  o  m*/
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        formatter.printHelp(formatstr, options);
        return;
    }

    final Path srcDir, dstDir;
    final Integer width, height;
    final Double ratio;

    //
    if (cmd.hasOption("s")) {
        srcDir = Paths.get(cmd.getOptionValue("s")).toAbsolutePath();
    } else {
        srcDir = Paths.get("").toAbsolutePath(); //??
    }

    //
    if (cmd.hasOption("d")) {
        dstDir = Paths.get(cmd.getOptionValue("d")).toAbsolutePath();
    } else {
        formatter.printHelp(formatstr, options);
        return;
    }

    if (!Files.exists(srcDir, LinkOption.NOFOLLOW_LINKS)
            || !Files.isDirectory(srcDir, LinkOption.NOFOLLOW_LINKS)) {
        System.out.println("[" + srcDir.toAbsolutePath() + "]??????");
        return;
    }

    if (Files.exists(dstDir, LinkOption.NOFOLLOW_LINKS)) {
        if (!Files.isDirectory(dstDir, LinkOption.NOFOLLOW_LINKS)) {
            //????????
            System.out.println("????????");
            return;
        }
    } else {
        //????????
        try {
            Files.createDirectories(dstDir);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    //??
    if (cmd.hasOption("w") && cmd.hasOption("h")) {
        try {
            width = Integer.valueOf(cmd.getOptionValue("width"));
            height = Integer.valueOf(cmd.getOptionValue("height"));
        } catch (NumberFormatException e) {
            System.out.println("??????");
            return;
        }
    } else {
        width = null;
        height = null;
    }

    //?
    if (cmd.hasOption("r")) {
        try {
            ratio = Double.valueOf(cmd.getOptionValue("r"));
        } catch (NumberFormatException e) {
            System.out.println("?????");
            return;
        }
    } else {
        ratio = null;
    }

    if (width != null && ratio != null) {
        System.out.println("??????????????");
        return;
    }

    if (width == null && ratio == null) {
        System.out.println("????????????");
        return;
    }

    //
    int maxDepth = 1;
    if (cmd.hasOption("R")) {
        maxDepth = Integer.MAX_VALUE;
    }

    try {
        //Java 7 ??@see http://docs.oracle.com/javase/jp/7/api/java/nio/file/Files.html
        Files.walkFileTree(srcDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                            throws IOException {

                        //???&???
                        String filename = path.getFileName().toString().toLowerCase();

                        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
                            //Jpeg??

                            /*
                             * relative??:
                             * rootPath: /a/b/c/d
                             * filePath: /a/b/c/d/e/f.jpg
                             * rootPath.relativize(filePath) = e/f.jpg
                             */

                            /*
                             * resolve??
                             * rootPath: /a/b/c/output
                             * relativePath: e/f.jpg
                             * rootPath.resolve(relativePath) = /a/b/c/output/e/f.jpg
                             */

                            Path dst = dstDir.resolve(srcDir.relativize(path));

                            if (!Files.exists(dst.getParent(), LinkOption.NOFOLLOW_LINKS)) {
                                Files.createDirectories(dst.getParent());
                            }
                            doResize(path.toFile(), dst.toFile(), width, height, ratio);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    } 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;/*from  w w  w  . java  2 s .  co 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:org.apdplat.superword.tools.JavaCodeAnalyzer.java

public static Map<String, AtomicInteger> parseDir(String dir) {
    LOGGER.info("?" + dir);
    Map<String, AtomicInteger> data = new HashMap<>();
    try {//from  ww  w.  j a  va  2 s .  co  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: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  ww w. ja  va 2 s .  com
            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  w w  .j a  v  a2  s.  c o 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. ja  va2 s .com*/
 * @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;
}

From source file:com.yahoo.rdl.maven.RdlFileFinderImpl.java

@Override
public List<Path> findRdlFiles() throws MojoExecutionException, MojoFailureException {
    List<Path> rdlFiles = new ArrayList<Path>();
    try {//  w  w w. j av a2  s.  c  om
        Files.walkFileTree(rdlDirectory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (FilenameUtils.isExtension(file.toString(), "rdl")) {
                    rdlFiles.add(file);
                }
                return super.visitFile(file, attrs);
            }
        });
    } catch (IOException e) {
        throw new MojoExecutionException("Error walking " + rdlDirectory.toAbsolutePath(), e);
    }
    if (rdlFiles.isEmpty()) {
        throw new MojoFailureException("No files ending in .rdl were found in the directory "
                + rdlDirectory.toAbsolutePath()
                + ". Assign <rdlDirectory> in the configuration of rdl-maven-plugin to a folder containing your rdl files.");
    }
    return rdlFiles;
}