Java 类org.apache.commons.io.filefilter.NameFileFilter 实例源码
项目:Maven-Vault-Checkout-Plugin
文件:CleanHelper.java
public static void cleanupDotContent(String root, String[] contentProperties) throws MojoExecutionException {
for (File file : FileUtils.listFiles(new File(root), new NameFileFilter(".content.xml"),
TrueFileFilter.INSTANCE)) {
try {
LOG.info("Cleaning up {}", file.getPath());
List<String> lines = new ArrayList<String>();
for (String line : FileUtils.readLines(file, CharEncoding.UTF_8)) {
String cleanLine = StringUtils.trimToEmpty(line);
boolean lineContains = lineContainsProperty(cleanLine, contentProperties);
if (lineContains) {
if (!cleanLine.endsWith(">")) {
} else {
String lastLine = lines.remove(lines.size() - 1);
lines.add(lastLine + ">");
}
} else {
lines.add(line);
}
}
FileUtils.writeLines(file, CharEncoding.UTF_8, lines);
} catch (IOException e) {
throw new MojoExecutionException(String.format("Error opening %s", file.getPath()), e);
}
}
}
项目:prometheus
文件:ReloadableConfig.java
public ReloadableConfig() {
new Thread(()->{
long interval = TimeUnit.SECONDS.toMillis(30);
try {
ClassPathResource resource = new ClassPathResource(getClassPathFilePath());
File file = resource.getFile();
FileAlterationObserver observer = new FileAlterationObserver(file.getParentFile() , new NameFileFilter(file.getName()));
observer.addListener(this);
FileAlterationMonitor monitor = new FileAlterationMonitor(interval , observer);
LOGGER.debug("监听文件:{}" , file.getPath());
monitor.start();
} catch (Exception e) {
LOGGER.error("ClassPathFilePath:{}" , getClassPathFilePath());
LOGGER.error("" , e);
}
}).start();
}
项目:xslweb
文件:Context.java
private void initWebApps() throws Exception {
File webAppsDir = new File(homeDir, "webapps");
File[] dirs = webAppsDir.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);
for (File dir : dirs) {
File[] webAppFiles = dir.listFiles((FilenameFilter) new NameFileFilter("webapp.xml"));
if (webAppFiles.length == 0) {
continue;
}
File file = webAppFiles[0];
try {
WebApp webApp = new WebApp(webAppFiles[0]);
webApps.put(webApp.getName(), webApp);
webApp.open();
} catch (Exception e) {
logger.error(String.format("Error creating webapp \"%s\"", file.getAbsolutePath()), e);
}
}
}
项目:selenium-grid-extensions
文件:TargetFactory.java
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();
}
项目:saos
文件:ContentSourceFileFinder.java
/**
* Finds content file in directory (or subdirectory) that 'corresponds' to
* passed metadata file.
*
* In our case 'corresponding' files means that files have the same name base
* but extensions may differ.
* Extension of returned file must be one of the {@link #setEligibleFileExtensions(String[])}
*/
public File findContentFile(File contentDir, File correspondingMetadataFile) {
String filenameBase = extractFilenameBase(correspondingMetadataFile.getName());
List<String> possibleFileNames = buildPossibleFilenames(filenameBase);
Collection<File> foundContentFiles = FileUtils.listFiles(contentDir, new NameFileFilter(possibleFileNames), TrueFileFilter.INSTANCE);
if (foundContentFiles.size() == 0) {
throw new ImportException("No content file was found for " + correspondingMetadataFile + " in " + contentDir.getPath());
}
if (foundContentFiles.size() > 1) {
throw new ImportException("More than one file found as content file candidate of " + correspondingMetadataFile);
}
return foundContentFiles.iterator().next();
}
项目:TheMatrixProject
文件:TempFileManager.java
/**
* Return the path of a file.
* First checks presence in IAD directory, if not return results as path for the file.
* It expects a file in the format of filename.extension.
* @param filename
* @return the path of a file
*/
// FIXME: this method should be moved elsewhere
public static File getPathForFile(String filename)
{
File iad = new File(Dynamic.getIadPath());
File result = new File(Dynamic.getResultsPath());
String[] iad_list = iad.list(new NameFileFilter(filename));
String[] result_list = result.list(new NameFileFilter(filename));
if (iad_list.length > 0 && result_list.length > 0)
LogST.logP(0, "*** WARNING: found the file "+filename+" both in IAD and RESULTs. Now reading from RESULTS.");
if (result_list.length > 0)
return result;
else if (iad_list.length > 0)
return iad;
else
return result;
}
项目:gocd
文件:JobDetailPresentationModel.java
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;
}
项目:jcabi-aether
文件:Aether.java
/**
* Apply maven invoker settings.
* @param builder Settings builder.
* @param result User and global settings.
* @return User, global and invoker settings.
*/
private Settings invokers(final SettingsBuilder builder,
final SettingsBuildingResult result) {
Settings main = result.getEffectiveSettings();
final File[] files = new File(System.getProperty("user.dir"))
.getParentFile().listFiles(
(FileFilter) new NameFileFilter("interpolated-settings.xml")
);
if (files.length == 1) {
final DefaultSettingsBuildingRequest irequest =
new DefaultSettingsBuildingRequest();
irequest.setUserSettingsFile(files[0]);
try {
final Settings isettings = builder.build(irequest)
.getEffectiveSettings();
SettingsUtils.merge(isettings, main, TrackableBase.USER_LEVEL);
main = isettings;
} catch (final SettingsBuildingException ex) {
throw new IllegalStateException(ex);
}
}
return main;
}
项目:confucius-commons
文件:SimpleFileScannerTest.java
@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());
}
项目:cucumber-runner-maven-plugin
文件:Run.java
private List<String> findReports(String reportFileName)
throws MojoFailureException {
List<String> reportFiles = new ArrayList<>();
NameFileFilter nameFileFilter = new NameFileFilter(reportFileName);
Iterator<File> files = org.apache.commons.io.FileUtils
.iterateFiles(getThreadFolder(),
nameFileFilter, DirectoryFileFilter.DIRECTORY);
while(files.hasNext()) {
reportFiles.add(files.next().getAbsolutePath());
}
return reportFiles;
}
项目:Maven-Vault-Checkout-Plugin
文件:CleanHelper.java
public static void removeVltFiles(String root) {
for (File file : FileUtils.listFiles(new File(root), new NameFileFilter(".vlt"),
TrueFileFilter.INSTANCE)) {
LOG.info("Deleting {}", file.getPath());
FileUtils.deleteQuietly(file);
}
}
项目:owsi-core-parent
文件:FileUtils.java
public static File getFile(File directory, String name) {
List<File> files = list(directory, new NameFileFilter(name));
if (files.size() == 1) {
return files.get(0);
} else {
throw new IllegalArgumentException("Unable to find file " + name + " in " + directory.getAbsolutePath());
}
}
项目:greenpepper
文件:JavaFixtureGenerator.java
private File getJavaSouceFile(FixtureDescription fixture, MetaInformation metaInformation, File fixtureSourceDirectory, String packageName) throws IOException {
String fixtureFilename = fixture.getName() + JAVA_EXTENSION;
File javaSouceFile = null;
// we search in every imports
List<String> imports = metaInformation.getImports();
for (String anImport : imports) {
File packageDir = new File(fixtureSourceDirectory, replaceChars(anImport, DOT, separatorChar));
if (packageDir.isDirectory()) {
Collection<File> files = listFiles(packageDir, new NameFileFilter(fixtureFilename, IOCase.INSENSITIVE), null);
if (files.size() == 1) {
javaSouceFile = files.iterator().next();
break;
} else if (files.size() > 1) {
LOGGER.error("You have multiple java sources with the same case insensitive names.");
LOGGER.error("We can't choose the file to merge the fixture in.");
LOGGER.error("Moreover, your build is platform dependant because of this issue.");
LOGGER.error("Incriminating files:");
for (File file : files) {
LOGGER.error("\t - {}", file.getAbsolutePath());
}
break;
}
}
}
// if we didn't find the file
if (javaSouceFile == null) {
if (isNotBlank(packageName)) {
File directoryForFixure = new File(fixtureSourceDirectory, replaceChars(packageName, DOT, separatorChar));
forceMkdir(directoryForFixure);
javaSouceFile = new File(directoryForFixure, fixtureFilename);
} else {
forceMkdir(fixtureSourceDirectory);
javaSouceFile = new File(fixtureSourceDirectory, fixtureFilename);
LOGGER.warn("You have no default package defined. I can't choose any import packages. Generating the Fixture in the source root. This is generally not a good idea.");
}
}
return javaSouceFile ;
}
项目:testfairy-uploader
文件:SdkEnvironment.java
/**
* Locates zipalign tool on disk.
*
* @return String
*/
public String locateZipalign() {
String ext = isWindows() ? ".exe" : "";
File zipalign = new File(FilenameUtils.normalize(sdkDirectory + "/tools/zipalign" + ext));
if (zipalign.exists()) {
return zipalign.getAbsolutePath();
}
// find any zipfiles under the sdk/build-tools
Collection<File> files = FileUtils.listFiles(new File(sdkDirectory + "/build-tools"), new NameFileFilter("zipalign" + ext), TrueFileFilter.INSTANCE);
if (files.size() > 0) {
// found at least one zipalign file, look up the highest version
Iterator<File> it = files.iterator();
zipalign = it.next();
while (it.hasNext()) {
File f = it.next();
if (zipalign.compareTo(f) < 0) {
// f is newer
zipalign = f;
}
}
return zipalign.getAbsolutePath();
}
return null;
}
项目:artifactory
文件:ArtifactoryApplicationContext.java
private void exportEtcDirectory(ExportSettings settings) {
try {
File targetBackupDir = new File(settings.getBaseDir(), "etc");
// TODO: [by fsi] Find a way to copy with permissions kept
FileUtils.copyDirectory(artifactoryHome.getEtcDir(), targetBackupDir,
new NotFileFilter(new NameFileFilter("artifactory.lic")), true);
checkSecurityFolder(targetBackupDir);
} catch (IOException e) {
settings.getStatusHolder().error(
"Failed to export etc directory: " + artifactoryHome.getEtcDir().getAbsolutePath(), e, log);
}
}
项目:artifactory
文件:ArtifactoryApplicationContext.java
private void exportHaEtcDirectory(ExportSettings settings) {
if (artifactoryHome.isHaConfigured()) {
try {
File targetBackupDir = new File(settings.getBaseDir(), "ha-etc");
// TODO: [by fsi] Find a way to copy with permissions kept
FileUtils.copyDirectory(artifactoryHome.getHaAwareEtcDir(), targetBackupDir,
new NotFileFilter(new NameFileFilter("artifactory.lic")));
checkSecurityFolder(targetBackupDir);
} catch (IOException e) {
settings.getStatusHolder().error(
"Failed to export etc directory: " + artifactoryHome.getEtcDir().getAbsolutePath(), e, log);
}
}
}
项目:sosiefier
文件:DirectoryWalkerTestCaseJava4.java
/**
* Create an name filter containg the names of the files
* in the array.
*/
private static IOFileFilter createNameFilter(File[] files) {
String[] names = new String[files.length];
for (int i = 0 ; i < (files.length) ; i++) {
names[i] = files[i].getName();
}
return new NameFileFilter(names);
}
项目:sosiefier
文件:DirectoryWalkerTestCase.java
/**
* Create an name filter containg the names of the files
* in the array.
*/
private static IOFileFilter createNameFilter(File[] files) {
String[] names = new String[files.length];
for (int i = 0 ; i < (files.length) ; i++) {
names[i] = files[i].getName();
}
return new NameFileFilter(names);
}
项目:magarena
文件:ImportWorker.java
/**
* 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);
}
项目:Leo
文件:LeoTypeSystemDescriptionTest.java
@Test
public void jCasGenTest() throws Exception {
String srcDirectory = "src/test/java";
String binDirectory = "target/resources/bin";
//Create the bin directory if it does not exist
File binFile = new File(binDirectory);
if(!binFile.exists()) {
assertTrue(binFile.mkdirs());
}
//Remove the Source Files if they exist
removeTestTypeFiles(srcDirectory, binDirectory);
//Import the Type System
LeoTypeSystemDescription ftsd = null;
ftsd = new LeoTypeSystemDescription("desc.gov.va.vinci.leo.types.TestTypeSystem", true);
assertNotNull(ftsd);
ftsd.jCasGen(srcDirectory, binDirectory);
assertNotNull(ftsd);
List<String> fileNames = new ArrayList<String>();
for (TypeDescription td :ftsd.getTypes()) {
String name = td.getName().substring(td.getName().lastIndexOf('.') + 1, td.getName().length());
fileNames.add(name + ".java");
fileNames.add(name + "_Type.java");
}//for
List<File> javaSrcFiles = LeoUtils.listFiles(new File(srcDirectory), new NameFileFilter(fileNames), true);
assertNotNull(javaSrcFiles);
File classFile = new File(binDirectory + "/gov/va/vinci/leo/types/TestType.class");
assertTrue(classFile.exists());
//Cleanup generated files
removeTestTypeFiles(srcDirectory, binDirectory);
}
项目:screwdriver
文件:ExcludesIntegrationTest.java
@Test
public void testFileFilterExclusions() throws Exception {
// exclude directories named "bootstrap"
IOFileFilter dirFilter = FileFilterUtils.and(
FileFilterUtils.notFileFilter(new NameFileFilter("bootstrap")),
DirectoryFileFilter.DIRECTORY);
cfg.setCssDirFilter(dirFilter);
BuildAll.build(cfg);
Collection<File> files = TestUtil.cssOutputFiles();
assertEquals(2, files.size());
}
项目:allure1
文件:DirectoryMatcher.java
@Override
protected boolean matchesSafely(File directory) {
return directory.isDirectory() && !FileUtils.listFiles(
directory,
new NameFileFilter(fileName),
TrueFileFilter.INSTANCE
).isEmpty();
}
项目:kalibro
文件:RepositoryLoaderTest.java
@Override
public boolean matches(Object argument) {
if (argument instanceof NameFileFilter) {
String[] names = Whitebox.getInternalState(argument, String[].class);
IOCase caseSensitivity = Whitebox.getInternalState(argument, IOCase.class);
return Arrays.equals(names, new String[]{METADATA_DIRECTORY})
&& caseSensitivity.equals(IOCase.SENSITIVE);
}
return false;
}
项目:tool.accelerate.core
文件:WorkspaceEndpoint.java
@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();
}
}
项目:Leo
文件:LeoTypeSystemDescription.java
/**
* Generate the .java files for the types in this TypeSystem then compile them into byte code
* to the bin directory specified.
*
* @param srcDirectory Path to the root source directory where the .java files will be generated, including package names
* @param binDirectory Bin directory where .class files will be generated.
* @throws Exception If there is no type system or there is an error generating the .java files
*/
public void jCasGen(String srcDirectory, String binDirectory) throws Exception {
//If there is no type system throw an Exception
if (this.myTypeSystemDescription == null) {
throw new Exception("Cannot generate a null TypeSystem");
}//if
//Throw and exception if we are missing one of our parameters
if (StringUtils.isBlank(srcDirectory) || StringUtils.isBlank(binDirectory)) {
throw new Exception("Both the source directory and bin directory are required arguments");
}//if
//Generate the TypeSystemDescription xml
this.toXML(this.mDescriptorLocator);
//Get the classpath
String classpath = System.getProperty("java.class.path");
//Create an instance of the Jg class and call the "main" method to generate the java files
String[] args = {"-jcasgeninput", this.mDescriptorLocator.trim(), "-jcasgenoutput", srcDirectory, "=jcasgenclasspath", classpath};
Jg jcasGen = new Jg();
int ret = jcasGen.main1(args);
if (ret == -1) {
//Error generating the java files
throw new Exception("Error occurred generating the Java source files");
}//if
List<String> fileNames = new ArrayList<String>();
for (TypeDescription td : getTypes()) {
String name = td.getName().substring(td.getName().lastIndexOf('.') + 1, td.getName().length());
fileNames.add(name + ".java");
fileNames.add(name + "_Type.java");
}//for
NameFileFilter fnf = new NameFileFilter(fileNames);
List<File> javaSrcFiles = LeoUtils.listFiles(new File(srcDirectory), fnf, true);
if (javaSrcFiles == null) {
log.warn("No Java Source files found to compile in jCasGen");
return;
}//if
//Iterate through the list of java files and compile them all
try {
AutoCompile.compileFiles(javaSrcFiles.toArray(new File[0]), binDirectory);
} catch (Exception e) {
log.warn("Exception Thrown compiling files in test", e);
}
}
项目:gocd
文件:BackupServiceIntegrationTest.java
private File backedUpFile(final String filename) {
return new ArrayList<>(FileUtils.listFiles(backupsDirectory, new NameFileFilter(filename), TrueFileFilter.TRUE)).get(0);
}
项目:gocd
文件:BackupServiceH2IntegrationTest.java
private File backedUpFile(final String filename) {
return new ArrayList<>(FileUtils.listFiles(backupsDirectory, new NameFileFilter(filename), TrueFileFilter.TRUE)).get(0);
}
项目:kalibro
文件:RepositoryLoader.java
@Override
protected boolean isUpdatable(File directory) {
NameFileFilter nameFilter = new NameFileFilter(metadataDirectoryName());
return FileUtils.iterateFiles(directory, FalseFileFilter.INSTANCE, nameFilter).hasNext();
}
项目:buildhealth
文件:PseudoFiles.java
public Collection<File> getFilesByName(String... filenames) {
return getFiles(new NameFileFilter(filenames));
}
项目:codeforces-commons
文件:ZipUtil.java
/**
* Adds a directory to a ZIP-archive. Ignores ".svn" files and directories.
*
* @param source directory to compress, will not be added itself;
* source directory child files will be placed in the root of archive
* @param destination ZIP-archive
* @param level compression level (0-9)
* @throws IOException if any I/O-exception occured
*/
public static void zipExceptSvn(File source, File destination, int level) throws IOException {
zip(source, destination, level, new NameFileFilter(".svn", IOCase.SYSTEM));
}
项目:codeforces-commons
文件:ZipUtil.java
/**
* Adds a directory to a ZIP-archive and returns its bytes. Ignores ".svn" files and directories.
*
* @param source directory to compress, will not be added itself;
* source directory child files will be placed in the root of archive
* @param level compression level (0-9)
* @return ZIP-archive bytes
* @throws IOException if any I/O-exception occured
*/
public static byte[] zipExceptSvn(File source, int level) throws IOException {
return zip(source, level, new NameFileFilter(".svn", IOCase.SYSTEM));
}