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:atg.tools.dynunit.test.AtgDustCase.java

private void preCopyingOfConfigurationFiles(final String[] srcDirs, final String excludes[])
        throws IOException {
    boolean isDirty = false;
    final FileFilter filter = new FileFilter() {
        @Override/*  w w w.  ja v a2  s  .co m*/
        public boolean accept(final File file) {
            return ArrayUtils.contains(excludes, file.getName());
        }
    };
    // TODO: use FileUtils.copyDirectory, etc.
    for (final String src : srcDirs) {
        final Collection<File> srcFiles = FileUtils.listFiles(new File(src), null, true);
        for (final File file : srcFiles) {
            if (!Arrays.asList(excludes == null ? new String[] {} : excludes).contains(file.getName())
                    && !file.getPath().contains(".svn") && file.isFile()) {
                if (CONFIG_FILES_TIMESTAMPS.get(file.getPath()) != null
                        && file.lastModified() == CONFIG_FILES_TIMESTAMPS.get(file.getPath())) {
                } else {
                    CONFIG_FILES_TIMESTAMPS.put(file.getPath(), file.lastModified());
                    isDirty = true;
                }
            }
        }
    }
    if (isDirty) {
        logger.debug("Config files timestamps map is dirty an will be re serialized");

        FileUtil.serialize(TIMESTAMP_SER, CONFIG_FILES_TIMESTAMPS);
    }

    FileUtil.setConfigFilesTimestamps(CONFIG_FILES_TIMESTAMPS);
    FileUtil.setConfigFilesGlobalForce(CONFIG_FILES_GLOBAL_FORCE);
}

From source file:com.ms.commons.test.classloader.IntlTestURLClassPath.java

private static void copyDirectoryTo(File dirFrom, File dirTo) throws IOException {
    if (dirFrom.exists() && dirFrom.isDirectory()) {
        FileUtil.copyDirectory(dirFrom, dirTo, new FileFilter() {

            public boolean accept(File pathname) {
                return (!pathname.toString().contains(".svn"));
            }/*from ww w.  ja  va 2 s. c  om*/
        });
    }
}

From source file:org.ops4j.pax.url.mvn.internal.AetherBasedResolver.java

/**
 * For the given parent, we find all child files, and then
 * sort those files by their name (not absolute path).
 *
 * The sorted list is returned, or an empty list if listFiles returns
 * null.//from   w  w  w .j  a va2s  .  c  o m
 * @param parent A non-null parent File for which you want to get the sorted list of child directories.
 * @return The alphabetically sorted list of files, or an empty list if parent.listFiles() returns null.
 */
private static File[] getSortedChildDirectories(File parent) {
    File[] files = parent.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    });
    if (files == null) {
        return new File[0];
    }
    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    return files;
}

From source file:fr.ens.biologie.genomique.eoulsan.it.IT.java

/**
 * Create the expected data test directory.
 * @return expected data directory for the test
 * @throws EoulsanException if the existing directory is empty
 * @throws IOException if the source test directory doesn't exist
 *//*from  ww  w . j  a  v a  2 s. c o m*/
private File retrieveExpectedDirectory() throws EoulsanException, IOException {

    checkExistingDirectoryFile(this.testDataDirectory, "output data parent directory");

    // Find directory start with expected
    final File[] expectedDirectories = this.testDataDirectory.listFiles(new FileFilter() {

        @Override
        public boolean accept(final File pathname) {
            return pathname.getName().startsWith("expected");
        }
    });

    // Execute test, expected must be existing
    if (expectedDirectories.length == 0 && !this.generateExpectedDirectoryTestData) {
        throw new EoulsanException(this.testName + ": no expected directory found to launch test in "
                + this.testDataDirectory.getAbsolutePath());
    }

    // No test directory found
    if (expectedDirectories.length == 0) {

        // Build expected directory name
        if (this.generateExpectedDirectoryTestData) {

            // Retrieve command line from test configuration
            final String cmdToGetApplicationVersion = this.testConf
                    .getProperty(ITFactory.COMMAND_TO_GET_APPLICATION_VERSION_CONF_KEY);

            final String versionExpectedApplication = this.itSuite
                    .retrieveVersionApplication(cmdToGetApplicationVersion, this.applicationPath);

            return new File(this.testDataDirectory, "/expected_"
                    + (this.manualGenerationExpectedData ? "UNKNOWN" : versionExpectedApplication));
        }
    }

    // One test directory found
    if (expectedDirectories.length > 1) {
        throw new EoulsanException(this.testName + ": more one expected directory found in "
                + this.testDataDirectory.getAbsolutePath());
    }

    if (!expectedDirectories[0].isDirectory()) {
        throw new EoulsanException(
                this.testName + ": no expected directory found in " + this.testDataDirectory.getAbsolutePath());
    }

    // Return expected data directory
    return expectedDirectories[0];

}

From source file:com.door43.translationstudio.core.TargetTranslationMigrator.java

/**
 * Merges chunks found in a target translation Project that do not exist in the source translation
 * to a sibling chunk so that no data is lost.
 * @param targetTranslationDir/*from  w  ww .  ja v  a 2s .c  om*/
 * @return
 */
private static boolean migrateChunkChanges(File targetTranslationDir) {
    // TRICKY: calling the AppContext here is bad practice, but we'll deprecate this soon anyway.
    final Library library = AppContext.getLibrary();
    final SourceTranslation sourceTranslation = library
            .getDefaultSourceTranslation(targetTranslationDir.getName(), "en");
    if (sourceTranslation == null) {
        // if there is no source we are done
        return true;
    }
    File[] chapterDirs = targetTranslationDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && !pathname.getName().equals(".git")
                    && !pathname.getName().equals("00"); // 00 contains project title translations
        }
    });
    for (File cDir : chapterDirs) {
        mergeInvalidChunksInChapter(library, new File(targetTranslationDir, "manifest.json"), sourceTranslation,
                cDir);
    }
    return true;
}

From source file:com.funambol.foundation.util.FileSystemDAOHelper.java

/**
 * We are interested in tmp files older than one day
 * @return the FileFilter for tmp files older than one day
 *//*from  w  w  w.  jav  a2 s .c  om*/
private FileFilter getFilterForOldTmpFiles() {
    final long cutoff = System.currentTimeMillis() - (24 * 60 * 60 * 1000);

    FileFilter filter = new FileFilter() {

        public boolean accept(File file) {
            return (file.getName().endsWith(FileDataObjectNamingStrategy.TMP_FILE_SUFFIX)
                    && file.lastModified() < cutoff);
        }
    };

    return filter;
}

From source file:com.isomorphic.maven.packaging.Distribution.java

/**
 * Extract the relevant contents from each file in the distribution.  Additionally creates ZIP/JAR
 * files from specified resources (e.g., javadoc).
 * /*ww w .  j  a  v  a2s .c o m*/
 * @param to The directory to which each file should be extracted.
 * @throws IOException
 */
public void unpack(File to) throws IOException {

    outer: for (File file : files) {

        String ext = FilenameUtils.getExtension(file.getName()).toUpperCase();

        //copy uncompressed files to target, renaming as necessary per 'contents' configuration
        if (!"ZIP".equals(ext)) {
            for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) {
                AntPathMatcherFilter filter = filterEntry.getValue();
                if (filter.accept(file.getName())) {
                    File target = FileUtils.getFile(to,
                            ArchiveUtils.rewritePath(file.getName(), filterEntry.getKey()));
                    FileUtils.copyFile(file, target);
                    LOGGER.debug("Copied file '{}' to file '{}'", file.getName(), target.getAbsolutePath());
                    continue outer;
                }
            }
            FileUtils.copyFileToDirectory(file, new File(to, "lib"));
            continue outer;
        }

        //otherwise extract contents (again renaming / relocating contents as necessary)
        ZipFile zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zip.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) {
                AntPathMatcherFilter filter = filterEntry.getValue();
                if (filter.accept(entry.getName())) {
                    File target = FileUtils.getFile(to,
                            ArchiveUtils.rewritePath(entry.getName(), filterEntry.getKey()));
                    FileUtils.copyInputStreamToFile(zip.getInputStream(entry), target);
                    LOGGER.debug("Copied input stream to file '{}'", target.getAbsolutePath());
                }
            }
        }
        zip.close();
    }

    /*
     * Create any number of assemblies by dropping their resources here.
     * Each subdirectory will get zipped up and then deleted
     */
    File assembliesDir = new File(to, "assembly");

    @SuppressWarnings("unchecked")
    Collection<File> assemblies = CollectionUtils.arrayToList(assembliesDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File arg0) {
            return arg0.isDirectory();
        }
    }));
    for (File assembly : assemblies) {
        String name = FilenameUtils.getBaseName(assembly.getName());
        LOGGER.debug("Copying resources for assembly '{}'", name);
        ArchiveUtils.zip(assembly, FileUtils.getFile(assembliesDir, name + ".zip"));
        FileUtils.deleteQuietly(assembly);
    }

    LOGGER.debug("Repackaging Javadoc...");
    File docLib = new File(to, "doc/lib");

    //TODO these paths should probably all be stuck in some constant
    File client = FileUtils.getFile(to, "doc/api/client");
    if (client.exists()) {
        ArchiveUtils.jar(client, new File(docLib, "smartgwt-javadoc.jar"));
    }

    File server = FileUtils.getFile(to, "doc/api/server");
    if (server.exists()) {
        ArchiveUtils.jar(server, new File(docLib, "isomorphic-javadoc.jar"));
    }
}

From source file:com.photon.phresco.impl.DrupalApplicationProcessor.java

public List<File> getSqlFolders(File sqlFolder) throws PhrescoException {
    List<File> sqlFolders = null;
    try {//from   ww  w .  j ava  2  s  . c o m
        FilenameFilter mysqlDirectoryFilter = new FilenameFilter() {
            public boolean accept(File directory, String fileName) {
                return directory.isDirectory() && MYSQL.equalsIgnoreCase(fileName);
            }
        };

        FileFilter directoryFilter = new FileFilter() {
            public boolean accept(File directory) {
                return directory.isDirectory();
            }
        };

        File[] dirs = sqlFolder.listFiles(mysqlDirectoryFilter);
        for (File dir : dirs) {
            File[] versionFiles = dir.listFiles(directoryFilter);
            sqlFolders = Arrays.asList(versionFiles);
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return sqlFolders;
}

From source file:com.microsoft.tfs.util.FileHelpers.java

public static boolean deleteDirectory(final File directory) {
    if (!directory.exists() || !directory.isDirectory()) {
        return false;
    }//from w  w  w . j  a  v  a2  s . c o  m

    /* Depth-first directory traversal */
    final File[] subdirectories = directory.listFiles(new FileFilter() {
        @Override
        public boolean accept(final File file) {
            return file.isDirectory();
        }
    });

    for (final File subdirectory : subdirectories) {
        if (!deleteDirectory(subdirectory)) {
            return false;
        }
    }

    final File[] files = directory.listFiles(new FileFilter() {
        @Override
        public boolean accept(final File file) {
            return file.isFile();
        }
    });

    for (final File file : files) {
        if (!file.delete()) {
            return false;
        }
    }

    return directory.delete();
}

From source file:org.atomserver.core.filestore.FileBasedContentStorage.java

/**
 * removes all of the files, except the file passed in
 * No more trash bin, files get deleted/*from   w ww.  j  a  v  a2s. c om*/
 * NOTE: this method does not throw an Exception. Instead, it simply logs errors and moves on.
 *
 * @param thisRev    the file pointint at the current revision
 * @param descriptor the entry that relates to the content
 */
private void cleanupExcessFiles(final File thisRev, final EntryDescriptor descriptor) {

    String fullPath = FilenameUtils.getFullPath(thisRev.getAbsolutePath());
    File baseDir = new File(fullPath);
    if (log.isTraceEnabled()) {
        log.trace("%> cleaning up excess files at " + baseDir + " based on " + thisRev);
    }

    try {

        // get a file pointer at the previous revision of the file -- we DON'T want to delete it
        final File oneRevBack = findExistingEntryFile(descriptor, 1);

        // the set of directories to clean is the directories that contain (A) the previous
        // revision, which may or may not be the same as the current rev, and (B) the one two
        // revisions back, which may or may not be the same as the previous rev
        Set<File> directoriesToClean = new HashSet<File>(2);

        // if there was a previous rev
        if (oneRevBack != null) {
            // add it's dir to the ones to clean
            directoriesToClean.add(oneRevBack.getParentFile());
            // and if the revision is greater than 1
            if (descriptor.getRevision() > 1) {
                // then two revs back is a reasonable thing to ask for...
                File twoRevsBack = findExistingEntryFile(descriptor, 2);
                // and if it exists, add its parent to the ones to clean
                if (twoRevsBack != null) {
                    directoriesToClean.add(twoRevsBack.getParentFile());
                }
            }
        }

        // list out all of the files in the directory that are (a) files, and (b) not one of
        // the last two revisions
        for (File directoryToClean : directoriesToClean) {
            final File[] toDelete = directoryToClean.listFiles(new FileFilter() {
                public boolean accept(File fileToCheck) {

                    return fileToCheck != null && fileToCheck.exists() && fileToCheck.isFile()
                            && fileToCheck.canRead() && fileToCheck.canWrite() && !fileToCheck.isHidden()
                            && !thisRev.equals(fileToCheck)
                            && (oneRevBack == null || !oneRevBack.equals(fileToCheck));

                }
            });

            // if there's anything to delete...
            if (toDelete != null && toDelete.length > 0) {

                for (File file : toDelete) {

                    //delete the file
                    if (log.isTraceEnabled()) {
                        log.trace("deleting file" + file.getName());
                    }

                    FileUtils.forceDelete(file);
                }
                cleanUpToCollection(descriptor, directoryToClean);
            }
        }
    } catch (Exception e) {
        // if there was any exception in the move (including the one we might have just thrown
        // above) then we should log it
        log.error("Error when cleaning up dir [" + baseDir + "] when writing file (" + thisRev + ")", e);
    }
}