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:io.personium.engine.extension.support.ExtensionJarLoader.java

/**
 * ExtensionJarDirectory?? jar?URL??./*from   w w w .  ja va2 s  . com*/
 * ???? "jar"????
 * @param extJarDir Extensionjar??
 * @param searchDescend true: ?, false: ????
 * @return jar? URL.
 */
private List<URL> getJarPaths(Path extJarDir, boolean searchDescend) throws PersoniumEngineException {
    try {
        // ??
        List<URL> uriList = new ArrayList<URL>();
        // jar?????
        uriList.add(new URL("file", "", extJarDir.toFile().getAbsolutePath() + "/"));

        // jar?
        File[] jarFiles = extJarDir.toFile().listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if (!pathname.exists() || !pathname.canRead() || pathname.isDirectory()) {
                    return false;
                }
                return FilenameUtils.isExtension(pathname.getName(), JAR_SUFFIX);
            }
        });

        if (null != jarFiles) {
            for (File jarFile : jarFiles) {
                try {
                    uriList.add(new URL("file", "", jarFile.getCanonicalPath()));
                    log.info(String.format("Info: Adding extension jar file %s to classloader.",
                            jarFile.toURI()));
                } catch (MalformedURLException e) {
                    // ############################################################################3
                    // ????????? jar???????? jar????
                    // ? Extension????????? Extension????? UserScript??
                    // ????????????
                    // ?? Extension?????Script???
                    // ############################################################################3
                    log.info(String.format("Warn: Some Extension jar file has malformed path. Ignoring: %s",
                            jarFile.toURI()));
                } catch (IOException e) {
                    log.info(String.format("Warn: Some Extension jar file has malformed path. Ignoring: %s",
                            jarFile.toURI()));
                }
            }
        }

        // ?
        File[] subDirs = extJarDir.toFile().listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.exists() && pathname.isDirectory() && pathname.canRead();
            }
        });

        if (null != subDirs) {
            for (File subDir : subDirs) {
                //  jar?
                uriList.addAll(getJarPaths(subDir.toPath(), searchDescend));
            }
        }
        return uriList;
    } catch (RuntimeException e) {
        e.printStackTrace();
        log.info(String.format("Warn: Error occured while loading Extension: %s", e.getMessage()));
        throw new PersoniumEngineException("Error occured while loading Extension.",
                PersoniumEngineException.STATUSCODE_SERVER_ERROR, e);
    } catch (Exception e) {
        log.info(String.format("Warn: Error occured while loading Extension: %s", e.getMessage()));
        throw new PersoniumEngineException("Error occured while loading Extension.",
                PersoniumEngineException.STATUSCODE_SERVER_ERROR, e);
    }
}

From source file:org.springmodules.validation.bean.conf.namespace.XmlBasedValidatorBeanDefinitionParser.java

protected List createResources(Element resourcesDefinition) {
    String dirName = resourcesDefinition.getAttribute(DIR_ATTR);
    final String pattern = resourcesDefinition.getAttribute(PATTERN_ATTR);
    final AntPathMatcher matcher = new AntPathMatcher();
    FileFilter filter = new FileFilter() {
        public boolean accept(File file) {
            return matcher.match(pattern, file.getName());
        }//  w w w. j  ava  2s. c om
    };
    List resources = new ArrayList();
    for (Iterator files = new FileIterator(dirName, filter); files.hasNext();) {
        File file = (File) files.next();
        resources.add(new FileSystemResource(file));
    }
    return resources;
}

From source file:com.amazonaws.eclipse.elasticbeanstalk.git.AWSGitPushCommand.java

private void clearOutRepository(Repository repository) throws IOException {
    // Delete all the old files before copying the new files
    final File gitMetadataDirectory = repository.getIndexFile().getParentFile();

    FileFilter fileFilter = new FileFilter() {
        public boolean accept(final File file) {
            if (file.equals(gitMetadataDirectory))
                return false;
            if (!file.getParentFile().equals(repoLocation))
                return false;
            return true;
        }//from  w  ww.  ja  v a2 s .  c  o  m
    };

    for (File f : repoLocation.listFiles(fileFilter)) {
        FileUtils.delete(f, FileUtils.RECURSIVE);
    }
}

From source file:com.LMO.capstone.KnoWITHerbalMain.java

private void resolver() throws XmlPullParserException, IOException {
    if (!new File(Config.dbPath(getApplicationContext())).exists()) { //no DB, no Folder
        HowToUseFragment howto = new HowToUseFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.frame_content, howto);
        ft.addToBackStack("help");
        ft.commit();/*from w w w .ja v a 2s  . com*/
        if (util.isNetworkAvailable())
            util.PrepareFileForDatabase();
    } else {
        File appDir = new File(Config.externalDirectory);
        if (!appDir.exists())
            appDir.mkdir();

        FileFilter filter = new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                // TODO Auto-generated method stub
                return pathname.toString().toLowerCase(Locale.getDefault()).contains(".jpg")
                        || pathname.toString().toLowerCase(Locale.getDefault()).contains(".png")
                        || pathname.toString().toLowerCase(Locale.getDefault()).contains(".bmp")
                        || pathname.toString().toLowerCase(Locale.getDefault()).contains(".gif")
                        || pathname.toString().toLowerCase(Locale.getDefault()).contains(".jpeg");
            }
        };
        File[] files = appDir.listFiles(filter);
        dbHelper = new DatabaseHelper(this);
        int imageEntryCount = Queries.getImageEntryCount(sqliteDB, dbHelper);

        if (files.length == 1 || (files.length + 1) < imageEntryCount) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            AlertDialog dialog = builder.create();
            dialog.setTitle("Oops!");
            dialog.setMessage("It seems your data is invalid!\nRe-download now?");
            dialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    if (util.isNetworkAvailable())
                        Queries.truncateDatabase(sqliteDB, dbHelper, getApplicationContext());
                    util.PrepareFileForDatabase();
                }
            });
            dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Maybe later", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }
}

From source file:mx.itesm.mexadl.metrics.util.Util.java

/**
 * Get the Java classes in the given directory, including those in
 * sub-directories.//from ww  w  . j av a2 s .  co m
 * 
 * @param directory
 * @return
 */
public static List<String> getClassesInDirectory(final File directory) {
    File currentFile;
    File[] directoryFiles;
    List<String> innerFiles;
    List<String> returnValue;

    returnValue = null;
    directoryFiles = directory.listFiles(new FileFilter() {
        @Override
        public boolean accept(final File pathname) {
            return (pathname.isDirectory() || pathname.toString().endsWith(".class"));
        }
    });

    if ((directoryFiles != null) && (directoryFiles.length > 0)) {
        returnValue = new ArrayList<String>();
        for (int i = 0; i < directoryFiles.length; i++) {
            currentFile = directoryFiles[i];

            if (currentFile.isDirectory()) {
                innerFiles = Util.getClassesInDirectory(currentFile);
                if (innerFiles != null) {
                    returnValue.addAll(innerFiles);
                }
            } else {
                returnValue.add(currentFile.getAbsolutePath());
            }
        }
    }

    return returnValue;
}

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

private Library() {
    this.songs = new ConcurrentLinkedQueue<Song>();
    this.toRead = new ConcurrentHashMap<String, File>();
    this.files = new ConcurrentLinkedQueue<File>();
    this.toInsert = new ConcurrentLinkedQueue<Song>();
    this.hashes = new HashSet<String>();
    this.artworks = new HashMap<String, Map<String, String>>();

    this.artworkFallback = new FileFilter() {
        @Override/*from ww w.  j ava  2 s. c o m*/
        public boolean accept(File pathname) {
            return Pattern.matches(".*[.](jpeg|jpg|png|bmp|gif)$", pathname.getName().toLowerCase());
        }
    };

    Runnable timer = new Runnable() {

        @Override
        public void run() {
            while (!kill) {
                final long t1 = System.currentTimeMillis();

                final List<File> music = new ArrayList<File>();
                for (String path : Config.getMusicPath()) {
                    music.add(new File(path));
                }

                addSongCount = 0;
                skipSongCount = 0;
                failedSongCount = 0;
                fileSearchTime = 0;
                dbCheckTime = 0;
                fileReadTime = 0;
                dbInsertTime = 0;
                resizeTime = 0;
                songs.clear();
                toRead.clear();
                files.clear();
                hashes.clear();
                toInsert.clear();
                artworks.clear();

                songsTodo = 0;
                songsDone = 0;
                working = true;
                stop = false;
                percentDone = 0.0f;
                secondsLeft = -1;

                artworkRegex = Pattern.compile(Config.getArtworkRegex());
                artworkFilter = new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        return (artworkRegex.matcher(pathname.getName().toLowerCase()).matches());
                    }
                };

                // walks filesystem and indexes files that look like music
                fileSearchDone = false;
                Thread fileSearch = new Thread(new Runnable() {
                    public void run() {
                        long f1 = System.currentTimeMillis();
                        for (File f : music) {
                            try {
                                listFiles(f, files);
                            } catch (IOException e) {
                                Logger.error("Failed to add directory to library: " + f.getAbsolutePath(), e);
                            } catch (InterruptedException e) {
                                return;
                            }
                        }
                        fileSearchDone = true;
                        fileSearchTime = (System.currentTimeMillis() - f1);
                    }
                });
                fileSearch.start();

                // exclude files that are already in DB
                dbCheckDone = false;
                Thread dbCheck = new Thread(new Runnable() {
                    public void run() {
                        while (!stop && !dbCheckDone) {
                            long f1 = System.currentTimeMillis();
                            while (!files.isEmpty()) {
                                File f = files.remove();
                                String hash = new String(md5.digest(f.getAbsolutePath().getBytes()));

                                boolean hasSong = false;

                                try {
                                    hasSong = DB.get().hasSong(hash);
                                } catch (SQLException e) {
                                    Logger.error("Failed to query DB for file " + f.getAbsolutePath(), e);
                                }
                                if (!hasSong) {
                                    toRead.put(hash, f);
                                } else {
                                    skipSongCount++;
                                }
                                hashes.add(hash);
                            }

                            dbCheckTime += (System.currentTimeMillis() - f1);
                            if (fileSearchDone && files.isEmpty()) {
                                dbCheckDone = true;
                                return;
                            }
                        }
                    }
                });
                dbCheck.start();

                // read file metadata
                fileReadDone = false;
                Thread fileRead = new Thread(new Runnable() {
                    public void run() {
                        while (!stop && !fileReadDone) {
                            long f1 = System.currentTimeMillis();

                            Iterator<Entry<String, File>> it = toRead.entrySet().iterator();
                            while (it.hasNext()) {
                                Entry<String, File> f = it.next();
                                it.remove();
                                try {
                                    Song s = getSong(f.getValue(), f.getKey());
                                    songs.add(s);
                                    addSongCount++;
                                } catch (IOException e) {
                                    Logger.warn("Failed to read music file " + f.getValue(), e);
                                    failedSongCount++;
                                }
                            }

                            fileReadTime += (System.currentTimeMillis() - f1);
                            if (dbCheckDone && toRead.isEmpty()) {
                                fileReadDone = true;
                                return;
                            }
                        }
                    }
                });
                fileRead.start();

                // resize images
                resizeDone = false;
                Thread resize = new Thread(new Runnable() {
                    public void run() {
                        while (!stop && !resizeDone) {
                            long f1 = System.currentTimeMillis();
                            while (!songs.isEmpty()) {
                                Song s = songs.remove();
                                String path = null;
                                Map<String, String> m = artworks.get(s.artist.name);
                                if (m != null && m.containsKey(s.album.name)) {
                                    path = m.get(s.album.name);
                                }
                                if (path != null) {
                                    if (new File(path + "_SCALED.jpg").exists()) {
                                        path = path + "_SCALED.jpg";
                                    } else {
                                        try {
                                            path = resizeArtwork(path);
                                        } catch (IOException e) {
                                            Logger.warn("Failed to resize image", e);
                                        }
                                    }
                                    s.album.artwork_path = path;
                                    s.album.artwork_id = "" + System.currentTimeMillis();
                                }
                                toInsert.add(s);
                            }
                            resizeTime += (System.currentTimeMillis() - f1);

                            if (fileReadDone && songs.isEmpty()) {
                                resizeDone = true;
                                return;
                            }
                        }
                    }
                });
                resize.start();

                // insert Songs in DB
                Thread dbInsert = new Thread(new Runnable() {
                    public void run() {
                        while (!stop) {
                            long f1 = System.currentTimeMillis();
                            while (!toInsert.isEmpty()) {
                                Song s = toInsert.remove();
                                try {
                                    DB.get().addSong(s);
                                } catch (SQLException e) {
                                    Logger.warn("Failed to insert in DB " + s.filepath, e);
                                    failedSongCount++;
                                }
                                songsDone++;
                                percentDone = songsDone / ((float) songsTodo);

                                float songsPerSec = songsDone / ((System.currentTimeMillis() - t1) / 1000f);
                                secondsLeft = (long) ((songsTodo - songsDone) / songsPerSec);
                            }
                            dbInsertTime += (System.currentTimeMillis() - f1);

                            if (resizeDone && toInsert.isEmpty()) {
                                return;
                            }
                        }
                    }
                });
                dbInsert.start();
                try {
                    dbInsert.join();
                } catch (InterruptedException e3) {
                    Logger.warn("Library indexer interrupted", e3);
                    fileSearch.interrupt();
                    dbCheck.interrupt();
                    fileRead.interrupt();
                    resize.interrupt();
                    dbInsert.interrupt();
                }

                if (Thread.interrupted()) {
                    Logger.warn("Library indexer has been interrupted");
                    continue;
                }

                // remove files from DB that were not found
                int removed = 0;
                long r1 = System.currentTimeMillis();
                try {
                    removed = DB.get().removeSongs(hashes);
                } catch (SQLException e3) {
                    Logger.error("Failed to remove songs", e3);
                }
                long dbRemoveTime = (System.currentTimeMillis() - r1);

                // update statistics
                long u1 = System.currentTimeMillis();
                try {
                    DB.get().updateSongCount();
                } catch (SQLException e1) {
                    Logger.error("Failed to update song count", e1);
                }
                long dbUpdateTime = (System.currentTimeMillis() - u1);

                try {
                    RuntimeStats.get().updateFromDB();
                } catch (SQLException e) {
                    Logger.error("Failed to update runtime statistics", e);
                }

                working = false;

                long t2 = (System.currentTimeMillis() - t1);
                Logger.info("Processed " + songsDone + " files " //
                        + "(add:" + addSongCount + "," //
                        + "skip:" + skipSongCount + "," //
                        + "fail:" + failedSongCount + "," //
                        + "rem:" + removed + ")");
                Logger.info("Indexer took " + t2 + " (" + ((float) songsDone / ((float) t2 / 1000)) + " /s) (" //
                        + "search:" + fileSearchTime + "," //
                        + "check:" + dbCheckTime + ","//
                        + "read:" + fileReadTime + "," //
                        + "resize:" + resizeTime + "," //
                        + "insert:" + dbInsertTime + "," //
                        + "remove:" + dbRemoveTime + "," //
                        + "update:" + dbUpdateTime + ")");

                int seconds = Config.getMusicRefreshRate();
                try {
                    Thread.sleep(seconds * 1000);
                } catch (InterruptedException e) {
                    Logger.warn("Library indexer interrupted", e);
                }
            }
        }

    };
    this.thread = new Thread(timer, "MusicIndexer");
}

From source file:com.hipu.bdb.util.FileUtils.java

/**
 * Get a list of all files in directory that have passed prefix.
 *
 * @param dir Dir to look in.//from w  ww . j a  va  2 s .co m
 * @param prefix Basename of files to look for. Compare is case insensitive.
 *
 * @return List of files in dir that start w/ passed basename.
 */
public static File[] getFilesWithPrefix(File dir, final String prefix) {
    FileFilter prefixFilter = new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.getName().toLowerCase().startsWith(prefix.toLowerCase());
        }
    };
    return dir.listFiles(prefixFilter);
}

From source file:de.tudarmstadt.lt.lm.app.NgramProbs.java

@Override
public void run() {

    _lm_prvdr = AbstractStringProvider.connectToServer(_host, _rmiport, _name);
    if (_lm_prvdr == null) {
        LOG.error("Could not connect to language model at '{}'", _rmi_string);
        return;//  w  w  w.  j  a  va  2s .co m
    }

    _pout = System.out;
    if (!"-".equals(_out)) {
        try {
            _pout = new PrintStream(new FileOutputStream(new File(_out), true));
        } catch (FileNotFoundException e) {
            LOG.error("Could not open ouput file '{}' for writing.", _out, e);
            System.exit(1);
        }
    }

    if ("-".equals(_file.trim())) {
        LOG.info("{}: Processing text from stdin ('{}').", _rmi_string, _file);
        try {
            run(new InputStreamReader(System.in, "UTF-8"));
        } catch (Exception e) {
            LOG.error("{}: Could not compute perplexity from file '{}'.", _rmi_string, _file, e);
        }
    } else {

        File f_or_d = new File(_file);
        if (!f_or_d.exists())
            throw new Error(String.format("%s: File or directory '%s' not found.", _rmi_string, _file));

        if (f_or_d.isFile()) {
            LOG.info("{}: Processing file '{}'.", _rmi_string, f_or_d.getAbsolutePath());
            try {
                run(new InputStreamReader(new FileInputStream(f_or_d), "UTF-8"));
            } catch (Exception e) {
                LOG.error("{}: Could not compute perplexity from file '{}'.", _rmi_string,
                        f_or_d.getAbsolutePath(), e);
            }
        }

        if (f_or_d.isDirectory()) {
            File[] txt_files = f_or_d.listFiles(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.isFile() && f.getName().endsWith(".txt");
                }
            });

            for (int i = 0; i < txt_files.length; i++) {
                File f = txt_files[i];
                LOG.info("{}: Processing file '{}' ({}/{}).", _rmi_string, f.getAbsolutePath(), i + 1,
                        txt_files.length);
                try {
                    run(new InputStreamReader(new FileInputStream(f), "UTF-8"));
                } catch (Exception e) {
                    LOG.error("{}: Could not compute perplexity from file '{}'.", _rmi_string,
                            f.getAbsolutePath(), e);
                }

            }
        }
    }

    String o = String.format("%s\t%s\tMax=%s (%6.3e)\tMin=%s (%6.3e)", _rmi_string, _file, _max_ngram,
            Math.pow(10, _max_prob), _min_ngram, Math.pow(10, _min_prob));
    LOG.info(o);

}

From source file:de.petermoesenthin.alarming.util.FileUtil.java

/**
 * Returns a file list of all non-hidden audio files in the application directory.
 *
 * @return//from www  .  j  av  a  2  s.  c  o m
 */
public static File[] getAlarmDirectoryAudioFileList(final Context context) {
    return FileUtil.getApplicationDirectory().listFiles(new FileFilter() {
        @Override
        public boolean accept(File f) {
            // Early out if hidden
            if (f.isHidden()) {
                return false;
            }
            String extension = FilenameUtils.getExtension(f.getPath());
            if (extension.equals(AUDIO_METADATA_FILE_EXTENSION)) {
                return false;
            }
            return fileIsOK(context, f.getPath());
        }
    });
}

From source file:gov.pnnl.goss.gridappsd.service.ServiceManagerImpl.java

/**
 * //www  .  j  a  va2  s .  c  o m
 */
protected void scanForServices() {
    //Get directory for services from the config
    File serviceConfigDir = getServiceConfigDirectory();

    //for each service found, parse the [service].config file to create serviceinfo object and add to services map
    File[] serviceconfigFiles = serviceConfigDir.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            if (pathname.isFile() && pathname.getName().endsWith(".config"))
                return true;
            else
                return false;
        }
    });
    for (File serviceConfigFile : serviceconfigFiles) {
        ServiceInfo serviceInfo = parseServiceInfo(serviceConfigFile);
        services.put(serviceInfo.getId(), serviceInfo);
    }
}