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:ch.entwine.weblounge.contentrepository.impl.fs.FileSystemContentRepository.java

/**
 * {@inheritDoc}/* www.j  av a2 s . c  om*/
 * 
 * @see ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository#listResources()
 */
@Override
protected Collection<ResourceURI> listResources() throws IOException {

    List<ResourceURI> uris = new ArrayList<ResourceURI>();

    // Add all known resource types to the index
    for (ResourceSerializer<?, ?> serializer : getSerializers()) {

        // Temporary path for rebuilt site
        String resourceType = serializer.getType().toLowerCase();
        String resourceDirectory = resourceType + "s";
        String homePath = UrlUtils.concat(repositorySiteRoot.getAbsolutePath(), resourceDirectory);
        File resourcesRootDirectory = new File(homePath);
        if (!resourcesRootDirectory.isDirectory() || resourcesRootDirectory.list().length == 0) {
            logger.debug("No {}s found to index", resourceType);
            continue;
        }

        try {
            Stack<File> u = new Stack<File>();
            u.push(resourcesRootDirectory);
            while (!u.empty()) {
                File dir = u.pop();
                File[] files = dir.listFiles(new FileFilter() {
                    public boolean accept(File path) {
                        if (path.getName().startsWith("."))
                            return false;
                        return path.isDirectory() || path.getName().endsWith(".xml");
                    }
                });
                if (files == null || files.length == 0)
                    continue;
                for (File f : files) {
                    if (f.isDirectory()) {
                        u.push(f);
                    } else {
                        long version = Long.parseLong(f.getParentFile().getName());
                        String id = f.getParentFile().getParentFile().getName();
                        ResourceURI uri = new ResourceURIImpl(resourceType, getSite(), null, id, version);

                        uris.add(uri);
                    }
                }
            }
        } catch (Throwable t) {
            logger.error("Error reading available uris from file system: {}", t.getMessage());
            throw new IOException(t);
        }

    }

    return uris;
}

From source file:fr.msch.wissl.server.Library.java

private void listFiles(File dir, Queue<File> acc) throws IOException, InterruptedException {
    if (stop)/*from www . ja va  2 s .co  m*/
        throw new InterruptedException();

    if (!dir.isDirectory()) {
        throw new IOException(dir.getAbsolutePath() + " is not a directory");
    }

    File[] children = dir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            if (pathname.getAbsolutePath().length() > 254) {
                return false;
            }

            String name = pathname.getName().toLowerCase();
            for (String format : Config.getMusicFormats()) {
                if (name.endsWith(format)) {
                    return true;
                }
            }
            if (pathname.isDirectory()) {
                return true;
            }
            return false;
        }
    });

    for (File child : children) {
        if (child.isDirectory()) {
            listFiles(child, acc);
        } else {
            acc.add(child);
            songsTodo++;
        }
    }
}

From source file:edu.duke.igsp.gkde.Main.java

private static File[] getFiles(String directory, String[] files) {

    File[] inputFiles = null;/*from  w w  w  . j a v  a2  s .co m*/

    if (directory != null) {
        File dir = new File(directory);
        if (!dir.exists() || !dir.isDirectory()) {
            System.out.println("Directory parameter " + directory + " does not exist or is not a directory.");
            System.exit(1);
        }
        if (files.length == 0) {
            inputFiles = dir.listFiles(new FileFilter() {
                public boolean accept(File f) {
                    return !f.isHidden() && f.isFile();
                }
            });
        }
    } else {
        directory = System.getProperty("user.dir");
    }

    if (inputFiles == null) {
        inputFiles = new File[files.length];
        for (int i = 0; i < files.length; ++i) {
            File f = new File(files[i]);
            boolean exists = false;
            if (!(exists = f.exists())) {
                f = new File(directory, files[i]);
                exists = f.exists();
            }
            if (!exists) {
                System.out.println("Input file " + files[i] + " does not exist.");
                System.exit(1);
            }
            inputFiles[i] = f;
        }
    }

    return inputFiles;
}

From source file:de.blizzy.documentr.page.PageStore.java

private List<File> listPageFilesInDir(File dir, boolean recursive) {
    List<File> result = Lists.newArrayList();
    if (dir.isDirectory()) {
        FileFilter filter = new FileFilter() {
            @Override/*  w w  w  .  j  av a 2s. c om*/
            public boolean accept(File pathname) {
                return (pathname.isFile() && pathname.getName().endsWith(DocumentrConstants.PAGE_SUFFIX))
                        || pathname.isDirectory();
            }
        };
        File[] files = dir.listFiles(filter);
        for (File file : files) {
            if (file.isDirectory()) {
                if (recursive) {
                    result.addAll(listPageFilesInDir(file, true));
                }
            } else {
                result.add(file);
            }
        }
    }
    return result;
}

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

/**
 * @param testCaseDir//  www  .j  av  a  2  s .  com
 * @return testCase files
 */
private File[] collectTestCaseFiles(File testCaseDir) {

    File[] testCaseFiles = testCaseDir.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.isFile() && TEST_CASE_REGEXP.matcher(pathname.getName()).matches();
        }
    });
    Arrays.sort(testCaseFiles);
    return testCaseFiles;
}

From source file:com.edgenius.wiki.search.service.IndexServiceImpl.java

public void cleanIndexes(final IndexRebuildListener listener) {
    //code move to AdvanceAdminAction.rebuild(), may move back until I find solution for lazy loading for each rebuild*()

    pageTemplate.closeIndex();//www.  j a v a  2 s  .  com
    commentTemplate.closeIndex();
    spaceTemplate.closeIndex();
    userTemplate.closeIndex();
    roleTemplate.closeIndex();
    pageTagTemplate.closeIndex();
    spaceTagTemplate.closeIndex();
    attachmentTemplate.closeIndex();
    widgetTemplate.closeIndex();

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Clean all sub directories(first level) under index root, but not delete directory itself.
    try {
        File[] list = indexRoot.getFile().listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.isDirectory() ? true : false;
            }
        });
        for (File file : list) {
            try {
                FileUtils.cleanDirectory(file);
            } catch (IOException e) {
                log.error("Unable to clean index root directory:" + indexRoot.getFilename(), e);
            }
        }
    } catch (IOException e1) {
        log.error("Unable to list index root directory", e1);
    }

    pageTemplate.createEmptyIndex();
    commentTemplate.createEmptyIndex();
    spaceTemplate.createEmptyIndex();
    userTemplate.createEmptyIndex();
    roleTemplate.createEmptyIndex();
    pageTagTemplate.createEmptyIndex();
    spaceTagTemplate.createEmptyIndex();
    attachmentTemplate.createEmptyIndex();
    widgetTemplate.createEmptyIndex();

}

From source file:com.cloudbees.hudson.plugins.folder.AbstractFolder.java

/**
 * Loads all the child {@link Item}s./*from w w  w . j av a  2  s . c o  m*/
 *
 * @param modulesDir Directory that contains sub-directories for each child item.
 */
// TODO replace with ItemGroupMixIn.loadChildren once baseline core has JENKINS-41222 merged
public static <K, V extends TopLevelItem> Map<K, V> loadChildren(AbstractFolder<V> parent, File modulesDir,
        Function1<? extends K, ? super V> key) {
    CopyOnWriteMap.Tree<K, V> configurations = new CopyOnWriteMap.Tree<K, V>();
    if (!modulesDir.isDirectory() && !modulesDir.mkdirs()) { // make sure it exists
        LOGGER.log(Level.SEVERE, "Could not create {0} for folder {1}",
                new Object[] { modulesDir, parent.getFullName() });
        return configurations;
    }

    File[] subdirs = modulesDir.listFiles(new FileFilter() {
        public boolean accept(File child) {
            return child.isDirectory();
        }
    });
    if (subdirs == null) {
        return configurations;
    }
    final ChildNameGenerator<AbstractFolder<V>, V> childNameGenerator = parent.childNameGenerator();
    Map<String, V> byDirName = new HashMap<String, V>();
    if (parent.items != null) {
        if (childNameGenerator == null) {
            for (V item : parent.items.values()) {
                byDirName.put(item.getName(), item);
            }
        } else {
            for (V item : parent.items.values()) {
                String itemName = childNameGenerator.dirNameFromItem(parent, item);
                if (itemName == null) {
                    itemName = childNameGenerator.dirNameFromLegacy(parent, item.getName());
                }
                byDirName.put(itemName, item);
            }
        }
    }
    for (File subdir : subdirs) {
        try {
            boolean legacy;
            String childName;
            if (childNameGenerator == null) {
                // the directory name is the item name
                childName = subdir.getName();
                legacy = false;
            } else {
                File nameFile = new File(subdir, ChildNameGenerator.CHILD_NAME_FILE);
                if (nameFile.isFile()) {
                    childName = StringUtils.trimToNull(FileUtils.readFileToString(nameFile, "UTF-8"));
                    if (childName == null) {
                        LOGGER.log(Level.WARNING, "{0} was empty, assuming child name is {1}",
                                new Object[] { nameFile, subdir.getName() });
                        legacy = true;
                        childName = subdir.getName();
                    } else {
                        legacy = false;
                    }
                } else {
                    // this is a legacy name
                    legacy = true;
                    childName = subdir.getName();
                }
            }
            // Try to retain the identity of an existing child object if we can.
            V item = byDirName.get(childName);
            boolean itemNeedsSave = false;
            if (item == null) {
                XmlFile xmlFile = Items.getConfigFile(subdir);
                if (xmlFile.exists()) {
                    item = (V) xmlFile.read();
                    String name;
                    if (childNameGenerator == null) {
                        name = subdir.getName();
                    } else {
                        String dirName = childNameGenerator.dirNameFromItem(parent, item);
                        if (dirName == null) {
                            dirName = childNameGenerator.dirNameFromLegacy(parent, childName);
                            BulkChange bc = new BulkChange(item); // suppress any attempt to save as parent not set
                            try {
                                childNameGenerator.recordLegacyName(parent, item, childName);
                                itemNeedsSave = true;
                            } catch (IOException e) {
                                LOGGER.log(Level.WARNING, "Ignoring {0} as could not record legacy name",
                                        subdir);
                                continue;
                            } finally {
                                bc.abort();
                            }
                        }
                        if (!subdir.getName().equals(dirName)) {
                            File newSubdir = parent.getRootDirFor(dirName);
                            if (newSubdir.exists()) {
                                LOGGER.log(Level.WARNING,
                                        "Ignoring {0} as folder naming rules collide with {1}",
                                        new Object[] { subdir, newSubdir });
                                continue;

                            }
                            LOGGER.log(Level.INFO, "Moving {0} to {1} in accordance with folder naming rules",
                                    new Object[] { subdir, newSubdir });
                            if (!subdir.renameTo(newSubdir)) {
                                LOGGER.log(Level.WARNING, "Failed to move {0} to {1}. Ignoring this item",
                                        new Object[] { subdir, newSubdir });
                                continue;
                            }
                        }
                        File nameFile = new File(parent.getRootDirFor(dirName),
                                ChildNameGenerator.CHILD_NAME_FILE);
                        name = childNameGenerator.itemNameFromItem(parent, item);
                        if (name == null) {
                            name = childNameGenerator.itemNameFromLegacy(parent, childName);
                            FileUtils.writeStringToFile(nameFile, name, "UTF-8");
                            BulkChange bc = new BulkChange(item); // suppress any attempt to save as parent not set
                            try {
                                childNameGenerator.recordLegacyName(parent, item, childName);
                                itemNeedsSave = true;
                            } catch (IOException e) {
                                LOGGER.log(Level.WARNING, "Ignoring {0} as could not record legacy name",
                                        subdir);
                                continue;
                            } finally {
                                bc.abort();
                            }
                        } else if (!childName.equals(name) || legacy) {
                            FileUtils.writeStringToFile(nameFile, name, "UTF-8");
                        }
                    }
                    item.onLoad(parent, name);
                } else {
                    LOGGER.log(Level.WARNING, "could not find file " + xmlFile.getFile());
                    continue;
                }
            } else {
                String name;
                if (childNameGenerator == null) {
                    name = subdir.getName();
                } else {
                    File nameFile = new File(subdir, ChildNameGenerator.CHILD_NAME_FILE);
                    name = childNameGenerator.itemNameFromItem(parent, item);
                    if (name == null) {
                        name = childNameGenerator.itemNameFromLegacy(parent, childName);
                        FileUtils.writeStringToFile(nameFile, name, "UTF-8");
                        BulkChange bc = new BulkChange(item); // suppress any attempt to save as parent not set
                        try {
                            childNameGenerator.recordLegacyName(parent, item, childName);
                            itemNeedsSave = true;
                        } catch (IOException e) {
                            LOGGER.log(Level.WARNING, "Ignoring {0} as could not record legacy name", subdir);
                            continue;
                        } finally {
                            bc.abort();
                        }
                    } else if (!childName.equals(name) || legacy) {
                        FileUtils.writeStringToFile(nameFile, name, "UTF-8");
                    }
                    if (!subdir.getName().equals(name) && item instanceof AbstractItem
                            && ((AbstractItem) item).getDisplayNameOrNull() == null) {
                        BulkChange bc = new BulkChange(item);
                        try {
                            ((AbstractItem) item).setDisplayName(childName);
                        } finally {
                            bc.abort();
                        }
                    }
                }
                item.onLoad(parent, name);
            }
            if (itemNeedsSave) {
                try {
                    item.save();
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Could not update {0} after applying folder naming rules",
                            item.getFullName());
                }
            }
            configurations.put(key.call(item), item);
        } catch (Exception e) {
            Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not load " + subdir, e);
        }
    }

    return configurations;
}

From source file:com.safi.asterisk.handler.SafletEngine.java

public synchronized void loadActionpaks() {
    File actionpakDir = new File(getActionpakDirectory());
    if (!actionpakDir.exists()) {
        actionpakDir.mkdirs();/*from ww  w. j  a  va 2 s.  co m*/
    } else {
        File[] files = actionpakDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                // TODO Auto-generated method stub
                return pathname.getName().endsWith(".jar");
            }
        });
        if (log.isDebugEnabled())
            for (File f : files) {
                log.debug("Got file " + f.getAbsolutePath() + " and uri " + f.toURI());
            }
        actionpakJars = new HashSet<File>(Arrays.asList(files));
        // for (File f : files){
        // try {
        // getDispatcher().loadJar(f);
        // } catch (Exception e) {
        // e.printStackTrace();
        // log.error("Couldn't load jar file "+f, e);
        // }
        // }
    }
}

From source file:com.hp.flume.plugins.source.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.
 *//*w  w w  .  j a v a2s.com*/
private Optional<FileInfo> getNextFile()// lucheng revised
{
    /* Filter to exclude finished or hidden files */
    FileFilter filter = new FileFilter() {
        public boolean accept(File candidate) {
            String fileName = candidate.getName();
            if ((candidate.isDirectory()) || (fileName.endsWith(completedSuffix)) || (fileName.startsWith("."))
                    || ignorePattern.matcher(fileName).matches() || (fileName.endsWith("~"))) {
                return false;
            }
            return true;
        }
    };
    List<File> candidateFiles = Arrays.asList(spoolDirectory.listFiles(filter));// lucheng

    // String file = new String();
    // for(File i : candidateFiles)
    // {
    // file += i.getAbsolutePath() + " && ";
    // }

    // logger.debug(file);

    if (candidateFiles.isEmpty()) { // No matching file in spooling
                                    // directory.
        return Optional.absent();
    }
    File rdFile, selectedFile;
    Random rd = new Random();
    do {
        int num = rd.nextInt(candidateFiles.size());
        rdFile = candidateFiles.get(num);
        selectedFile = candidateFiles.get(0);
        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) {
                selectedFile = candidateFile;
            }
        }

    } while (rdFile.getAbsolutePath().equals(selectedFile.getAbsolutePath()) && candidateFiles.size() > 2);// obsolete algorithm

    if (candidateFiles.size() == 2)
        return openFile(selectedFile);
    return openFile(rdFile);
}

From source file:org.apache.flume.client.avro.TestReliableSpoolingFileEventReader.java

private static List<File> listFiles(File dir) {
    List<File> files = Lists.newArrayList(dir.listFiles(new FileFilter() {
        @Override/*from  www .  jav  a 2 s .c om*/
        public boolean accept(File pathname) {
            return !pathname.isDirectory();
        }
    }));
    return files;
}