Example usage for java.io FileFilter accept

List of usage examples for java.io FileFilter accept

Introduction

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

Prototype

boolean accept(File pathname);

Source Link

Document

Tests whether or not the specified abstract pathname should be included in a pathname list.

Usage

From source file:com.zimbra.kabuki.tools.img.ImageMerger.java

private static File[] listFiles(File[] all, FileFilter filter) {
    List<File> list = new LinkedList<File>();
    for (File file : all) {
        if (filter.accept(file))
            list.add(file);//from   ww w. j  av  a 2  s.com
    }
    return list.toArray(new File[] {});
}

From source file:org.schemaspy.util.ResourceWriter.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination path.//  ww w . ja v a2 s.  c  om
 *
 * @param jarConnection
 * @param destPath destination file or directory
 */
private static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath, FileFilter filter) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName + "/")) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destPath, filename);

                if (jarEntry.isDirectory()) {
                    FileUtils.forceMkdir(currentFile);
                } else {
                    if (filter == null || filter.accept(currentFile)) {
                        InputStream is = jarFile.getInputStream(jarEntry);
                        OutputStream out = FileUtils.openOutputStream(currentFile);
                        IOUtils.copy(is, out);
                        is.close();
                        out.close();
                    }
                }
            }
        }
    } catch (IOException e) {
        LOGGER.warn(e.getMessage(), e);
    }
}

From source file:org.omegat.util.FileUtil.java

/**
 * Internal find method, which calls himself recursively.
 * // w  ww  .ja  v  a2  s  .com
 * @param dir
 *            directory to start find
 * @param filter
 *            filter for found files
 * @param result
 *            list of filtered found files
 */
private static void findFiles(final File dir, final FileFilter filter, final List<File> result,
        final Set<String> knownDirs) {
    String curr_dir;
    try {
        // check for recursive
        curr_dir = dir.getCanonicalPath();
        if (!knownDirs.add(curr_dir)) {
            return;
        }
    } catch (IOException ex) {
        Log.log(ex);
        return;
    }
    File[] list = dir.listFiles();
    if (list != null) {
        for (File f : list) {
            if (f.isDirectory()) {
                findFiles(f, filter, result, knownDirs);
            } else {
                if (filter.accept(f)) {
                    result.add(f);
                }
            }
        }
    }
}

From source file:org.clickframes.testframes.TestPreparationUtil.java

/**
 * Use this advanced interface to only run tests approved by this filter
 *
 * @param appspec/*from   ww w  .  j av  a  2s.com*/
 * @param filenameFilter
 *
 * @throws Exception
 *
 * @author Vineet Manohar
 */
@SuppressWarnings("unchecked")
static void prepareAllTestSuites(final TestProfile testProfile, Techspec techspec, Appspec appspec,
        String filterName, final FileFilter fileFilter) throws Exception {
    File suiteSourceDirectory = new File(
            "src" + File.separator + "test" + File.separator + "selenium" + File.separator + "clickframes");

    File suiteTargetDirectory = new File(
            "target" + File.separator + "clickframes" + File.separator + "selenium" + File.separator
                    + ClickframeUtils.convertSlashToPathSeparator(filterName) + File.separator + "tests");

    // copy selected tests from source to suite directory
    FileUtils.deleteDirectory(suiteTargetDirectory);
    suiteTargetDirectory.mkdirs();

    // select for suites which match the given pattern

    IOFileFilter regexIOFilter = new IOFileFilter() {
        @Override
        public boolean accept(File file) {
            return fileFilter.accept(file);
        }

        @Override
        public boolean accept(File dir, String name) {
            return fileFilter.accept(new File(dir, name));
        }
    };

    Collection<File> filesFound;

    if (suiteSourceDirectory.exists() && suiteSourceDirectory.isDirectory()) {
        filesFound = FileUtils.listFiles(suiteSourceDirectory, regexIOFilter,
                FileFilterUtils.makeSVNAware(FileFilterUtils.makeCVSAware(TrueFileFilter.INSTANCE)));
    } else {
        filesFound = new ArrayList<File>();
    }

    log.info(filesFound.size() + " files found for " + fileFilter + " => " + filesFound);

    Map<File, String> listOfFlattenedSuites = new LinkedHashMap<File, String>();

    StepFilter profileStepFilter = new StepFilter() {
        @Override
        public SeleniumTestStep filter(SeleniumTestCase testCase, SeleniumTestStep testStep) {
            // if testCase name is "applicationInitialize.html", apply
            // substitution vars

            if (testCase.getFile().getName().equals("applicationInitialize.html")) {
                String target = testStep.getTarget();

                // apply profile
                target = VelocityHelper.resolveText(testProfile.getProperties(), target);

                // modify step
                testStep.setTarget(target);
            }

            return testStep;
        }
    };

    for (File sourceSuiteFile : filesFound) {
        int counter = 1;

        File targetSuiteFile;
        do {
            // name is 'some-suite.html'
            // remove suite - as multisuite runner uses suite as a keyword
            targetSuiteFile = new File(suiteTargetDirectory, sourceSuiteFile.getName()
                    .replaceAll(".html$", counter++ + ".html").replaceAll("suite", ""));
        } while (targetSuiteFile.exists());

        validateFilePathLength(targetSuiteFile);

        // flatten
        SeleniumUtils.flattenTestSuiteToTestCase(sourceSuiteFile, targetSuiteFile, profileStepFilter);

        // store names
        listOfFlattenedSuites.put(targetSuiteFile, getRelativePath(sourceSuiteFile.getAbsolutePath()));
    }

    // write one master suite to suite target directory
    File masterTestSuite = new File(suiteTargetDirectory, "master-test-suite.html");
    SeleniumUtils.testCasesToTestSuite(listOfFlattenedSuites, masterTestSuite);

    File resultsDir = new File(
            "target" + File.separator + "clickframes" + File.separator + "selenium" + File.separator
                    + ClickframeUtils.convertSlashToPathSeparator(filterName) + File.separator + "results");

    FileUtils.deleteDirectory(resultsDir);

    resultsDir.mkdirs();

    // prepare user extensions
    File userExtensionsFile = new File(System.getProperty("java.io.tmpdir"), "user-extensions.js");
    if (userExtensionsFile.exists()) {
        userExtensionsFile.delete();
    }
}

From source file:jlib.polling.MaskFileFilter.java

public boolean accept(File pathname) {
    if (m_arrMaskFilters == null)
        return true;

    for (int n = 0; n < m_arrMaskFilters.size(); n++) {
        FileFilter maskFilter = m_arrMaskFilters.get(n);
        if (maskFilter.accept(pathname))
            return true;
    }// ww  w  .  j  a  v  a2  s  .  co  m
    return false;
}

From source file:org.olat.core.util.FileUtils.java

/**
 * Copy a file from one spot on hard disk to another. Will create any target dirs if necessary.
 * /*from  www  .  j  a  va2s .  com*/
 * @param sourceFile file to copy on local hard disk.
 * @param targetDir new file to be created on local hard disk.
 * @param move
 * @param filter file filter or NULL if no filter applied
 * @return true if the copy was successful.
 */
public static boolean copyFileToDir(File sourceFile, File targetDir, boolean move, FileFilter filter,
        String wt) {
    try {
        // copy only if filter allows. filtered items are considered a success
        // and not a failure of the operation
        if (filter != null && !filter.accept(sourceFile))
            return true;

        // catch if source is directory by accident
        if (sourceFile.isDirectory()) {
            return copyDirToDir(sourceFile, targetDir, move, filter, wt);
        }

        // create target directories
        targetDir.mkdirs(); // don't check for success... would return false on
        // existing dirs
        if (!targetDir.isDirectory())
            return false;
        File targetFile = new File(targetDir, sourceFile.getName());

        // catch move/copy of "same" file -> buggy under Windows.
        if (sourceFile.getCanonicalPath().equals(targetFile.getCanonicalPath()))
            return true;
        if (move) {
            // try to rename it first - operation might only be successful on a local filesystem!
            if (sourceFile.renameTo(targetFile))
                return true;
            // it failed, so continue with copy code!
        }

        bcopy(sourceFile, targetFile, "copyFileToDir:" + wt);

        if (move) {
            // to finish the move accross different filesystems we need to delete the source file
            sourceFile.delete();
        }
    } catch (IOException e) {
        log.error("Could not copy file::" + sourceFile.getAbsolutePath() + " to dir::"
                + targetDir.getAbsolutePath(), e);
        return false;
    }
    return true;
}

From source file:org.geowebcache.util.FileUtils.java

/**
 * Traverses the directory denoted by {@code path} recursively and calls {@code filter.accept}
 * on each child, files first, subdirectories next.
 * <p>/*from  w  ww .j a  va  2 s . co  m*/
 * For a child directory to be traversed, the {@code filter.accept(File)} method shall have
 * returned {@code true}, otherwise the child directory is skipped.
 * </p>
 * <p>
 * This method guarantees that {@code filter.accept} will be called first for all files in a
 * directory and then for all it's sub directories.
 * <p>
 * 
 * @param path
 * @param filter
 *            used to implement the visitor pattern. The accept method may contain any desired
 *            logic, it will be called for all files and directories inside {@code path},
 *            recursively
 */
public static void traverseDepth(final File path, final FileFilter filter) {
    if (path == null) {
        throw new NullPointerException("path");
    }
    if (filter == null) {
        throw new NullPointerException("filter");
    }
    if (!path.exists() || !path.isDirectory() || !path.canRead()) {
        throw new IllegalArgumentException(
                path.getAbsolutePath() + " either does not exist, or is not a readable directory");
    }
    // Use path.list() instead of path.listFiles() to avoid the simultaneous creation of
    // thousands of File objects as well as its String objects for the path name. Faster and
    // less resource intensive
    String[] fileNames = path.list();
    List<File> subDirectories = new ArrayList<File>();

    File file;
    for (int i = 0; i < fileNames.length; i++) {
        file = new File(path, fileNames[i]);
        if (file.isDirectory()) {
            subDirectories.add(file);
        }
        filter.accept(file);
    }
    if (subDirectories.size() > 0) {
        for (File subdir : subDirectories) {
            boolean accepted = filter.accept(subdir);
            if (accepted && subdir.isDirectory()) {
                traverseDepth(subdir, filter);
            }
        }
    }
}

From source file:org.openflexo.toolbox.FileUtils.java

public static int countFilesInDirectory(File directory, boolean recursive, FileFilter fileFilter) {
    if (!directory.isDirectory() || !directory.exists()) {
        return -1;
    }/*from ww w.  ja  va2s  . co m*/
    File[] files = directory.listFiles();
    int count = 0;
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        if (fileFilter != null && !fileFilter.accept(file)) {
            continue;
        }
        if (file.isDirectory()) {
            if (recursive) {
                count += countFilesInDirectory(file, recursive);
            }
        } else {
            count++;
        }
    }
    return count;
}

From source file:org.eclipse.internal.xpand2.pr.util.GenericFileFilter.java

/**
 * Accept all files and directories not included in the ignore list.
 * @param file File to check/*  w  w w  .j  a  v a 2s.c  o  m*/
 * @return <code>true</code> when the file is accepted by the filter.
 */
public boolean accept(final File file) {
    if (!file.isFile() && !file.isDirectory())
        return false;

    for (final Iterator<GlobbingFileFilter> iter = fileFilters.iterator(); iter.hasNext();) {
        final FileFilter ffilter = iter.next();
        if (ffilter.accept(file)) {
            if (log.isDebugEnabled()) {
                log.debug("File " + file + " excluded (pattern: " + ffilter + ").");
            }
            return false;
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("File " + file + " included.");
    }

    return true;
}

From source file:com.ms.commons.test.common.FileUtil.java

private static void doCopyDirectory(File srcDir, File destDir, boolean preserveFileDate, FileFilter filter)
        throws IOException {
    if (destDir.exists()) {
        if (destDir.isDirectory() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }/* ww w.  ja  v  a  2 s. co m*/
    } else {
        if (destDir.mkdirs() == false) {
            throw new IOException("Destination '" + destDir + "' directory cannot be created");
        }
        if (preserveFileDate) {
            destDir.setLastModified(srcDir.lastModified());
        }
    }
    if (destDir.canWrite() == false) {
        throw new IOException("Destination '" + destDir + "' cannot be written to");
    }
    // recurse
    File[] files = srcDir.listFiles();
    if (files == null) { // null if security restricted
        throw new IOException("Failed to list contents of " + srcDir);
    }
    for (int i = 0; i < files.length; i++) {
        if (filter.accept(files[i])) {
            File copiedFile = new File(destDir, files[i].getName());
            if (files[i].isDirectory()) {
                doCopyDirectory(files[i], copiedFile, preserveFileDate, filter);
            } else {
                doCopyFile(files[i], copiedFile, preserveFileDate);
            }
        }
    }
}