Java Code Examples for java.nio.file.SimpleFileVisitor

The following examples show how to use java.nio.file.SimpleFileVisitor. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: servicecomb-toolkit   Source File: FileUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, byte[]> getFilesGroupByFilename(String pathName) throws IOException {

    if (pathName == null) {
      throw new IOException("Path is null");
    }

    if (!new File(pathName).exists()) {
      throw new IOException("Path " + pathName + " is not exists");
    }

    Map<String, byte[]> filesGroup = new HashMap<>();
    File path = new File(pathName);

    Files.walkFileTree(Paths.get(path.toURI()), new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        filesGroup.put(file.toFile().getName(), Files.readAllBytes(file));
        return super.visitFile(file, attrs);
      }
    });

    return filesGroup;
  }
 
Example 2
Source Project: presto   Source File: PluginDiscovery.java    License: Apache License 2.0 6 votes vote down vote up
private static List<String> listClasses(Path base)
        throws IOException
{
    ImmutableList.Builder<String> list = ImmutableList.builder();
    walkFileTree(base, new SimpleFileVisitor<Path>()
    {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
        {
            if (file.getFileName().toString().endsWith(CLASS_FILE_SUFFIX)) {
                String name = file.subpath(base.getNameCount(), file.getNameCount()).toString();
                list.add(javaName(name.substring(0, name.length() - CLASS_FILE_SUFFIX.length())));
            }
            return FileVisitResult.CONTINUE;
        }
    });
    return list.build();
}
 
Example 3
Source Project: spring-analysis-note   Source File: FileSystemUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Delete the supplied {@link File} - for directories,
 * recursively delete any nested directories or files as well.
 * @param root the root {@code File} to delete
 * @return {@code true} if the {@code File} existed and was deleted,
 * or {@code false} it it did not exist
 * @throws IOException in the case of I/O errors
 * @since 5.0
 */
public static boolean deleteRecursively(@Nullable Path root) throws IOException {
	if (root == null) {
		return false;
	}
	if (!Files.exists(root)) {
		return false;
	}

	Files.walkFileTree(root, 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 exc) throws IOException {
			Files.delete(dir);
			return FileVisitResult.CONTINUE;
		}
	});
	return true;
}
 
Example 4
public void scanTree(Path base) throws IOException {
    PathLoader loader = new PathLoader(base, bootLoader);
    loaders.add(loader);

    try {
        Files.walkFileTree(base, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                if (file.toString().endsWith(".class")) {
                    String className = base.relativize(file).toString();
                    className = className.replace('\\', '/');
                    className = className.substring(0, className.length() - 6);
                    registerClass(className, loader);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (NoSuchFileException e) {
        // Skip invalid classpath entry
    }
}
 
Example 5
Source Project: synopsys-detect   Source File: DiagnosticZipCreator.java    License: Apache License 2.0 6 votes vote down vote up
public void compress(final ZipOutputStream outputStream, final Path sourceDir, final Path toCompress, final String removePiece) throws IOException {
    Files.walkFileTree(toCompress, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
            try {
                final Path targetFile = sourceDir.relativize(file);
                final String target = toZipEntryName(targetFile, removePiece);
                logger.debug("Adding file to zip: " + target);
                outputStream.putNextEntry(new ZipEntry(target));
                final byte[] bytes = Files.readAllBytes(file);
                outputStream.write(bytes, 0, bytes.length);
                outputStream.closeEntry();
            } catch (final IOException e) {
                logger.error("Failed to write to zip.", e);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}
 
Example 6
Source Project: vertx-starter   Source File: TempDir.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws Exception {
  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 exc) throws IOException {
      Files.delete(dir);
      return FileVisitResult.CONTINUE;
    }
  });
}
 
Example 7
Source Project: openjdk-jdk9   Source File: SourcePathTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method is primarily used to give visual confirmation that a test case
 * generated files when the compilation succeeds and so generates no other output,
 * such as error messages.
 */
List<Path> showFiles(Path dir) throws IOException {
    List<Path> files = new ArrayList<>();
    Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            if (Files.isRegularFile(file)) {
                out.println("Found " + file);
                files.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
    });
    return files;
}
 
Example 8
Source Project: java-technology-stack   Source File: FileSystemUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Delete the supplied {@link File} - for directories,
 * recursively delete any nested directories or files as well.
 * @param root the root {@code File} to delete
 * @return {@code true} if the {@code File} existed and was deleted,
 * or {@code false} it it did not exist
 * @throws IOException in the case of I/O errors
 * @since 5.0
 */
public static boolean deleteRecursively(@Nullable Path root) throws IOException {
	if (root == null) {
		return false;
	}
	if (!Files.exists(root)) {
		return false;
	}

	Files.walkFileTree(root, 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 exc) throws IOException {
			Files.delete(dir);
			return FileVisitResult.CONTINUE;
		}
	});
	return true;
}
 
Example 9
@After
public void tearDown() throws Exception
{
    Files.walkFileTree(_tmpDir,
                       new SimpleFileVisitor<Path>()
                       {
                           @Override
                           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;
                           }
                       });
}
 
Example 10
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException, SecurityException {
    this.archivePath = archivePath;
    if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) {
        Map<String,String> env = Collections.singletonMap("multi-release", multiReleaseValue);
        FileSystemProvider jarFSProvider = fsInfo.getJarFSProvider();
        Assert.checkNonNull(jarFSProvider, "should have been caught before!");
        this.fileSystem = jarFSProvider.newFileSystem(archivePath, env);
    } else {
        this.fileSystem = FileSystems.newFileSystem(archivePath, null);
    }
    packages = new HashMap<>();
    for (Path root : fileSystem.getRootDirectories()) {
        Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                        if (isValid(dir.getFileName())) {
                            packages.put(new RelativeDirectory(root.relativize(dir).toString()), dir);
                            return FileVisitResult.CONTINUE;
                        } else {
                            return FileVisitResult.SKIP_SUBTREE;
                        }
                    }
                });
    }
}
 
Example 11
Source Project: datawave   Source File: FlagMaker.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Determine the number of unprocessed flag files in the flag directory
 * 
 * @param fc
 * @return the flag found for this ingest pool
 */
private int countFlagFileBacklog(final FlagDataTypeConfig fc) {
    final MutableInt fileCounter = new MutableInt(0);
    final FileFilter fileFilter = new WildcardFileFilter("*_" + fc.getIngestPool() + "_" + fc.getDataName() + "_*.flag");
    final FileVisitor<java.nio.file.Path> visitor = new SimpleFileVisitor<java.nio.file.Path>() {
        
        @Override
        public FileVisitResult visitFile(java.nio.file.Path path, BasicFileAttributes attrs) throws IOException {
            if (fileFilter.accept(path.toFile())) {
                fileCounter.increment();
            }
            return super.visitFile(path, attrs);
        }
    };
    try {
        Files.walkFileTree(Paths.get(fmc.getFlagFileDirectory()), visitor);
    } catch (IOException e) {
        // unable to get a flag count....
        log.error("Unable to get flag file count", e);
        return -1;
    }
    return fileCounter.intValue();
}
 
Example 12
Source Project: hub-detect   Source File: DiagnosticZipCreator.java    License: Apache License 2.0 6 votes vote down vote up
public void compress(final ZipOutputStream outputStream, final Path sourceDir, final Path toCompress, final File out, final String removePiece) throws IOException {
    Files.walkFileTree(toCompress, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
            try {
                final Path targetFile = sourceDir.relativize(file);
                final String target = toZipEntryName(targetFile, removePiece);
                logger.debug("Adding file to zip: " + target);
                outputStream.putNextEntry(new ZipEntry(target));
                final byte[] bytes = Files.readAllBytes(file);
                outputStream.write(bytes, 0, bytes.length);
                outputStream.closeEntry();
            } catch (final IOException e) {
                logger.error("Failed to write to zip.", e);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}
 
Example 13
Source Project: cava   Source File: Files.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete a directory and all files contained within it.
 *
 * @param directory The directory to delete.
 * @throws IOException If an I/O error occurs.
 */
public static void deleteRecursively(Path directory) throws IOException {
  checkNotNull(directory);

  walkFileTree(directory, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      delete(file);
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
      delete(dir);
      return FileVisitResult.CONTINUE;
    }
  });
}
 
Example 14
Source Project: gadgetinspector   Source File: Util.java    License: MIT License 6 votes vote down vote up
/**
 * Recursively delete the directory root and all its contents
 * @param root Root directory to be deleted
 */
public static void deleteDirectory(Path root) throws IOException {
    Files.walkFileTree(root, 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 exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }
    });
}
 
Example 15
Source Project: HaloDB   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
static void deleteDirectory(File directory) throws IOException {
    if (!directory.exists())
        return;

    Path path = Paths.get(directory.getPath());
    SimpleFileVisitor<Path> visitor = 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 exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }
    };

    Files.walkFileTree(path, visitor);
}
 
Example 16
Source Project: dartboard   Source File: DartProjectConfigurator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Set<File> findConfigurableLocations(File root, IProgressMonitor monitor) {
	Set<File> files = new HashSet<>();

	try {
		Files.walkFileTree(root.toPath(), new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
				if (file.endsWith(GlobalConstants.PUBSPEC_YAML)) {
					files.add(file.toFile().getParentFile());
				}
				return FileVisitResult.CONTINUE;
			}
		});
	} catch (IOException e) {
		LOG.log(DartLog.createError("Couldn't walk children directories", e)); //$NON-NLS-1$
	}
	return files;
}
 
Example 17
@Before
public void before() throws Exception {

    // Clean up old files.
    if (Files.isDirectory(archiveDir.toPath())) {
        Files.walkFileTree(archiveDir.toPath(), new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    // Create original flow.xml.gz
    Files.createDirectories(flowFile.getParentFile().toPath());
    try (OutputStream os = Files.newOutputStream(flowFile.toPath(),
            StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
        // 10 bytes.
        os.write("0123456789".getBytes());
    }

}
 
Example 18
Source Project: Launcher   Source File: CertificateManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void readTrustStore(Path dir) throws IOException, CertificateException {
    if (!IOHelper.isDir(dir)) {
        Files.createDirectories(dir);
        try (OutputStream outputStream = IOHelper.newOutput(dir.resolve("GravitCentralRootCA.crt"));
             InputStream inputStream = IOHelper.newInput(IOHelper.getResourceURL("pro/gravit/launchserver/defaults/GravitCentralRootCA.crt"))) {
            IOHelper.transfer(inputStream, outputStream);
        }
    }
    List<X509Certificate> certificates = new ArrayList<>();
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    IOHelper.walk(dir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toFile().getName().endsWith(".crt")) {
                try (InputStream inputStream = IOHelper.newInput(file)) {
                    certificates.add((X509Certificate) certFactory.generateCertificate(inputStream));
                } catch (CertificateException e) {
                    throw new IOException(e);
                }
            }
            return super.visitFile(file, attrs);
        }
    }, false);
    trustManager = new LauncherTrustManager(certificates.toArray(new X509Certificate[0]));
}
 
Example 19
Source Project: db   Source File: Version1to2.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private void cleanTraces() {
    Path path = null;
    try {
        path = FileSystems.getDefault().getPath(BSql.OLD_BSQL_BASE_FOLDER);
        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 exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException ex) {
        logger.error("Failed to delete old copy of data. You may manually delete the folder located at: " + path.toAbsolutePath().toString());
        java.util.logging.Logger.getLogger(Version1to2.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 20
Source Project: component-runtime   Source File: SVG2Png.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        Files.walkFileTree(iconsFolder, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                final String fileName = file.getFileName().toString();
                if (fileName.endsWith(".svg")) {
                    final Path svg = file
                            .getParent()
                            .resolve(fileName.substring(0, fileName.length() - ".svg".length()) + "_icon32.png");
                    if (!Files.exists(svg)) {
                        createPng(file, svg);
                        log.info("Created " + svg);
                    }
                }
                return super.visitFile(file, attrs);
            }
        });
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 21
Source Project: quarkus   Source File: ResteasyStandaloneBuildStep.java    License: Apache License 2.0 6 votes vote down vote up
private void collectKnownPaths(Path resource, Set<String> knownPaths) {
    try {
        Files.walkFileTree(resource, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path p, BasicFileAttributes attrs)
                    throws IOException {
                String file = resource.relativize(p).toString();
                if (file.equals("index.html") || file.equals("index.htm")) {
                    knownPaths.add("/");
                }
                if (!file.startsWith("/")) {
                    file = "/" + file;
                }
                // Windows has a backslash
                file = file.replace('\\', '/');
                knownPaths.add(file);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 22
Source Project: steady   Source File: GradlePluginApp.java    License: Apache License 2.0 6 votes vote down vote up
private void cleanupTempFiles() throws IOException {

        if (tmpPath == null) {
            return;
        }

        Files.walkFileTree(tmpPath, 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 exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

        });
    }
 
Example 23
Source Project: openjdk-jdk8u   Source File: IterationCount.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void deleteDir(Path directory) throws IOException {
    Files.walkFileTree(directory, 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 exc)
                throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }
    });
}
 
Example 24
public void delete() {
    FileVisitor<Path> fileVisitor = new SimpleFileVisitor<>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

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

    try {
        Files.walkFileTree(dir, fileVisitor);
    } catch (IOException e) {
        throw new ResourceException("failed to delete dir, path={}", dir, e);
    }
}
 
Example 25
Source Project: Java-Data-Science-Cookbook   Source File: IndexFiles.java    License: MIT License 6 votes vote down vote up
static void indexDocs(final IndexWriter writer, Path path) throws IOException {
	if (Files.isDirectory(path)) {
		Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
				try {
					indexDoc(writer, file, attrs.lastModifiedTime().toMillis());
				} catch (IOException ignore) {
				}
				return FileVisitResult.CONTINUE;
			}
		}
				);
	} else {
		indexDoc(writer, path, Files.getLastModifiedTime(path).toMillis());
	}
}
 
Example 26
Source Project: openjdk-systemtest   Source File: WalkFileTreeTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testWalkFileTreeMultiple() throws IOException {		
	final int ITERATIONS = 1000;
	Path newDirectory = WALKFILETREE_FILE_DIR;	
	for (int counter=0; counter< ITERATIONS; counter++) {		
		HangNotifier.ping();	
		final List<Path> visitorFiles = new LinkedList<Path>();		
		// Check that we keep returning the same set of files!
		Files.walkFileTree(newDirectory, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) {
				if (path.toString().endsWith(".txt")) {
					visitorFiles.add(path);
				}
				return FileVisitResult.CONTINUE;
			}
		});

		if(!ReiserSpotter.getIsReiser()){
			assertEquals("Wrong number of files walked on iteration " + counter, NUMBER_OF_FILES, visitorFiles.size());
		}		
	}	
}
 
Example 27
Source Project: ProjectAres   Source File: MapSource.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public Set<Path> getMapFolders(final Logger logger) throws IOException {
    final Set<Path> mapFolders = new HashSet<>();
    for(Path root : getRootPaths()) {
        int depth = "".equals(root.toString()) ? 0 : Iterables.size(root);
        Files.walkFileTree(getPath().resolve(root), ImmutableSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth - depth, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if(!isExcluded(dir)) {
                    if(MapFolder.isMapFolder(dir)) {
                        mapFolders.add(dir);
                    }
                    return FileVisitResult.CONTINUE;
                } else {
                    logger.fine("Skipping excluded path " + dir);
                    return FileVisitResult.SKIP_SUBTREE;
                }
            }
        });
    }
    return mapFolders;
}
 
Example 28
Source Project: Elasticsearch   Source File: LogConfigurator.java    License: Apache License 2.0 6 votes vote down vote up
static void resolveConfig(Environment env, final Settings.Builder settingsBuilder) {

        try {
            Files.walkFileTree(env.configFile(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String fileName = file.getFileName().toString();
                    if (fileName.startsWith("logging.")) {
                        for (String allowedSuffix : ALLOWED_SUFFIXES) {
                            if (fileName.endsWith(allowedSuffix)) {
                                loadConfig(file, settingsBuilder);
                                break;
                            }
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException ioe) {
            throw new ElasticsearchException("Failed to load logging configuration", ioe);
        }
    }
 
Example 29
public void compact() throws IOException {
  // making the cache using a local repository generates a lot of files
  // we don't need, including duplicated jars for -SNAPSHOT versions so
  // we remove any file from the cache where the name doesn't include
  // the parent folder name within it, which leaves us the main jar, the
  // pom.xml and the -creole.jar plus some .sha1 files
  Files.walkFileTree(head.toPath(), new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
        throws IOException {

      String filename = file.getFileName().toString();

      if((!filename.endsWith(".jar") && !filename.endsWith(".pom")) ||
          !filename.contains(file.getParent().getFileName().toString())) {
        java.nio.file.Files.delete(file);
      }

      return FileVisitResult.CONTINUE;
    }
  });
}
 
Example 30
Source Project: jpa2ddl   Source File: FileResolver.java    License: Apache License 2.0 6 votes vote down vote up
static List<String> listClassNamesInPackage(String packageName) throws Exception {
	List<String> classes = new ArrayList<>();
	Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(packageName.replace('.', File.separatorChar));
	if (!resources.hasMoreElements()) {
		throw new IllegalStateException("No package found: " + packageName);
	}
	PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:*.class");
	while (resources.hasMoreElements()) {
		URL resource = resources.nextElement();
		Files.walkFileTree(Paths.get(resource.toURI()), new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
				if (pathMatcher.matches(path.getFileName())) {
					try {
						String className = Paths.get(resource.toURI()).relativize(path).toString().replace(File.separatorChar, '.');
						classes.add(packageName + '.' + className.substring(0, className.length() - 6));
					} catch (URISyntaxException e) {
						throw new IllegalStateException(e);
					}
				}
				return FileVisitResult.CONTINUE;
			}
		});
	}
	return classes;
}