Example usage for java.io FileFilter FileFilter

List of usage examples for java.io FileFilter FileFilter

Introduction

In this page you can find the example usage for java.io FileFilter FileFilter.

Prototype

FileFilter

Source Link

Usage

From source file:com.opengamma.util.test.DbTool.java

/**
 * Creates map from versions to sql scripts
 * @param dbCreateSuperDir the directory holding versioned scripts
 * @return the map//from   w  w w. j ava2  s .  c om
 */
private Map<File, Map<Integer, File>> getScripts(File dbCreateSuperDir, final Pattern scriptPattern) {
    ArgumentChecker.isTrue(dbCreateSuperDir.exists(),
            "Directory " + dbCreateSuperDir.getAbsolutePath() + " does not exist");
    ArgumentChecker.isTrue(dbCreateSuperDir.isDirectory(),
            "dbCreateSuperDir must be directory not a regular file");
    final File[] dbCreateScriptDirs = dbCreateSuperDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return matches(pathname.getName(), DATABASE_SCRIPT_FOLDER_PATTERN);
        }
    });
    //
    Map<File, Map<Integer, File>> dbFolder2versionedScripts = newHashMap();
    //
    for (File dbCreateScriptDir : dbCreateScriptDirs) {
        final File[] scripts = dbCreateScriptDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isFile() && matches(pathname.getName(), scriptPattern);
            }
        });
        //

        Map<Integer, File> versionedScripts = newHashMap();
        for (File script : scripts) {
            Integer version = getScriptVersion(script, scriptPattern);
            versionedScripts.put(version, script);
        }

        dbFolder2versionedScripts.put(dbCreateScriptDir, versionedScripts);

    }
    return dbFolder2versionedScripts;
}

From source file:com.enjoyxstudy.selenium.htmlsuite.MultiHTMLSuiteRunner.java

/**
 * @param testCaseDir//  ww  w. ja va 2s.  c  om
 * @return suiteFile
 * @throws IOException
 */
private File[] generateHTMLSutes(File testCaseDir) throws IOException {

    File suiteFile = null;
    if (!testCaseDir.isDirectory()) {
        suiteFile = testCaseDir;
        testCaseDir = testCaseDir.getParentFile();
    }

    if (!testCaseDir.exists()) {
        throw new IOException("Can't find Test Case dir:" + testCaseDir.getAbsolutePath());
    }

    ArrayList<File> testSuiteList = new ArrayList<File>();

    File[] testCaseFiles = collectTestCaseFiles(testCaseDir);
    if (testCaseFiles.length != 0) {

        if (suiteFile == null) {
            suiteFile = new File(testCaseDir, "generatedTestSuite.html");
        }
        generateHTMLSute(suiteFile, testCaseFiles, null);
        testSuiteList.add(suiteFile);

    } else {

        File[] childDirs = testCaseDir.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.isDirectory() && !pathname.isHidden();
            }
        });
        Arrays.sort(childDirs);

        for (File childDir : childDirs) {
            File childSuiteFile = new File(testCaseDir, childDir.getName() + ".html");
            generateHTMLSute(childSuiteFile, collectTestCaseFiles(childDir),
                    childDir.getName() + PATH_SEPARATOR);
            testSuiteList.add(childSuiteFile);
        }
    }

    log.info("Generate HTMLSuites total count[" + testSuiteList.size() + "]");

    return testSuiteList.toArray(new File[testSuiteList.size()]);
}

From source file:com.vaadin.tests.tb3.ScreenshotTB3Test.java

/**
 * Removes any old screenshots related to this test from the errors
 * directory before running the test//from  ww  w.java2  s.c o  m
 */
@Before
public void cleanErrorDirectory() {
    // Remove any screenshots for this test from the error directory
    // before running it. Leave unrelated files as-is
    File errorDirectory = new File(getScreenshotErrorDirectory());

    // Create errors directory if it does not exist
    if (!errorDirectory.exists()) {
        errorDirectory.mkdirs();
    }

    final String errorBase = getScreenshotErrorBaseName();
    File[] files = errorDirectory.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            String thisFile = pathname.getAbsolutePath();
            if (thisFile.startsWith(errorBase)) {
                return true;
            }
            return false;
        }
    });
    for (File f : files) {
        f.delete();
    }
}

From source file:common.ckplugins.utils.FileUtils.java

/**
 * Checks if folder has any subfolders but respects ACL and hideFolders
 * setting from configuration./* www.j  a  v  a  2 s.  com*/
 *
 * @param dirPath path to current folder.
 * @param dir current folder being checked. Represented by File object.
 * @param configuration configuration object.
 * @param resourceType name of resource type, folder is assignd to.
 * @param currentUserRole user role.
 * @return true if there are any allowed and non-hidden subfolders.
 */
public static Boolean hasChildren(String dirPath, File dir, IConfiguration configuration, String resourceType,
        String currentUserRole) {
    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };
    File[] subDirsList = dir.listFiles(fileFilter);

    if (subDirsList != null) {
        for (int i = 0; i < subDirsList.length; i++) {
            String subDirName = subDirsList[i].getName();

            if (!FileUtils.checkIfDirIsHidden(subDirName, configuration) && AccessControlUtil
                    .getInstance(configuration).checkFolderACL(resourceType, dirPath + subDirName,
                            currentUserRole, AccessControlUtil.CKFINDER_CONNECTOR_ACL_FOLDER_VIEW)) {
                return true;
            }
        }
    }
    return false;
}

From source file:net.unicon.demetrius.fac.filesystem.FsResourceFactory.java

protected long getNumFiles(IFolder r) {

    // assertions
    if (r == null) {
        throw new IllegalArgumentException("The given " + "resource must not be null.");
    }/*from www.ja  v a  2 s.c  o  m*/

    File f = new File(evaluateFsPath(dataSource, r));
    ;
    long numFiles = 0;

    File[] files = f.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.isFile();
        }
    });
    if (files != null) {
        numFiles = files.length;
    }
    return numFiles;
}

From source file:dk.netarkivet.harvester.harvesting.HarvestDocumentation.java

/**
 * Write harvestdetails to archive file(s).
 * This includes the order.xml, seeds.txt,
 * specific settings.xml for certain domains,
 * the harvestInfo.xml,/* w ww  . jav  a  2  s  . c  o m*/
 * All available reports (subset of HeritrixFiles.HERITRIX_REPORTS),
 * All available logs (subset of HeritrixFiles.HERITRIX_LOGS).
 *
 * @param jobID the given job Id
 * @param harvestID the id for the harvestdefinition, which created this job
 * @param crawlDir the directory where the crawljob took place
 * @param writer an MetadaFileWriter used to store the harvest configuration,
 *      and harvest logs and reports.
 * @param heritrixVersion the heritrix version used by the harvest. 
 * @throws ArgumentNotValid If null arguments occur
 * @return a list of files added to the archive file.
 */
private static List<File> writeHarvestDetails(long jobID, long harvestID, File crawlDir,
        MetadataFileWriter mdfw, String heritrixVersion) {
    List<File> filesAdded = new ArrayList<File>();

    // We will sort the files by URL
    TreeSet<MetadataFile> files = new TreeSet<MetadataFile>();

    // List heritrix files in the crawl directory
    File[] heritrixFiles = crawlDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File f) {
            return (f.isFile() && f.getName().matches(MetadataFile.HERITRIX_FILE_PATTERN));
        }
    });

    // Add files in the crawl directory
    for (File hf : heritrixFiles) {
        files.add(new MetadataFile(hf, harvestID, jobID, heritrixVersion));
    }
    // Generate an arcfiles-report.txt if configured to do so.
    boolean genArcFilesReport = Settings.getBoolean(HarvesterSettings.METADATA_GENERATE_ARCHIVE_FILES_REPORT);
    if (genArcFilesReport) {
        log.debug("Creating an arcfiles-report.txt");
        files.add(new MetadataFile(new ArchiveFilesReportGenerator(crawlDir).generateReport(), harvestID, jobID,
                heritrixVersion));
    } else {
        log.debug("Creation of the arcfiles-report.txt has been disabled" + "by the setting '"
                + HarvesterSettings.METADATA_GENERATE_ARCHIVE_FILES_REPORT + "'!");
    }

    // Add log files
    File logDir = new File(crawlDir, "logs");
    if (logDir.exists()) {
        File[] heritrixLogFiles = logDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return (f.isFile() && f.getName().matches(MetadataFile.LOG_FILE_PATTERN));
            }
        });
        for (File logFile : heritrixLogFiles) {
            files.add(new MetadataFile(logFile, harvestID, jobID, heritrixVersion));
            log.info("Found Heritrix log file " + logFile.getName());
        }
    } else {
        log.debug("No logs dir found in crawldir: " + crawlDir.getAbsolutePath());
    }

    // Check if exists any settings directory (domain-specific settings)
    // if yes, add any settings.xml hiding in this directory.
    // TODO Delete any settings-files found in the settings directory */
    File settingsDir = new File(crawlDir, "settings");
    if (settingsDir.isDirectory()) {
        Map<File, String> domainSettingsFiles = findDomainSpecificSettings(settingsDir);
        for (Map.Entry<File, String> entry : domainSettingsFiles.entrySet()) {

            File dsf = entry.getKey();
            String domain = entry.getValue();
            files.add(new MetadataFile(dsf, harvestID, jobID, heritrixVersion, domain));
        }
    } else {
        log.debug("No settings directory found in crawldir: " + crawlDir.getAbsolutePath());
    }

    // Write files in order to metadata archive file.
    for (MetadataFile mdf : files) {
        File heritrixFile = mdf.getHeritrixFile();
        String heritrixFileName = heritrixFile.getName();
        String mimeType = (heritrixFileName.endsWith(".xml") ? "text/xml" : "text/plain");
        if (mdfw.writeTo(heritrixFile, mdf.getUrl(), mimeType)) {
            filesAdded.add(heritrixFile);
        } else {
            log.warn("The Heritrix file '" + heritrixFile.getAbsolutePath()
                    + "' was not included in the metadata archivefile due to some error.");
        }
    }

    return filesAdded;
}

From source file:ca.weblite.xmlvm.XMLVM.java

/**
 * Finds all matching target files in the output directory for a given class.  This 
 * should find .h, .m, and .c files with with mangled names matching the class file
 * pattern./*ww  w  .jav  a 2s  .  c o m*/
 * @param clsFile
 * @param out List where matches will be added.
 */
private void findMatchingTargetFiles(final ClassFile clsFile, List<File> out) {
    if (clsFile == null) {
        return;
    }
    File[] files = getDest().listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            return pathname.getName().startsWith(clsFile.getcPrefix());
        }

    });

    for (File f : files) {
        out.add(f);
    }
}

From source file:com.taobao.android.builder.tasks.app.databinding.DataBindingRenameTask.java

/**
 * ?so//from   w  w w  . jav a  2s  . c o  m
 */
@TaskAction
void createAwbPackages() throws ExecutionException, InterruptedException {

    AtlasDependencyTree atlasDependencyTree = AtlasBuildContext.androidDependencyTrees.get(getVariantName());

    if (null == atlasDependencyTree) {
        return;
    }

    ExecutorServicesHelper executorServicesHelper = new ExecutorServicesHelper(taskName, getLogger(), 0);
    List<Runnable> runnables = new ArrayList<>();

    for (final AwbBundle awbBundle : atlasDependencyTree.getAwbBundles()) {

        runnables.add(new Runnable() {
            @Override
            public void run() {

                try {

                    File dataBindingClazzFolder = appVariantOutputContext.getVariantContext()
                            .getJAwbavaOutputDir(awbBundle);
                    String packageName = ManifestFileUtils
                            .getPackage(ManifestHelper.getOrgManifestFile(awbBundle.getAndroidLibrary()));
                    String appName = appVariantContext.getVariantConfiguration().getOriginalApplicationId();

                    //?
                    File dataMapperClazz = new File(dataBindingClazzFolder,
                            "android/databinding/DataBinderMapper.class");
                    if (!dataMapperClazz.exists()) {
                        throw new GradleException("missing datamapper class");
                    }

                    FileInputStream fileInputStream = new FileInputStream(dataMapperClazz);
                    ClassReader in1 = new ClassReader(fileInputStream);
                    ClassWriter cw = new ClassWriter(0);

                    Map<String, String> reMapping = new HashMap();
                    reMapping.put(appName.replace(".", "/") + "/BR", packageName.replace(".", "/") + "/BR");
                    RemappingClassAdapter remappingClassAdapter = new RemappingClassAdapter(cw,
                            new SimpleRemapper(reMapping));
                    in1.accept(remappingClassAdapter, 8);

                    ClassReader in2 = new ClassReader(cw.toByteArray());
                    ClassWriter cw2 = new ClassWriter(0);
                    Set<String> renames = new HashSet<String>();
                    renames.add("android/databinding/DataBinderMapper");
                    in2.accept(
                            new ClassRenamer(cw2, renames, packageName.replace(".", "/") + "/DataBinderMapper"),
                            8);

                    File destClass = new File(dataBindingClazzFolder,
                            packageName.replace(".", "/") + "/DataBinderMapper.class");
                    destClass.getParentFile().mkdirs();
                    FileOutputStream fileOutputStream = new FileOutputStream(destClass);
                    fileOutputStream.write(cw2.toByteArray());
                    IOUtils.closeQuietly(fileOutputStream);
                    IOUtils.closeQuietly(fileInputStream);

                    FileUtils.deleteDirectory(new File(dataBindingClazzFolder, "android/databinding"));
                    FileUtils.deleteDirectory(new File(dataBindingClazzFolder, "com/android/databinding"));

                    File appDir = new File(dataBindingClazzFolder, appName.replace(".", "/"));
                    if (appDir.exists()) {

                        File[] files = appDir.listFiles(new FileFilter() {
                            @Override
                            public boolean accept(File pathname) {
                                return pathname.isFile() && !pathname.isDirectory();
                            }
                        });

                        for (File tmp : files) {
                            FileUtils.forceDelete(tmp);
                        }

                    }

                } catch (Throwable e) {
                    e.printStackTrace();
                    throw new GradleException("package awb failed");
                }

            }
        });

    }

    executorServicesHelper.execute(runnables);

}

From source file:com.hp.flume.plugins.spoolsource.ReliableSpoolingFileEventReader.java

/**
 * Returns the next file to be consumed from the chosen directory. If the
 * directory is empty or the chosen file is not readable, this will return
 * an absent option. If the {@link #consumeOrder} variable is
 * {@link ConsumeOrder#OLDEST} then returns the oldest file. If the
 * {@link #consumeOrder} variable is {@link ConsumeOrder#YOUNGEST} then
 * returns the youngest file. If two or more files are equally old/young,
 * then the file name with lower lexicographical value is returned. If the
 * {@link #consumeOrder} variable is {@link ConsumeOrder#RANDOM} then
 * returns any arbitrary file in the directory.
 *///from   w w  w  .java  2s . com
private Optional<FileInfo> getNextFile() {
    /* Filter to exclude finished or hidden files */
    FileFilter filter = new FileFilter() {
        public boolean accept(File candidate) {
            String fileName = candidate.getName();
            // lucheng
            // int date =
            // String regEx = "[a-zA-Z]+_\\d{4}_\\d{2}_(\\d{2})";
            // Pattern pat = Pattern.compile(regEx);
            //
            // Matcher mat = pat.matcher(fileName);
            // mat.find();
            // int fileDate = Integer.parseInt(mat.group(1));
            //            Matcher mat = Pattern.compile(
            //                  "[a-zA-Z]+_\\d{4}_\\d{2}_(\\d{2})").matcher(fileName);
            //            mat.find();
            Long time = candidate.lastModified();
            Date dt = new Date();
            dt.setTime(time);
            int modifiedTime = dt.getDate();
            if ((candidate.isDirectory()) || (fileName.endsWith(completedSuffix)) || (fileName.startsWith("."))
                    || ignorePattern.matcher(fileName).matches()
                    || new Date().getDate() == modifiedTime/*Integer.parseInt(mat
                                                           .group(1))*/) {
                return false;
            }
            return true;
        }
    };
    List<File> candidateFiles = Arrays.asList(spoolDirectory.listFiles(filter));
    if (candidateFiles.isEmpty()) { // No matching file in spooling directory.
        return Optional.absent();
    }

    File selectedFile = candidateFiles.get(0); // Select the first random
    // file.
    if (consumeOrder == ConsumeOrder.RANDOM) { // Selected file is random.
        return openFile(selectedFile);
    } else if (consumeOrder == ConsumeOrder.YOUNGEST) {
        for (File candidateFile : candidateFiles) {
            long compare = selectedFile.lastModified() - candidateFile.lastModified();
            if (compare == 0) { // ts is same pick smallest lexicographically.
                selectedFile = smallerLexicographical(selectedFile, candidateFile);
            } else if (compare < 0) { // candidate is younger (cand-ts > selec-ts)
                selectedFile = candidateFile;
            }
        }
    } else { // default order is OLDEST
        for (File candidateFile : candidateFiles) {
            long compare = selectedFile.lastModified() - candidateFile.lastModified();
            if (compare == 0) { // ts is same pick smallest lexicographically.
                selectedFile = smallerLexicographical(selectedFile, candidateFile);
            } else if (compare > 0) { // candidate is older (cand-ts < selec-ts).
                selectedFile = candidateFile;
            }
        }
    }

    return openFile(selectedFile);
}

From source file:net.unicon.demetrius.fac.filesystem.FsResourceFactory.java

protected long getNumFolders(IFolder r) {

    // Assertions
    if (r == null) {
        throw new IllegalArgumentException("The given " + "resource must not be null.");
    }//from ww w.  j  a va  2 s  .  c om

    File f = new File(evaluateFsPath(dataSource, r));
    int numFolders = 0;

    File[] files = f.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    });
    if (files != null) {
        numFolders = files.length;
    }
    return numFolders;
}