Example usage for java.io FilenameFilter FilenameFilter

List of usage examples for java.io FilenameFilter FilenameFilter

Introduction

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

Prototype

FilenameFilter

Source Link

Usage

From source file:cw.kop.autobackground.settings.AppSettings.java

public static void versionUpdate() {

    if (prefs.getBoolean("version_update_1.0", true)) {

        FilenameFilter fileFilter = (new FilenameFilter() {

            @Override/*from   ww  w  .j av a 2  s  .  c  om*/
            public boolean accept(File dir, String filename) {
                return filename.endsWith(".png") || filename.endsWith(".jpg") || filename.endsWith(".jpg");
            }
        });

        String downloadCache = getDownloadPath();
        for (int i = 0; i < AppSettings.getNumSources(); i++) {
            if (AppSettings.getSourceType(i).equals(AppSettings.WEBSITE)) {
                String title = AppSettings.getSourceTitle(i);
                String titleTrimmed = title.replaceAll(" ", "");
                File oldFolder = new File(downloadCache + "/" + titleTrimmed + AppSettings.getImagePrefix());
                if (oldFolder.exists() && oldFolder.isDirectory()) {

                    File[] fileList = oldFolder.listFiles(fileFilter);

                    for (int index = 0; index < fileList.length; index++) {
                        if (fileList[index].getName().contains(title)) {
                            fileList[index].renameTo(
                                    new File(downloadCache + "/" + title + AppSettings.getImagePrefix() + "/"
                                            + title + " " + AppSettings.getImagePrefix() + index + ".png"));
                            Log.i("AS", "Renamed file");
                        }
                    }

                    oldFolder.renameTo(new File(downloadCache + "/" + title + " " + getImagePrefix()));

                    Log.i("AS", "Renamed");
                }
            }
        }
        prefs.edit().putBoolean("version_update_1.0", false).commit();
    }
}

From source file:com.gitblit.tests.HtpasswdAuthenticationTest.java

private void deleteGeneratedFiles() {
    File dir = new File(RESOURCE_DIR);
    FilenameFilter filter = new FilenameFilter() {
        @Override/* ww w  . jav a  2s . co  m*/
        public boolean accept(File dir, String file) {
            return !(file.endsWith(".in"));
        }
    };
    for (File file : dir.listFiles(filter)) {
        file.delete();
    }
}

From source file:gov.redhawk.efs.sca.server.internal.FileSystemImpl.java

@Override
public FileInformationType[] list(final String fullPattern) throws FileException, InvalidFileName {
    final int index = fullPattern.lastIndexOf('/');
    final File container;
    if (index > 0) {
        container = new File(this.root, fullPattern.substring(0, index));
    } else {//from   www . jav a2s. c  o m
        container = this.root;
    }

    final String pattern = fullPattern.substring(index + 1, fullPattern.length());

    final String[] fileNames;

    if (pattern.length() == 0) {
        fileNames = new String[] { "" };
    } else {
        fileNames = container.list(new FilenameFilter() {

            @Override
            public boolean accept(final File dir, final String name) {
                if (!dir.equals(container)) {
                    return false;
                }
                return FilenameUtils.wildcardMatch(name, pattern);
            }
        });
    }

    final FileInformationType[] retVal = new FileInformationType[fileNames.length];
    for (int i = 0; i < fileNames.length; i++) {
        final FileInformationType fileInfo = new FileInformationType();
        final File file = new File(container, fileNames[i]);
        fileInfo.name = file.getName();
        fileInfo.size = file.length();
        if (file.isFile()) {
            fileInfo.kind = FileType.PLAIN;
        } else {
            fileInfo.kind = FileType.DIRECTORY;
        }
        final Any any = this.orb.create_any();
        any.insert_ulonglong(file.lastModified() / FileSystemImpl.MILLIS_PER_SEC);
        final DataType modifiedTime = new DataType("MODIFIED_TIME", any);

        fileInfo.fileProperties = new DataType[] { modifiedTime };

        retVal[i] = fileInfo;
    }
    return retVal;
}

From source file:io.smartspaces.configuration.FileSystemConfigurationStorageManager.java

/**
 * Get all configuration files from the Smart Spaces configuration
 * folder.//from  w  w w .  ja  va  2 s  .c  om
 *
 * @return all files in the configuration folder
 */
private File[] getConfigFiles() {
    File configurationFolder = new File(configFolder, ContainerFilesystemLayout.FOLDER_CONFIG_smartspaces);
    if (configurationFolder.exists()) {
        if (!configurationFolder.isDirectory()) {
            throw new SimpleSmartSpacesException(String
                    .format("Smart Spaces configuration folder %s is not a directory", configurationFolder));
        }
    } else {
        throw new SimpleSmartSpacesException(
                String.format("Smart Spaces configuration folder %s does not exist", configurationFolder));
    }

    File[] configFiles = configurationFolder.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            String filename = name.toLowerCase();
            return filename.endsWith(CONFIGURATION_FILE_EXTENSION);
        }
    });

    if (configFiles.length == 0) {
        throw new SimpleSmartSpacesException(
                String.format("Smart Spaces configuration folder %s contains no files ending with %s",
                        configurationFolder, CONFIGURATION_FILE_EXTENSION));
    }

    return configFiles;
}

From source file:com.richtodd.android.repository.FileRepositoryContainerProvider.java

private File[] listFiles(boolean listThumbnails) {

    final boolean localListThumbnails = listThumbnails;

    File[] files = m_folderFile.listFiles(new FilenameFilter() {
        @Override// w  ww .j  av  a  2  s  .com
        public boolean accept(File dir, String filename) {
            return localListThumbnails == filename.startsWith(THUMBNAIL_PREFIX);
        }
    });

    return files;
}

From source file:io.smartspaces.launcher.bootstrap.ExtensionsReader.java

/**
 * Add all extension classpath entries that the controller specifies.
 *
 * @param extensionsFolder//w ww .j a  v a  2 s.com
 *          the folder which contains the extension files
 */
public void processExtensionFiles(File extensionsFolder) {
    File[] extensionFiles = extensionsFolder.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(EXTENSION_FILE_EXTENSION);
        }
    });
    if (extensionFiles == null || extensionFiles.length == 0) {
        return;
    }

    for (File extensionFile : extensionFiles) {
        processExtensionFile(extensionFile);
    }

    log.debug(String.format("Extensions have added the following Java packages: %s", packages));
    log.debug(String.format("Extensions have added the following classes to be loaded automatically: %s",
            loadClasses));
    log.debug(String.format("Extensions have loaded the following native libraries: %s ", loadLibraries));
    log.debug(String.format("Extensions have loaded the following container path items: %s ", containerPath));
}

From source file:org.red5.server.script.jython.JythonScriptFactory.java

/** {@inheritDoc} */
@SuppressWarnings({ "rawtypes" })
public Object getScriptedObject(ScriptSource scriptSourceLocator, Class[] scriptInterfaces)
        throws IOException, ScriptCompilationException {
    String basePath = "";

    /* TODO: how to do this when running under Tomcat?
    ContextHandler handler = WebAppContext.getCurrentWebAppContext();
    if (handler != null) {//w  ww .ja  va2  s.c  o  m
       File root = handler.getBaseResource().getFile();
       if (root != null && root.exists()) {
    basePath = root.getAbsolutePath() + File.separator + "WEB-INF" + File.separator;
       }
    }
    */

    String strScript = scriptSourceLocator.getScriptAsString();
    if (scriptInterfaces.length > 0) {
        try {
            PySystemState state = new PySystemState();
            if (!"".equals(basePath)) {
                // Add webapp paths that can contain classes and .jar files to python search path
                state.path.insert(0, Py.newString(basePath + "classes"));
                File jarRoot = new File(basePath + "lib");
                if (jarRoot.exists()) {
                    for (String filename : jarRoot.list(new FilenameFilter() {
                        public boolean accept(File dir, String name) {
                            return (name.endsWith(".jar"));
                        }
                    })) {
                        state.path.insert(1, Py.newString(basePath + "lib" + File.separator + filename));
                    }
                }
            }
            PythonInterpreter interp = new PythonInterpreter(null, state);
            interp.exec(strScript);
            PyObject getInstance = interp.get("getInstance");
            if (!(getInstance instanceof PyFunction)) {
                throw new ScriptCompilationException("\"getInstance\" is not a function.");
            }
            PyObject _this;
            if (arguments == null) {
                _this = ((PyFunction) getInstance).__call__();
            } else {
                PyObject[] args = new PyObject[arguments.length];
                for (int i = 0; i < arguments.length; i++) {
                    args[i] = PyJavaType.wrapJavaObject(arguments[i]);
                }
                _this = ((PyFunction) getInstance).__call__(args);
            }
            return _this.__tojava__(scriptInterfaces[0]);
        } catch (Exception ex) {
            logger.error("Error while loading script.", ex);
            if (ex instanceof IOException) {
                // Raise to caller
                throw (IOException) ex;
            } else if (ex instanceof ScriptCompilationException) {
                // Raise to caller
                throw (ScriptCompilationException) ex;
            }

            throw new ScriptCompilationException(ex.getMessage());
        }
    }
    logger.error("No scriptInterfaces provided.");
    return null;
}

From source file:nz.co.senanque.madura.bundle.BundleManagerImpl.java

public synchronized void scan() {
    m_logger.debug("Scanning files");
    if (m_directory == null) {
        return;//from  www  .  j a  va  2s. c o  m
    }
    File dir = new File(m_directory);
    File[] files = dir.listFiles(new FilenameFilter() {

        public boolean accept(File arg0, String arg1) {
            if (arg1.toUpperCase().endsWith("JAR"))
                return true;
            if (arg1.toUpperCase().endsWith("BUNDLE"))
                return true;
            return false;
        }
    });
    if (files == null) {
        throw new RuntimeException("Could not access directory: " + m_directory);
    }

    // Put all the names in the list of delete candidates
    // we will remove the ones we want to keep
    List<String> deleteCandidates = new ArrayList<String>();
    for (BundleVersion bv : m_bundleMap.getAvailableBundles()) {
        deleteCandidates.add(bv.getFullVersion());
    }

    m_lock = Thread.currentThread();
    // Scan all the files in the directory
    for (File file : files) {
        String fileName = file.getName().toLowerCase();
        int i = fileName.lastIndexOf('.');
        if (i <= 0) {
            continue;
        }
        BundleManagerDelegate bundleManagerDelegate = getBundleManagerDelegate(fileName.substring(i));
        if (bundleManagerDelegate == null)
            continue;

        String bundleName = fileName.substring(0, i);
        BundleRoot root = m_bundleMap.getBundleRoot(bundleName);
        long lastModified = file.lastModified();
        if (root == null) {
            // This is a new one so add it
            try {
                bundleManagerDelegate.addBundle(bundleName, new FileInputStream(file));
            } catch (FileNotFoundException e) {
                m_logger.warn("Failed to open {}", file.getAbsolutePath());
            }
        } else {
            // Make sure we don't delete (shutdown) this
            deleteCandidates.remove(bundleName);
            if (root.getDate() != lastModified) {
                m_bundleMap.deleteBundle(bundleName);
                try {
                    bundleManagerDelegate.addBundle(bundleName, new FileInputStream(file));
                } catch (FileNotFoundException e) {
                    m_logger.warn("Failed to open {}", file.getAbsolutePath());
                }
            }
        }
    }
    for (String bundleName : deleteCandidates) {
        m_bundleMap.deleteBundle(bundleName);
    }
    m_lock = null;
}

From source file:AIR.Common.Web.Session.CaseInsensitiveFileNameFilter.java

public static String getFile(String directory, final String filePathSegment) {
    File f = new File(directory);
    if (f.isDirectory()) {
        String[] filesInFolder = f.list(new FilenameFilter() {
            @Override/*  w w  w.j a  v a  2s  .c o m*/
            public boolean accept(File dir, String name) {
                if (StringUtils.equalsIgnoreCase(name, filePathSegment))
                    return true;
                return false;
            }
        });
        // We are only expecting one match as we are doing a case insensitive
        // match.
        if (filesInFolder != null && filesInFolder.length > 0)
            return filesInFolder[0];
    }
    return filePathSegment;
}

From source file:com.npower.unicom.sync.AbstractImportDaemonPlugIn.java

public synchronized void run() {
    if (this.isRunning) {
        return;/* w ww  .  ja v a 2s  . c  o m*/
    }
    this.isRunning = true;
    try {
        File dir = new File(this.getDirectory());
        if (!dir.isAbsolute()) {
            dir = new File(System.getProperty("otas.dm.home"), this.getDirectory() + "/request");
        }
        while (true) {
            try {
                File[] files = dir.listFiles(new FilenameFilter() {

                    public boolean accept(File dir, String name) {
                        if (StringUtils.isNotEmpty(name)) {
                            if (name.toLowerCase().endsWith(".req")) {
                                return true;
                            }
                        }
                        return false;
                    }
                });
                if (files != null && files.length > 0) {
                    // 
                    for (File file : files) {
                        // 
                        File finishedDir = new File(file.getParentFile().getParentFile().getAbsolutePath(),
                                "finished");
                        if (!finishedDir.exists()) {
                            finishedDir.mkdirs();
                        }

                        File finishedFile = new File(finishedDir, file.getName());
                        if (!finishedFile.exists()) {
                            log.info("start processing new file: " + file.getAbsolutePath());
                            SyncProcessor processor = this.getProcessor(file);
                            processor.sync();
                            log.info("end of processing new file: " + file.getAbsolutePath());
                        } else {
                            log.info("discard finished file: " + file.getAbsolutePath());
                            finishedFile = new File(finishedDir,
                                    file.getName() + "." + System.currentTimeMillis());
                        }

                        // 
                        boolean renameSuccess = file.renameTo(finishedFile);
                        log.info("rename file:" + renameSuccess + " to " + finishedFile.getAbsolutePath());
                    }
                }
            } catch (Exception ex) {
                log.error("Error to monitor directory: " + this.getDirectory(), ex);
            } finally {
                try {
                    Thread.sleep(this.getIntervalInSeconds() * 1000);
                } catch (InterruptedException e) {
                    log.warn("File monitor thread has been interrupted: " + this.getDirectory());
                    if (log.isDebugEnabled()) {
                        log.debug("File monitor thread has been interrupted: " + this.getDirectory(), e);
                    }
                    break;
                }
            }
        }
    } catch (Exception e) {
        log.error("Error to monitor directory: " + this.getDirectory(), e);
    } finally {
        this.isRunning = false;
    }
}