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:de.blizzy.documentr.access.UserStore.java

/** Returns all known role names. */
public List<String> listRoles() throws IOException {
    ILockedRepository repo = null;//from  w  w w.j  a v  a 2  s. c  o m
    try {
        repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);
        File workingDir = RepositoryUtil.getWorkingDir(repo.r());
        FileFilter filter = new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.isFile() && file.getName().endsWith(ROLE_SUFFIX);
            }
        };
        List<File> files = Lists.newArrayList(workingDir.listFiles(filter));
        Function<File, String> function = new Function<File, String>() {
            @Override
            public String apply(File file) {
                return StringUtils.substringBeforeLast(file.getName(), ROLE_SUFFIX);
            }
        };
        List<String> users = Lists.newArrayList(Lists.transform(files, function));
        Collections.sort(users);
        return users;
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:com.runwaysdk.dataaccess.io.Restore.java

private void restoreWebapp() {
    File backupProfileLocationFile = new File(
            this.restoreDirectory.getPath() + File.separator + Backup.WEBAPP_DIR_NAME + File.separator);

    String webappRootDir = DeployProperties.getDeployPath();

    File webappRootFile = new File(webappRootDir);

    FilenameFilter filenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            if (name.endsWith(".svn") || dir.getName().startsWith(".")) {
                return false;
            }//  w  w w .  java  2s. c  om

            return true;
        }
    };

    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File pathname) {
            return true;
        }
    };

    try {
        this.logPrintStream.println("\n" + ServerExceptionMessageLocalizer
                .cleaningWebappFolderMessage(Session.getCurrentLocale(), webappRootFile));
        FileIO.deleteFolderContent(webappRootFile, fileFilter);
    } catch (IOException e) {
        // Some files might have already been deleted. We will copy anyway, as the
        // files should overwrite.
    }

    boolean success = FileIO.copyFolder(backupProfileLocationFile, webappRootFile, filenameFilter,
            this.logPrintStream);
    if (!success) {
        // TODO : This success stuff is garbage, I want the actual IOException why swallow it
        BackupReadException bre = new BackupReadException();
        bre.setLocation(webappRootFile.getAbsolutePath());
        throw bre;
    }
}

From source file:eu.asterics.mw.services.ResourceRegistry.java

/**
 * Returns the URI of the requested resource.
 * Generally the URI is not tested for existence it just constructs a valid URI for the given parameters.
 * The returned URI can be opened with {@link URI#toURL()} and {@link URL#openStream()}, or better use directly {@link ResourceRegistry#getResourceInputStream(String, RES_TYPE)}.
 * If you know that it is a file path URI and need to perform file operations, convert it to a file with {@link ResourceRegistry#toFile(URI)}.
 * // w w w  .j ava 2 s .  c o  m
 * resourcePath can be 
 *     an absolute URL-conforming string (e.g. file://, http://). In this case the string must be encoded correctly.
 *   or an absolute or relative file path (windows or unix-style). In this case {@link File} class and its method {@link File#toURI()} is used. The file path may contain both \\ and / seperators. Relative resourcePaths are resolved against the ARE.baseURI or a subfolder depending on the provided type ({@link RES_TYPE}). 
        
 * The type ({@link RES_TYPE}) determines the type of the resource which is used to append the respective subfolder for the resource type (e.g. data, models).
 * In case of {@value RES_TYPE#DATA} a 4 step approach is used to guess the correct subfolder (e.g. a sensor.facetrackerLK or pictures):
 *   Step 1: If resource ARE.baseURI/data/{resourcePath} exists, return
 *   Step 2: If componentTypeId!=null and resource ARE.baseURI/{DATA_FOLDER}/{componentTypeId}/{resourcePath} exists, return
 *   Step 3: If componentTypeId!=null and resource ARE.baseURI/{DATA_FOLDER}/{*componentTypeId*}/{resourcePath} exists, return
 *   Step 4: If resource ARE.baseURI/{DATA_FOLDER}/{*}/{resourcePath} exists, return
 *   Default: If none of the above was successful, ARE.baseURI/data/{resourcePath} is returned.
 * In case of {@value RES_TYPE#ANY} no subfolder is appended. 
 * 
 * @param resourcePath an absolute URL-conforming string or an absolute or relative file path string
 * @param type The resource type {@link RES_TYPE} for the requested resource
 * @param componentTypeId Hint for a better guessing of a {@value RES_TYPE#DATA} resource.
 * @param runtimeComponentInstanceId Hint for a better guessing of a {@value RES_TYPE#DATA} resource.
 * @return a valid URI.
 * @throws URISyntaxException
 */
public URI getResource(String resourcePath, RES_TYPE type, String componentTypeId,
        String runtimeComponentInstanceId) throws URISyntaxException {
    URI uri = null;
    File resFilePath = null;

    try {
        URL url = new URL(resourcePath);
        AstericsErrorHandling.instance.getLogger().fine("Resource URL: " + url);
        uri = url.toURI();
    } catch (MalformedURLException e) {
        //Fix the string first, because it could have \ and / mixed up and stuff and convert it to path with unix-style path seperator (/)
        //Thanks to apache commons io lib this is very easy!! :-)
        final String resourcePathSlashified = FilenameUtils.separatorsToUnix(resourcePath);
        //AstericsErrorHandling.instance.getLogger().fine("resourceNameArg: "+resourcePath+", resourceName after normalization: "+resourcePathSlashified+", concat: "+FilenameUtils.concat(getAREBaseURI().getPath(), resourcePath));

        File resourceNameAsFile = new File(resourcePathSlashified);
        //AstericsErrorHandling.instance.getLogger().fine("resourceName: "+resourcePathSlashified+", resourceNameAsFile: "+resourceNameAsFile+", resourceNameAsFile.toURI: "+resourceNameAsFile.toURI());

        if (!resourceNameAsFile.isAbsolute()) {
            switch (type) {
            case MODEL:
                resFilePath = resolveRelativeFilePath(toAbsolute(MODELS_FOLDER), resourcePathSlashified, false);
                break;
            case PROFILE:
                resFilePath = resolveRelativeFilePath(toAbsolute(PROFILE_FOLDER), resourcePathSlashified,
                        false);
                break;
            case LICENSE:
                resFilePath = resolveRelativeFilePath(toAbsolute(LICENSES_FOLDER), resourcePathSlashified,
                        false);
                break;
            case DATA:
                /*
                 * 1) Check resourceName directly, if it exists return
                 * 2) Check resourceName with exactly matching componentTypeId, if it exists return
                 * 3) Check resourceName with first subfolder containing componentTypeId, if it exists return
                 * 4) Check all subfolders (only first level) and resolve against the given resourceName, if it exists return 
                 */
                URI dataFolderURI = toAbsolute(DATA_FOLDER);
                File dataFolderFile = ResourceRegistry.toFile(dataFolderURI);

                //1) Check resourceName directly, if it exists return
                resFilePath = resolveRelativeFilePath(dataFolderFile, resourcePathSlashified, false);
                if (resFilePath.exists()) {
                    break;
                }

                if (componentTypeId != null) {
                    //2) Check resourceName with exactly matching componentTypeId, if it exists return
                    resFilePath = resolveRelativeFilePath(dataFolderFile,
                            componentTypeId + "/" + resourcePathSlashified, false);
                    if (resFilePath.exists()) {
                        break;
                    }

                    //3) Check resourceName with first subfolder containing componentTypeId (but only last part of asterics.facetrackerLK or sensor.facetrackerLK)
                    //if it exists return
                    String[] componentTypeIdSplit = componentTypeId.split("\\.");
                    //split returns the given string as element 0 if the regex patterns was not found.
                    final String componentTypeIdLC = componentTypeIdSplit[componentTypeIdSplit.length - 1]
                            .toLowerCase();

                    File[] dataSubFolderFiles = dataFolderFile.listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File dirFile) {
                            //AstericsErrorHandling.instance.getLogger().fine("Step3, dirFile: "+dirFile);
                            if (dirFile.isDirectory() && dirFile.exists()) {
                                //lowercase name contains lowercase componentTypeId
                                return (dirFile.getName().toLowerCase().indexOf(componentTypeIdLC) > -1);
                            }
                            return false;
                        }
                    });
                    //AstericsErrorHandling.instance.getLogger().fine("Data, Step3, resourceName="+resourceName+", componentTypeIdLC="+componentTypeIdLC+", runtimeComponentInstanceId="+runtimeComponentInstanceId+", dataSubFolderFiless <"+Arrays.toString(dataSubFolderFiles)+">");
                    if (dataSubFolderFiles.length > 0) {
                        resFilePath = resolveRelativeFilePath(dataSubFolderFiles[0], resourcePathSlashified,
                                false);
                        if (resFilePath.exists()) {
                            break;
                        }
                    }
                }

                //4) Check all subfolders (only first level) and resolve against the given resourceName, if it exists return
                File[] dataSubFolderFiles = dataFolderFile.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File dirFile) {
                        //AstericsErrorHandling.instance.getLogger().fine("Step3, dirFile: "+dirFile);
                        if (dirFile.isDirectory() && dirFile.exists()) {
                            File resourceFile;
                            //resourceFile = toFile(dirFile.toURI().resolve(resourceName));
                            resourceFile = resolveRelativeFilePath(dirFile, resourcePathSlashified, false);
                            return resourceFile.exists();
                        }
                        return false;
                    }
                });
                //AstericsErrorHandling.instance.getLogger().fine("Data, Step4, resourceName="+resourceName+", componentTypeId="+componentTypeId+", runtimeComponentInstanceId="+runtimeComponentInstanceId+", dataSubFolderFiless <"+Arrays.toString(dataSubFolderFiles)+">");
                if (dataSubFolderFiles.length > 0) {
                    resFilePath = resolveRelativeFilePath(dataSubFolderFiles[0], resourcePathSlashified, false);
                    if (resFilePath.exists()) {
                        break;
                    }
                }

                break;
            case IMAGE:
                resFilePath = resolveRelativeFilePath(toAbsolute(IMAGES_FOLDER), resourcePathSlashified, false);
                break;
            case STORAGE:
                resFilePath = resolveRelativeFilePath(toAbsolute(STORAGE_FOLDER), resourcePathSlashified,
                        false);
                break;
            case TMP:
                resFilePath = resolveRelativeFilePath(toAbsolute(TMP_FOLDER), resourcePathSlashified, false);
                break;
            default:
                resFilePath = resolveRelativeFilePath(getAREBaseURIFile(), resourcePathSlashified, false);
                break;
            }

            uri = resFilePath.toURI();
        } else {
            uri = resourceNameAsFile.toURI();
        }
    }
    //System.out.println("file absolute: "+resourceNameAsFile.isAbsolute()+", uri absolute: "+uri.isAbsolute()+", uri opaque: "+uri.isOpaque());
    //System.out.println("resource File.toURI: "+resourceNameAsFile.toURI());
    //AstericsErrorHandling.instance.getLogger().fine("URI before normalize: "+uri.normalize());
    if (uri != null) {
        uri = uri.normalize();
    }
    AstericsErrorHandling.instance.getLogger()
            .fine("resourceName=" + resourcePath + ", componentTypeId=" + componentTypeId
                    + ", runtimeComponentInstanceId=" + runtimeComponentInstanceId + ", Resource URI <" + uri
                    + ">");
    return uri;
}

From source file:com.moro.synapsemod.MainActivity.java

private void dialogo_restaurar() {

    File ficheros = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
            + getString(R.string.dir_backups));
    FileFilter ff = new FileFilter() {
        @Override/*w  ww  .  j ava 2 s.c  o  m*/
        public boolean accept(File pathname) {
            String ruta;
            if (pathname.isFile()) {
                ruta = pathname.getAbsolutePath().toLowerCase();
                //compruebo que el nombre completo, con ruta, del archivo tiene la extensin que yo uso en la apk para backups
                if (ruta.contains("." + getString(R.string.ext_backups))) {
                    return true;
                }
            }
            return false;
        }
    };
    File fa[] = ficheros.listFiles(ff);
    if (fa.length == 0) {
        Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.no_backups),
                Toast.LENGTH_LONG);
        toast.show();
    } else {

        AdapterBackups ab = new AdapterBackups();
        ab.AdapterBackups(this, fa);
        ListView lista = new ListView(this);
        lista.setAdapter(ab);
        lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view.findViewById(android.R.id.text1);
                String archivo = tv.getText().toString();
                dlg_restaurar.dismiss();
                dlg_restaurar = null;
                File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
                        + getString(R.string.dir_backups) + archivo + "." + getString(R.string.ext_backups));
                //compruebo que fsicamente existe de verdad (otra vez)
                if (f.exists())
                    confirmar_restaurar(archivo);
                else {
                    Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.no_backups),
                            Toast.LENGTH_LONG);
                    toast.show();
                }
            }
        });
        AlertDialog.Builder abd = new AlertDialog.Builder(this);
        abd.setTitle(R.string.dlg_restore_title);
        abd.setMessage(R.string.dlg_restore_message);
        abd.setIcon(R.drawable.ic_action_restore);
        abd.setView(lista);
        dlg_restaurar = abd.create();
        dlg_restaurar.show();
    }

}

From source file:com.xtructure.xevolution.gui.XEvolutionGui.java

/**
 * Creates a background thread to watch the output directory where.
 * /*from  w  ww  .java2  s .co m*/
 * {@link Population} xml files are written. The thread polls the file
 * system once every two seconds for new files.
 */
public void watchDir() {
    watchDirThread = new Thread(new Runnable() {
        private long newest = 0l;

        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            if (OUTPUT_OPTION.hasValue()) {
                File watchDir = OUTPUT_OPTION.processValue();
                populationFiles.clear();
                populationPanel.removeAllItems();
                while (true) {
                    File[] newFiles = watchDir.listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File pathname) {
                            return pathname.lastModified() > newest && pathname.getName().endsWith(".xml");
                        }
                    });
                    if (newFiles.length == 0) {
                        try {
                            // polling for now...
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            break;
                        }
                        continue;
                    }
                    List<File> newFilesList = Arrays.asList(newFiles);
                    Collections.sort(newFilesList, new Comparator<File>() {
                        @Override
                        public int compare(File o1, File o2) {
                            Matcher matcher = POPULATION_FILE_PATTERN.matcher(o1.getName());
                            if (matcher.matches()) {
                                int age1 = Integer.parseInt(matcher.group(1));
                                matcher = POPULATION_FILE_PATTERN.matcher(o2.getName());
                                if (matcher.matches()) {
                                    int age2 = Integer.parseInt(matcher.group(1));
                                    return age1 - age2;
                                }
                            }
                            return o1.compareTo(o2);
                        }
                    });
                    populationFiles.addAll(newFilesList);
                    populationPanel.addAllItems(newFilesList);
                    XEvolutionGui.this.statusBar.startProgressBar(0, newFilesList.size());
                    int i = 0;
                    for (File populationFile : newFilesList) {
                        newest = Math.max(newest, populationFile.lastModified());
                        statusBar.setProgressBar(i++);
                        statusBar.setMessage("Loading population : " + populationFile.getName());
                        Population<?> population = null;
                        for (int j = 0; j < RETRIES; j++) {
                            popLock.lock();
                            try {
                                population = dataTracker.processPopulation(populationFile);
                                for (@SuppressWarnings("rawtypes")
                                final XValId valueId : population.getGenomeAttributeIds()) {
                                    Graph graph = graphsMap.get(valueId);
                                    if (graph == null) {
                                        graph = addGraph(valueId);
                                    }
                                    graph.addData(
                                            //
                                            ((Number) population.getHighestGenomeByAttribute(valueId)
                                                    .getAttribute(valueId)).doubleValue(), //
                                            population.getAverageGenomeAttribute(valueId), //
                                            ((Number) population.getLowestGenomeByAttribute(valueId)
                                                    .getAttribute(valueId)).doubleValue());
                                }
                                // success
                                break;
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                popLock.unlock();
                            }
                            // failed to read population, wait and try again
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        if (population == null) {
                            // failed to read population. we know there was
                            // a population, so add dummy data as a place
                            // holder
                            for (XValId<?> valueId : graphsMap.keySet()) {
                                Graph graph = graphsMap.get(valueId);
                                if (graph == null) {
                                    graph = new Graph(valueId.getBase(), bufferSize, 3);
                                    graphsMap.put(valueId, graph);
                                    menuBar.addGraphCheckbox(graph, graphPanel, false);
                                }
                                graph.addData(0.0, 0.0, 0.0);
                            }
                        }
                        frame.repaint();
                    }
                    statusBar.clearMessage();
                    statusBar.clearProgressBar();
                }
            }
        }
    });
    watchDirThread.start();
}

From source file:net.pms.external.ExternalFactory.java

/**
 * This method scans the plugins directory for ".jar" files and processes
 * each file that is found. First, a resource named "plugin" is extracted
 * from the jar file. Its contents determine the name of the main plugin
 * class. This main plugin class is then loaded and an instance is created
 * and registered for later use.//w ww. j  av a 2s. c  o m
 */
public static void lookup() {
    // Start by purging files
    purgeFiles();
    File pluginsFolder = new File(configuration.getPluginDirectory());
    LOGGER.info("Searching for plugins in " + pluginsFolder.getAbsolutePath());

    try {
        FilePermissions permissions = new FilePermissions(pluginsFolder);
        if (!permissions.isFolder()) {
            LOGGER.warn("Plugins folder is not a folder: " + pluginsFolder.getAbsolutePath());
            return;
        }
        if (!permissions.isBrowsable()) {
            LOGGER.warn("Plugins folder is not readable: " + pluginsFolder.getAbsolutePath());
            return;
        }
    } catch (FileNotFoundException e) {
        LOGGER.warn("Can't find plugins folder: {}", e.getMessage());
        return;
    }

    // Find all .jar files in the plugin directory
    File[] jarFiles = pluginsFolder.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.isFile() && file.getName().toLowerCase().endsWith(".jar");
        }
    });

    int nJars = (jarFiles == null) ? 0 : jarFiles.length;

    if (nJars == 0) {
        LOGGER.info("No plugins found");
        return;
    }

    // To load a .jar file the filename needs to converted to a file URL
    List<URL> jarURLList = new ArrayList<>();

    for (int i = 0; i < nJars; ++i) {
        try {
            jarURLList.add(jarFiles[i].toURI().toURL());
        } catch (MalformedURLException e) {
            LOGGER.error("Can't convert file path " + jarFiles[i] + " to URL", e);
        }
    }

    URL[] jarURLs = new URL[jarURLList.size()];
    jarURLList.toArray(jarURLs);

    // Load the jars
    loadJARs(jarURLs, false);

    // Instantiate the early external listeners immediately.
    instantiateEarlyListeners();
}

From source file:de.pksoftware.springstrap.fs.service.LocalFileSystemService.java

@Override
public void copyFolder(ItemVisibility visibility, FileSystemBucket bucket, IFileSystemPath srcPath,
        IFileSystemPath destPath, String[] excludeAntPattern)
        throws NotAFolderException, FSIOException, NoSuchFolderException {
    File srcFolder = getItem(visibility, bucket, srcPath);

    if (!srcFolder.exists()) {
        throw new NoSuchFolderException(bucket, srcPath);
    }// ww w  . j  av  a 2 s  . com

    if (!srcFolder.isDirectory()) {
        throw new NotAFolderException(bucket, srcPath);
    }

    File destFolder = getItem(visibility, bucket, destPath);

    if (destFolder.exists() && !destFolder.isDirectory()) {
        throw new NotAFolderException(bucket, destPath);
    }

    try {
        FileUtils.copyDirectory(srcFolder, destFolder, new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                for (String antPattern : excludeAntPattern) {
                    String absAntPattern = srcFolder.getAbsolutePath() + "/" + antPattern;

                    //logger.info("Testing {} against {}", absAntPattern, pathname.getAbsolutePath());

                    if (antPathMatcher.match(absAntPattern, pathname.getAbsolutePath())) {
                        return false;
                    }
                }

                return true;
            }

        });
    } catch (IOException e) {
        throw new FSIOException(bucket, srcPath, "copyFolder", e);
    }

}

From source file:dk.statsbiblioteket.doms.radiotv.extractor.transcoder.OutputFileUtil.java

private static boolean hasSnapshot(TranscodeRequest request, final ServletConfig config) {
    final String uuid = request.getPid();
    final FileFilter filter = new FileFilter() {
        @Override/*from  w w w.  j  av a  2 s . c  o m*/
        public boolean accept(File pathname) {
            return pathname.getName().startsWith(uuid + ".") && !pathname.getName().contains("preview")
                    && pathname.getName()
                            .endsWith(Util.getInitParameter(config, Constants.SNAPSHOT_FINAL_FORMAT));
        }
    };
    File outputDir = getOutputDir(request, config);
    final File[] files = outputDir.listFiles(filter);
    if (files != null && files.length > 0) {
        log.debug("Found existing output file '" + files[0].getAbsolutePath() + "'");
    }
    return files.length > 0;
}

From source file:com.ibm.team.build.internal.hjplugin.RTCFacadeFactory.java

private static URL[] getToolkitJarURLs(File toolkitFile, PrintStream debugLog) throws IOException {
    File[] files = toolkitFile.listFiles(new FileFilter() {
        public boolean accept(File file) {
            return file.getName().toLowerCase().endsWith(".jar") && !file.isDirectory(); //$NON-NLS-1$
        }/*from   w ww .  j a  va 2s.c om*/
    });
    if (files == null) {
        throw new RuntimeException(Messages.RTCFacadeFactory_scan_error(toolkitFile.getAbsolutePath()));
    }

    // Log what we found 
    if (LOGGER.isLoggable(Level.FINER) || debugLog != null) {
        String eol = System.getProperty("line.separator"); //$NON-NLS-1$
        StringBuilder message = new StringBuilder("Found ").append(files.length) //$NON-NLS-1$
                .append(" jars in ").append(toolkitFile.getAbsolutePath()).append(eol); //$NON-NLS-1$
        for (File file : files) {
            message.append(file.getName()).append(eol);
        }

        debug(debugLog, message.toString());
    }

    URL[] urls = new URL[files.length];
    for (int i = 0; i < files.length; ++i) {
        urls[i] = files[i].toURI().toURL();
    }
    return urls;
}