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.jboss.as.test.manualmode.logging.SizeAppenderRestartTestCase.java

private void clearLogs(final Path path) throws IOException {
    final String expectedName = path.getFileName().toString();
    Files.walkFileTree(path.getParent(), new SimpleFileVisitor<Path>() {
        @Override//from  w  ww.ja v a 2 s.com
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            final String currentName = file.getFileName().toString();
            if (currentName.startsWith(expectedName)) {
                Files.delete(file);
            }
            return super.visitFile(file, attrs);
        }
    });
}

From source file:de.dentrassi.rpm.builder.YumMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    this.logger = new Logger(getLog());

    try {//from w  w w.  j  a  v  a2 s  . c o m
        final Builder builder = new RepositoryCreator.Builder();
        builder.setTarget(new FileSystemSpoolOutTarget(this.outputDirectory.toPath()));

        if (!this.skipSigning) {
            final PGPPrivateKey privateKey = SigningHelper.loadKey(this.signature, this.logger);
            if (privateKey != null) {
                final int digestAlgorithm = HashAlgorithm.from(this.signature.getHashAlgorithm()).getValue();
                builder.setSigning(output -> new SigningStream(output, privateKey, digestAlgorithm, false,
                        "RPM builder Mojo - de.dentrassi.maven:rpm"));
            }
        }

        final RepositoryCreator creator = builder.build();

        this.packagesPath = new File(this.outputDirectory, "packages");
        Files.createDirectories(this.packagesPath.toPath());

        final Collection<Path> paths = Lists.newArrayList();

        if (!this.skipDependencies) {
            final Set<Artifact> deps = this.project.getArtifacts();
            if (deps != null) {
                paths.addAll(deps.stream()//
                        .filter(d -> d.getType().equalsIgnoreCase("rpm"))//
                        .map(d -> d.getFile().toPath())//
                        .collect(Collectors.toList()));
            }
        } else {
            this.logger.debug("Skipped RPM artifacts from maven dependencies");
        }

        if (this.files != null) {
            paths.addAll(this.files.stream().map(f -> f.toPath()).collect(Collectors.toList()));
        }
        if (this.directories != null) {
            for (final File dir : this.directories) {
                Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                            throws IOException {
                        if (file.getFileName().toString().toLowerCase().endsWith(".rpm")) {
                            paths.add(file);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
            }
        }

        addPackageList(creator, paths);
    } catch (final IOException e) {
        throw new MojoExecutionException("Failed to write repository", e);
    }
}

From source file:spdxedit.SpdxLogic.java

/**
 * Creates a new package with the specified license, name, comment, and root
 * path./*  w w  w . j av a  2 s  .  c  om*/
 *
 * @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:org.olat.course.certificate.ui.UploadCertificateController.java

private boolean validateHtml(String filename, File template) {
    boolean allOk = true;
    try {//from   w w  w  . j av a  2s .  c  o m
        if (certificatesManager.isHTMLTemplateAllowed()) {
            Path path = FileResource.getResource(template, filename);
            IndexVisitor visitor = new IndexVisitor(path);
            Files.walkFileTree(path, visitor);
            if (!visitor.hasFound()) {
                fileEl.setErrorKey("upload.error.noindex", null);
            }
            allOk = visitor.hasFound();

            formatEl.setVisible(allOk);
            orientationEl.setVisible(allOk);
        } else {
            fileEl.setErrorKey("upload.error.no.phantomjs", null);
            allOk = false;
        }
    } catch (IOException e) {
        logError("", e);
        fileEl.setErrorKey("upload.unkown.error", null);
        allOk = false;
    }
    return allOk;
}

From source file:stroom.streamstore.server.fs.FileSystemUtil.java

public static boolean deleteContents(final Path path) {
    try {//from  www .j a va2s  .co  m
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                    throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
                // try to delete the file anyway, even if its attributes
                // could not be read, since delete-only access is
                // theoretically possible
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
                    throws IOException {
                if (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    // directory iteration failed; propagate exception
                    throw exc;
                }
            }
        });
    } catch (final IOException e) {
        return false;
    }

    return true;
}

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//  w w w .  ja  v  a 2s . c  om
        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.springframework.integration.file.WatchServiceDirectoryScanner.java

private Set<File> walkDirectory(Path directory) {
    final Set<File> walkedFiles = new LinkedHashSet<File>();
    try {//from   ww w  .java  2 s  .c o m
        registerWatch(directory);
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.preVisitDirectory(dir, attrs);
                registerWatch(dir);
                return fileVisitResult;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.visitFile(file, attrs);
                walkedFiles.add(file.toFile());
                return fileVisitResult;
            }

        });
    } catch (IOException e) {
        logger.error("Failed to walk directory: " + directory.toString(), e);
    }
    return walkedFiles;
}

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   ww w. j  a  va  2s .  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:org.bonitasoft.platform.configuration.impl.ConfigurationServiceImpl.java

@Override
public void storeAllConfiguration(Path configurationRootFolder) throws PlatformException {
    List<FullBonitaConfiguration> fullBonitaConfigurations = new ArrayList<>();
    AllConfigurationResourceVisitor allConfigurationResourceVisitor = new AllConfigurationResourceVisitor(
            fullBonitaConfigurations);//  w w  w  .j a va2s. co  m
    try {
        Files.walkFileTree(configurationRootFolder, allConfigurationResourceVisitor);
        transactionTemplate.execute(new CleanAndStoreAllConfigurationInTransaction(jdbcTemplate, dbVendor,
                fullBonitaConfigurations));
    } catch (IOException e) {
        throw new PlatformException(e);
    }
}

From source file:com.github.anba.es6draft.util.Resources.java

/**
 * Recursively searches for js-file test cases in {@code basedir} and its sub-directories.
 *///w  ww . j a  v a  2 s.  c  om
private static <TEST extends TestInfo> List<TEST> loadTests(Configuration config, Function<Path, TEST> mapper,
        Path basedir) throws IOException {
    FilterFileVisitor<Path> ffv = new FilterFileVisitor<Path>(basedir, new FileMatcher(config));
    CollectorFileVisitor<Path, TEST> cfv = new CollectorFileVisitor<>(ffv, mapper);
    Files.walkFileTree(basedir, cfv);
    List<TEST> tests = cfv.getResult();
    filterTests(tests, basedir, config);
    if (REMOVE_DISABLED_TESTS) {
        tests = removeDisabled(tests);
    }
    return tests;
}