下面列出了怎么用org.apache.commons.io.filefilter.NameFileFilter的API类实例代码及写法,或者点击链接到github查看源代码。
private File findImageFile(File lookupFolder, String lookupTarget) {
// given file can contain sub-folders in its name
String[] paths = lookupTarget.split("[/\\\\]");
String[] foldersToFind = Arrays.copyOfRange(paths, 0, paths.length - 1);
for (String folderToFind : foldersToFind) {
lookupFolder = findFolderRecursively(lookupFolder, folderToFind);
if (lookupFolder == null) {
return null;
}
}
lookupTarget = paths[paths.length - 1];
// finally searching for file name recursively
Collection<File> files = listFiles(lookupFolder, new NameFileFilter(lookupTarget), TRUE);
return files.isEmpty() ? null : files.iterator().next();
}
public String getIndexPageURL() {
try {
File testOutputFolder = artifactsService.findArtifact(job.getIdentifier(), TEST_OUTPUT_FOLDER);
if (testOutputFolder.exists()) {
Collection<File> files = FileUtils.listFiles(testOutputFolder, new NameFileFilter("index.html"), TrueFileFilter.TRUE);
if (files.isEmpty()) {
return null;
}
File testIndexPage = files.iterator().next();
return getRestfulUrl(testIndexPage.getPath().substring(testIndexPage.getPath().indexOf(TEST_OUTPUT_FOLDER)));
}
} catch (Exception ignore) {
}
return null;
}
@Override
public URL getResource(final String name) {
final String[] list = tempDir.list(new NameFileFilter(name));
if (list.length == 0) {
return super.getResource(name);
} else {
try {
return new File(tempDir, list[0]).toURI().toURL();
} catch (final MalformedURLException e) {
return null;
}
}
}
@Test
public void testScan() {
File jarHome = new File(SystemUtils.JAVA_HOME);
Set<File> directories = simpleFileScanner.scan(jarHome, true, DirectoryFileFilter.INSTANCE);
Assert.assertFalse(directories.isEmpty());
directories = simpleFileScanner.scan(jarHome, false, new NameFileFilter("bin"));
Assert.assertEquals(1, directories.size());
}
@Override
public List<MagicCollection> listCollectionFromCards(MagicCard mc) throws SQLException {
String id = IDGenerator.generate(mc);
File f = new File(directory, CARDSDIR);
List<MagicCollection> ret = new ArrayList<>();
Collection<File> res = FileUtils.listFiles(f, new NameFileFilter(id), TrueFileFilter.INSTANCE);
for (File result : res)
ret.add(new MagicCollection(result.getParentFile().getParentFile().getName()));
return ret;
}
/**
* Creates a filter that returns everything in the "mods" folder except
* the specified cubes which are distributed with each new release and
* any existing themes which are now found in the "themes" folder.
*/
private FileFilter getModsFileFilter() {
final String[] excludedCubes = new String[]{
"legacy_cube.txt", "modern_cube.txt", "standard_cube.txt", "extended_cube.txt", "ubeefx_cube.txt"
};
final IOFileFilter cubesFilter = new NameFileFilter(excludedCubes, IOCase.INSENSITIVE);
final IOFileFilter excludeCubes = FileFilterUtils.notFileFilter(cubesFilter);
final IOFileFilter excludeThemes = FileFilterUtils.notFileFilter(new WildcardFileFilter("*_theme*"));
return FileFilterUtils.and(excludeCubes, excludeThemes);
}
@Override
protected boolean matchesSafely(File directory) {
return directory.isDirectory() && !FileUtils.listFiles(
directory,
new NameFileFilter(fileName),
TrueFileFilter.INSTANCE
).isEmpty();
}
@Override
public boolean hasAlert(MagicCard mc) {
return !FileUtils.listFiles(new File(directory, ALERTSDIR), new NameFileFilter(IDGenerator.generate(mc)),
TrueFileFilter.INSTANCE).isEmpty();
}
@GET
@Path("packages/prepare")
@Produces(MediaType.TEXT_PLAIN)
public String prepareDynamicPackages(@QueryParam("path") String techWorkspaceDir, @QueryParam("options") String options, @QueryParam("techs") String techs) throws IOException {
if(techWorkspaceDir != null && !techWorkspaceDir.trim().isEmpty()){
File packageDir = new File(techWorkspaceDir + "/package");
if(packageDir.exists() && packageDir.isDirectory()){
FileUtils.deleteDirectory(packageDir);
log.finer("Deleted package directory : " + techWorkspaceDir + "/package");
}
if(options != null && !options.trim().isEmpty()){
String[] techOptions = options.split(",");
String codeGenType = techOptions.length >= 1 ? techOptions[0] : null;
if("server".equals(codeGenType)){
String codeGenSrcDirPath = techWorkspaceDir + "/" + codeGenType + "/src";
File codeGenSrcDir = new File(codeGenSrcDirPath);
if(codeGenSrcDir.exists() && codeGenSrcDir.isDirectory()){
String packageSrcDirPath = techWorkspaceDir + "/package/src";
File packageSrcDir = new File(packageSrcDirPath);
FileUtils.copyDirectory(codeGenSrcDir, packageSrcDir, FileFilterUtils.notFileFilter(new NameFileFilter(new String[]{"RestApplication.java", "AndroidManifest.xml"})));
log.fine("Copied files from " + codeGenSrcDirPath + " to " + packageSrcDirPath);
}else{
log.fine("Swagger code gen source directory doesn't exist : " + codeGenSrcDirPath);
}
}else{
log.fine("Invalid options : " + options);
return "Invalid options : " + options;
}
}
if(techs != null && !techs.trim().isEmpty()){
//Perform actions based on other technologies/micro-services that were selected by the user
String[] techList = techs.split(",");
boolean restEnabled = false;
boolean servletEnabled = false;
for (String tech : techList) {
switch(tech){
case "rest":
restEnabled = true;
break;
case "web" :
servletEnabled = true;
break;
}
}
log.finer("Enabled : REST=" + restEnabled + " : Servlet=" + servletEnabled);
if(restEnabled){
// Swagger and REST are selected. Add Swagger annotations to the REST sample application.
String restSampleAppPath = getSharedResourceDir() + "appAccelerator/swagger/samples/rest/LibertyRestEndpoint.java";
File restSampleApp = new File(restSampleAppPath);
if(restSampleApp.exists()){
String targetRestSampleFile = techWorkspaceDir + "/package/src/main/java/application/rest/LibertyRestEndpoint.java";
FileUtils.copyFile(restSampleApp, new File(targetRestSampleFile));
log.finer("Successfuly copied " + restSampleAppPath + " to " + targetRestSampleFile);
}else{
log.fine("No swagger annotations were added : " + restSampleApp.getAbsolutePath() + " : exists=" + restSampleApp.exists());
}
}
if(servletEnabled){
//Swagger and Servlet are selected. Add swagger.json stub that describes the servlet endpoint to META-INF/stub directory.
String swaggerStubPath = getSharedResourceDir() + "appAccelerator/swagger/samples/servlet/swagger.json";
File swaggerStub = new File(swaggerStubPath);
if(swaggerStub.exists()){
String targetStubPath = techWorkspaceDir + "/package/src/main/webapp/META-INF/stub/swagger.json";
FileUtils.copyFile(swaggerStub, new File(targetStubPath));
log.finer("Successfuly copied " + swaggerStubPath + " to " + targetStubPath);
}else{
log.fine("Didn't add swagger.json stub : " + swaggerStub.getAbsolutePath() + " : exists=" + swaggerStub.exists());
}
}
}
}else{
log.fine("Invalid path : " + techWorkspaceDir);
return "Invalid path";
}
return "success";
}
@GET
@Path("files")
@Produces("application/zip")
//Swagger annotations
@ApiOperation(value = "Retrieve a zip of the content from a directory in the workspace", httpMethod = "GET", notes = "Get zip containing files from the workspace.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully produced a zip of the required workspace files") })
public Response getFiles(@QueryParam("workspace") String workspaceId, @QueryParam("serviceId") String serviceId, @QueryParam("dir") String dir) throws IOException {
log.info("GET request for /workspace/files");
String techWorkspaceDir = StarterUtil.getWorkspaceDir(workspaceId) + "/";
String filesDir = techWorkspaceDir + "/" + serviceId + "/" + dir;
File directory = new File(filesDir);
if(directory.exists() && directory.isDirectory()) {
IOFileFilter filter;
if("swagger".equals(serviceId)) {
filter = FileFilterUtils.notFileFilter(new NameFileFilter(new String[]{"RestApplication.java", "AndroidManifest.xml"}));
} else {
filter = FileFilterUtils.trueFileFilter();
}
Iterator<File> itr = FileUtils.iterateFilesAndDirs(directory, filter, FileFilterUtils.trueFileFilter());
StreamingOutput so = (OutputStream os) -> {
ZipOutputStream zos = new ZipOutputStream(os);
while(itr.hasNext()) {
File file = itr.next();
if(file.isFile()) {
byte[] byteArray = FileUtils.readFileToByteArray(file);
String path = file.getAbsolutePath().replace('\\', '/');
int index = path.indexOf(serviceId + "/" + dir);
String relativePath = path.substring(index);
ZipEntry entry = new ZipEntry(relativePath);
entry.setSize(byteArray.length);
entry.setCompressedSize(-1);
try {
zos.putNextEntry(entry);
zos.write(byteArray);
} catch (IOException e) {
throw new IOException(e);
}
}
}
zos.close();
};
log.info("Copied files from " + filesDir + " to zip.");
return Response.ok(so, "application/zip").header("Content-Disposition", "attachment; filename=\"swagger.zip\"").build();
} else {
log.severe("File directory doesn't exist : " + filesDir);
return Response.status(Status.BAD_REQUEST).entity("File directory specified doesn't exist").build();
}
}
/** Reads the package info from a given file
*
* @param file the package file as zip or an exploded directory containing metadata.
* @return the package info if the package is valid, otherwise {@code null}.
* @throws IOException if an error occurs. */
public static @Nullable PackageInfo read(@NotNull File file) throws IOException {
DefaultPackageInfo info = new DefaultPackageInfo(null, null, PackageType.MIXED);
if (!file.exists()) {
throw new FileNotFoundException("Could not find file " + file);
}
if (file.isDirectory()) {
for (File directoryFile : FileUtils.listFiles(file, new NameFileFilter(new String[] { "MANIFEST.MF", Constants.PROPERTIES_XML, Constants.FILTER_XML}),
new SuffixFileFilter(new String[] { Constants.META_INF, Constants.VAULT_DIR }))) {
try (InputStream input = new BufferedInputStream(new FileInputStream(directoryFile))) {
info = readFromInputStream(new File(file.toURI().relativize(directoryFile.toURI()).getPath()), input, info);
// bail out as soon as all info was found
if (info.getId() != null && info.getFilter() != null) {
break;
}
}
}
if (info.getId() == null || info.getFilter() == null) {
return null;
} else {
return info;
}
} else if (file.getName().endsWith(".zip")) {
// try to derive from vault-work?
try (ZipFile zip = new ZipFile(file)) {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
try (InputStream input = zip.getInputStream(e)) {
info = readFromInputStream(new File(e.getName()), input, info);
// bail out as soon as all info was found
if (info.getId() != null && info.getFilter() != null) {
break;
}
}
}
}
if (info.getId() == null || info.getFilter() == null) {
return null;
} else {
return info;
}
} else {
throw new IOException("Only metadata from zip files could be extracted but the given file is not a zip:" + file);
}
}
private File backedUpFile(final String filename) {
return new ArrayList<>(FileUtils.listFiles(backupsDirectory, new NameFileFilter(filename), TrueFileFilter.TRUE)).get(0);
}
@Test
public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() throws IOException {
final String testFile = "fileTest.txt";
String path = getClass().getClassLoader().getResource(testFile).getPath();
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
String[] possibleNames = { "NotThisOne", testFile };
Assert.assertEquals(testFile, dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]);
}