Example usage for java.nio.file FileVisitor FileVisitor

List of usage examples for java.nio.file FileVisitor FileVisitor

Introduction

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

Prototype

FileVisitor

Source Link

Usage

From source file:neembuu.uploader.zip.generator.NUZipFileGenerator.java

private void walkOverAllFiles() throws IOException {
    for (final Path uploadersDirectory : uploadersDirectories) {
        Files.walkFileTree(uploadersDirectory, new FileVisitor<Path>() {
            @Override/*from w w w  . j  av  a  2 s  . co  m*/
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }

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

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

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().endsWith(".class")) {
                    visitClassFile(file, attrs, uploadersDirectory);
                }
                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   ww w .jav 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:act.installer.pubchem.PubchemTTLMergerTest.java

@After
public void tearDown() throws Exception {
    // Clean up temp dir once the test is complete.  TODO: use mocks instead maybe?  But testing RocksDB helps too...
    /* With help from://from  ww w  .  j  a  v  a2  s.  c o  m
     * http://stackoverflow.com/questions/779519/delete-directories-recursively-in-java/27917071#27917071 */
    Files.walkFileTree(tempDirPath, new FileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            // walkFileTree may ignore . and .., but I have never found it a /bad/ idea to check for these special names.
            if (!THIS_DIR.equals(file.toFile().getName()) && !PARENT_DIR.equals(file.toFile().getName())) {
                Files.delete(file);
            }
            return FileVisitResult.CONTINUE;
        }

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

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

    // One last check to make sure the top level directory is removed.
    if (tempDirPath.toFile().exists()) {
        Files.delete(tempDirPath);
    }
}

From source file:fr.ortolang.diffusion.runtime.engine.task.ImportReferentialEntityTask.java

@Override
public void executeTask(DelegateExecution execution) throws RuntimeEngineTaskException {
    checkParameters(execution);//from  ww w  .  jav  a2s .c  om
    String referentialPathParam = execution.getVariable(REFERENTIAL_PATH_PARAM_NAME, String.class);
    report = new StringBuilder();

    File referentialPathFile = new File(referentialPathParam);
    if (referentialPathFile.exists()) {

        final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.{json}");
        final Path referentialPath = Paths.get(referentialPathParam);
        try {
            Files.walkFileTree(referentialPath, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path filepath, BasicFileAttributes attrs) throws IOException {
                    Path filename = filepath.getFileName();
                    if (filename != null && matcher.matches(filename)) {

                        File jsonFile = filepath.toFile();
                        String content = StreamUtils.getContent(jsonFile);
                        if (content == null) {
                            //                           LOGGER.log(Level.SEVERE, "Referential entity content is empty for file " + jsonFile);
                            report.append(" - referential entity content is empty for file ").append(jsonFile)
                                    .append("\r\n");
                            partial = true;
                            return FileVisitResult.CONTINUE;
                        }

                        String type = extractField(content, "type");
                        if (type == null) {
                            //                           LOGGER.log(Level.SEVERE, "Referential entity type unknown for file " + jsonFile);
                            report.append(" - referential entity type unknown for file ").append(jsonFile)
                                    .append("\r\n");
                            partial = true;
                            return FileVisitResult.CONTINUE;
                        }

                        String name = jsonFile.getName().substring(0, jsonFile.getName().length() - 5);
                        try {
                            boolean exist = exists(name);

                            if (!exist) {
                                createReferentialEntity(name, type, content);
                                report.append(" + referential entity created : ").append(name).append("\r\n");
                            } else {
                                updateReferentialEntity(name, type, content);
                                report.append(" + referential entity updated : ").append(name).append("\r\n");
                            }
                        } catch (RuntimeEngineTaskException e) {
                            //                           LOGGER.log(Level.SEVERE, "  unable to import referential entity ("+type+") named "+name, e);
                            report.append(" - unable to import referential entity '").append(name)
                                    .append("' : ").append(e.getMessage()).append("\r\n");
                            partial = true;
                            return FileVisitResult.CONTINUE;
                        }
                    }
                    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 (Exception e) {
            //            LOGGER.log(Level.SEVERE, "  unable to import referential : " + referentialPathFile, e);
            report.append("Enable to import referential ").append(referentialPathFile).append(" caused by : ")
                    .append(e.getMessage()).append("\r\n");
            partial = true;
        }

    } else {
        //         LOGGER.log(Level.SEVERE, "Referential folder doesn't exists : " + referentialPathFile);
        report.append("Referential folder doesn't exists at ").append(referentialPathFile).append("\r\n");
        partial = true;
    }

    if (partial) {
        throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(),
                "Some entities has not been imported (see trace for detail)"));
    } else {
        throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(),
                "All entities imported succesfully"));
    }
    throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessTraceEvent(execution.getProcessBusinessKey(),
            "Report: \r\n" + report.toString(), null));
}

From source file:spdxedit.SpdxLogic.java

/**
 * Creates a new package with the specified license, name, comment, and root
 * path./*  w w  w.  ja v a2  s.  co  m*/
 *
 * @param pkgRootPath
 *            The path from which the files will be included into the
 *            package. If absent, creates a "remote" package, i.e. one
 *            without files, just referencing a remote dependency.
 * @param name
 * @param omitHiddenFiles
 * @param declaredLicense
 * @param downloadLocation
 * @return
 */
public static SpdxPackage createSpdxPackageForPath(Optional<Path> pkgRootPath, AnyLicenseInfo declaredLicense,
        String name, String downloadLocation, final boolean omitHiddenFiles) {
    Objects.requireNonNull(pkgRootPath);
    try {

        SpdxPackage pkg = new SpdxPackage(name, declaredLicense,
                new AnyLicenseInfo[] {} /* Licences from files */, null /* Declared licenses */,
                declaredLicense, downloadLocation, new SpdxFile[] {} /* Files */,
                new SpdxPackageVerificationCode(null, new String[] {}));
        pkg.setLicenseInfosFromFiles(new AnyLicenseInfo[] { new SpdxNoAssertionLicense() });
        pkg.setCopyrightText("NOASSERTION");

        if (pkgRootPath.isPresent()) {
            // Add files in path
            List<SpdxFile> addedFiles = new LinkedList<>();
            String baseUri = pkgRootPath.get().toUri().toString();
            FileVisitor<Path> fileVisitor = new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (omitHiddenFiles && dir.getFileName().toString().startsWith(".")) {
                        return FileVisitResult.SKIP_SUBTREE;
                    } else
                        return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    // Skip if omitHidden is set and this file is hidden.
                    if (omitHiddenFiles
                            && (file.getFileName().toString().startsWith(".") || Files.isHidden(file)))
                        return FileVisitResult.CONTINUE;
                    try {
                        SpdxFile addedFile = newSpdxFile(file, baseUri);
                        addedFiles.add(addedFile);
                    } catch (InvalidSPDXAnalysisException e) {
                        throw new RuntimeException(e);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    logger.error("Unable to add file ", file.toAbsolutePath().toString());
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }
            };
            Files.walkFileTree(pkgRootPath.get(), fileVisitor);
            SpdxFile[] files = addedFiles.stream().toArray(size -> new SpdxFile[size]);
            pkg.setFiles(files);
            recomputeVerificationCode(pkg);
        } else {
            //External package
            pkg.setFilesAnalyzed(false);
            pkg.setPackageVerificationCode(null);
        }
        return pkg;
    } catch (InvalidSPDXAnalysisException | IOException e) {
        throw new RuntimeException(e);
    }
}

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

private void copy(Path localPath, String workspace, String remotePath) {
    try {//from w  ww . j a  v a  2  s . c  o  m
        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:fr.ortolang.diffusion.client.cmd.CheckBagCommand.java

private void checkSnapshotMetadata(Path root) {
    Path metadata = Paths.get(root.toString(), "metadata");
    try {/*from  w w w  . j  a  v a  2  s . co  m*/
        Files.walkFileTree(metadata, new FileVisitor<Path>() {

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

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path target = Paths.get(root.toString(), "objects",
                        metadata.relativize(file.getParent()).toString());
                if (!Files.exists(target)) {
                    errors.append("-> unexisting target for metadata: ").append(file).append("\r\n");
                    if (fix) {
                        try {
                            Files.delete(file);
                            fixed.append("-> deleted metadata: ").append(file).append("\r\n");
                        } catch (IOException e) {
                            errors.append("-> unable to fix: ").append(e.getMessage()).append("\r\n");
                        }
                    }
                } else if (file.endsWith("ortolang-item-json")) {
                    checkOrtolangItemJson(file);
                }
                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:com.github.jrialland.ajpclient.AbstractTomcatTest.java

protected static void deleteDirectory(final Path path) throws IOException {
    Files.walkFileTree(path, new FileVisitor<Path>() {
        @Override/* ww w .  ja va 2  s  .  co  m*/
        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;
        }

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

        @Override
        public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
            throw exc;
        }
    });
}

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

private Map<String, JSONObject> getStationMap() throws IOException, JSONException {
    final Map<String, JSONObject> map = new HashMap<>();
    final Path maps = vfs.getPath("maps");
    if (Files.isDirectory(maps)) {
        Files.walkFileTree(maps, new FileVisitor<Path>() {

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

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                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("stations").toString(),
                        JSONArray.class);
                for (int i = 0; i < jarr.length(); ++i) {
                    JSONObject jobj = jarr.getJSONObject(i);
                    String id = jobj.getString("stationID");
                    if (!map.containsKey(id))
                        map.put(id, jobj);
                }
                return FileVisitResult.CONTINUE;
            }

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

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

        });
    }
    return map;
}

From source file:com.streamsets.datacollector.bundles.content.SdcInfoContentGenerator.java

private void listDirectory(String configDir, String name, BundleWriter writer) throws IOException {
    writer.markStartOfFile("dir_listing/" + name);
    Path prefix = Paths.get(configDir);

    try {/*from w w  w . j  av  a 2  s . c  om*/
        Files.walkFileTree(Paths.get(configDir), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                printFile(dir, prefix, DIR, writer);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                printFile(file, prefix, FILE, writer);
                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 (Exception e) {
        LOG.error("Can't generate listing of {} directory: {}", configDir, e.toString(), e);
    }
    writer.markEndOfFile();
}