List of usage examples for java.nio.file SimpleFileVisitor SimpleFileVisitor
protected SimpleFileVisitor()
From source file:net.sourceforge.pmd.cache.AbstractAnalysisCache.java
private URL[] getClassPathEntries() { final String classpath = System.getProperty("java.class.path"); final String[] classpathEntries = classpath.split(File.pathSeparator); final List<URL> entries = new ArrayList<>(); final SimpleFileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() { @Override/*from www. j a va 2 s. c om*/ public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { if (!attrs.isSymbolicLink()) { // Broken link that can't be followed entries.add(file.toUri().toURL()); } return FileVisitResult.CONTINUE; } }; final SimpleFileVisitor<Path> jarFileVisitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { String extension = FilenameUtils.getExtension(file.toString()); if ("jar".equalsIgnoreCase(extension)) { fileVisitor.visitFile(file, attrs); } return FileVisitResult.CONTINUE; } }; try { for (final String entry : classpathEntries) { final File f = new File(entry); if (isClassPathWildcard(entry)) { Files.walkFileTree(new File(entry.substring(0, entry.length() - 1)).toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, jarFileVisitor); } else if (f.isFile()) { entries.add(f.toURI().toURL()); } else { Files.walkFileTree(f.toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, fileVisitor); } } } catch (final IOException e) { LOG.log(Level.SEVERE, "Incremental analysis can't check execution classpath contents", e); throw new RuntimeException(e); } return entries.toArray(new URL[0]); }
From source file:org.fao.geonet.api.mapservers.GeoFile.java
/** * Returns the names of the vector layers (Shapefiles) in the geographic file. * * @param onlyOneFileAllowed Return exception if more than one shapefile found * @return a collection of layer names/*from w ww. j av a 2 s . c om*/ * @throws IllegalArgumentException If more than on shapefile is found and onlyOneFileAllowed is * true or if Shapefile name is not equal to zip file base * name */ public Collection<String> getVectorLayers(final boolean onlyOneFileAllowed) throws IOException { final LinkedList<String> layers = new LinkedList<String>(); if (zipFile != null) { for (Path path : zipFile.getRootDirectories()) { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String fileName = file.getFileName().toString(); if (fileIsShp(fileName)) { String base = getBase(fileName); if (onlyOneFileAllowed) { if (layers.size() > 1) throw new IllegalArgumentException("Only one shapefile per zip is allowed. " + layers.size() + " shapefiles found."); if (base.equals(getBase(fileName))) { layers.add(base); } else throw new IllegalArgumentException("Shapefile name (" + base + ") is not equal to ZIP file name (" + file.getFileName() + ")."); } else { layers.add(base); } } if (fileIsSld(fileName)) { _containsSld = true; _sldBody = fileName; } return FileVisitResult.CONTINUE; } }); } if (_containsSld) { ZipFile zf = new ZipFile(new File(this.file.toString())); InputStream is = zf.getInputStream(zf.getEntry(_sldBody)); BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String line; _sldBody = ""; while ((line = br.readLine()) != null) { _sldBody += line; } br.close(); is.close(); zf.close(); } } return layers; }
From source file:org.jboss.as.test.manualmode.logging.SizeAppenderRestartTestCase.java
private Iterable<Path> listLogFiles() throws IOException { final Collection<Path> names = new ArrayList<>(); Files.walkFileTree(logFile.getParent(), new SimpleFileVisitor<Path>() { @Override/*ww w . j a v a2s. c om*/ public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { names.add(file); return super.visitFile(file, attrs); } }); return names; }
From source file:org.talend.dataprep.cache.file.FileSystemContentCacheTest.java
@Test public void testJanitor() throws Exception { // given some cache entries List<ContentCacheKey> keys = new ArrayList<>(); for (int i = 0; i < 10; i++) { keys.add(new DummyCacheKey("janitor me " + i + 1)); }//from w ww . ja v a2 s . c o m for (ContentCacheKey key : keys) { addCacheEntry(key, "janitor content", ContentCache.TimeToLive.DEFAULT); Assert.assertThat(cache.has(key), is(true)); } // when eviction is performed and the janitor is called for (ContentCacheKey key : keys) { cache.evict(key); } janitor.janitor(); // then no file in the cache should be left Files.walkFileTree(Paths.get(TEST_DIRECTORY), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!StringUtils.contains(file.toFile().getName(), ".nfs")) { Assert.fail("file " + file + " was not cleaned by the janitor"); } return super.visitFile(file, attrs); } }); }
From source file:org.roda.core.storage.fs.FSUtils.java
private static void moveRecursively(final Path sourcePath, final Path targetPath, final boolean replaceExisting) throws GenericException { final CopyOption[] copyOptions = replaceExisting ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING } : new CopyOption[] {}; try {/*from w w w . ja v a 2 s . com*/ Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path sourceDir, BasicFileAttributes attrs) throws IOException { Path targetDir = targetPath.resolve(sourcePath.relativize(sourceDir)); LOGGER.trace("Creating target directory {}", targetDir); Files.createDirectories(targetDir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path sourceFile, BasicFileAttributes attrs) throws IOException { Path targetFile = targetPath.resolve(sourcePath.relativize(sourceFile)); LOGGER.trace("Moving file from {} to {}", sourceFile, targetFile); Files.move(sourceFile, targetFile, copyOptions); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path sourceFile, IOException exc) throws IOException { LOGGER.trace("Deleting source directory {}", sourceFile); Files.delete(sourceFile); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { throw new GenericException( "Error while moving (recursively) directory from " + sourcePath + " to " + targetPath, e); } }
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 ww w . ja v a2 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 {// www. j a va 2 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:stroom.streamstore.server.fs.FileSystemUtil.java
public static boolean deleteContents(final Path path) { try {/*from ww w .j av a 2 s. c o 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: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 om*/ 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.craftercms.studio.impl.v1.repository.disk.DiskContentRepository.java
/** * get immediate children for path/*from w w w. ja v a 2 s .co m*/ * @param path path to content */ public RepositoryItem[] getContentChildren(String path) { final List<RepositoryItem> retItems = new ArrayList<RepositoryItem>(); try { EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); final String finalPath = path; Files.walkFileTree(constructRepoPath(finalPath), opts, 1, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path visitPath, BasicFileAttributes attrs) throws IOException { if (!visitPath.equals(constructRepoPath(finalPath))) { RepositoryItem item = new RepositoryItem(); item.name = visitPath.toFile().getName(); String visitFolderPath = visitPath.toString();//.replace("/index.xml", ""); //Path visitFolder = constructRepoPath(visitFolderPath); item.isFolder = visitPath.toFile().isDirectory(); int lastIdx = visitFolderPath.lastIndexOf(File.separator + item.name); if (lastIdx > 0) { item.path = visitFolderPath.substring(0, lastIdx); } //item.path = visitFolderPath.replace("/" + item.name, ""); item.path = item.path.replace(getRootPath().replace("/", File.separator), ""); item.path = item.path.replace(File.separator + ".xml", ""); item.path = item.path.replace(File.separator, "/"); if (!".DS_Store".equals(item.name)) { logger.debug("ITEM NAME: {0}", item.name); logger.debug("ITEM PATH: {0}", item.path); logger.debug("ITEM FOLDER: ({0}): {1}", visitFolderPath, item.isFolder); retItems.add(item); } } return FileVisitResult.CONTINUE; } }); } catch (Exception err) { // log this error } RepositoryItem[] items = new RepositoryItem[retItems.size()]; items = retItems.toArray(items); return items; }