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:cd.education.data.collector.android.tasks.FormLoaderTask.java

@SuppressWarnings("unchecked")
private void loadExternalData(File mediaFolder) {
    // SCTO-594/*from w w w . j a  v a 2s.c o m*/
    File[] zipFiles = mediaFolder.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.getName().toLowerCase().endsWith(".zip");
        }
    });

    if (zipFiles != null) {
        ZipUtils.unzip(zipFiles);
        for (File zipFile : zipFiles) {
            boolean deleted = zipFile.delete();
            if (!deleted) {
                Log.w(t, "Cannot delete " + zipFile + ". It will be re-unzipped next time. :(");
            }
        }
    }

    File[] csvFiles = mediaFolder.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            String lowerCaseName = file.getName().toLowerCase();
            return lowerCaseName.endsWith(".csv") && !lowerCaseName.equalsIgnoreCase(ITEMSETS_CSV);
        }
    });

    Map<String, File> externalDataMap = new HashMap<String, File>();

    if (csvFiles != null) {

        for (File csvFile : csvFiles) {
            String dataSetName = csvFile.getName().substring(0, csvFile.getName().lastIndexOf("."));
            externalDataMap.put(dataSetName, csvFile);
        }

        if (externalDataMap.size() > 0) {

            publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_csv_message));

            ExternalDataReader externalDataReader = new ExternalDataReaderImpl(this);
            externalDataReader.doImport(externalDataMap);
        }
    }
}

From source file:com.andrada.sitracker.ui.fragment.DirectoryChooserFragment.java

/**
 * Change the directory that is currently being displayed.
 *
 * @param dir The file the activity should switch to. This File must be
 *            non-null and a directory, otherwise the displayed directory
 *            will not be changed//  w w w  .  j  ava  2  s. c  o  m
 */
private void changeDirectory(@Nullable File dir) {
    if (dir == null) {
        debug("Could not change folder: dir was null");
    } else if (!dir.isDirectory() && !mIsDirectoryChooser) {
        debug("Could not change folder: dir is no directory, selecting file");
        //Selecting file
        mSelectedFile = dir;
        mTxtvSelectedFolder.setText(dir.getAbsolutePath());
        if (isAdded()) {
            mTxtvSelectedFolderLabel.setText(getResources().getString(R.string.fp_selected_file_label));
        }
        if (isValidFile(mSelectedFile)) {
            returnSelectedFile();
        }
    } else {
        File[] contents = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(@NotNull File file) {
                return !file.isHidden();
            }
        });
        if (contents != null) {
            int numDirectories = 0;
            if (mIsDirectoryChooser) {
                for (File f : contents) {
                    if (f.isDirectory()) {
                        numDirectories++;
                    }
                }
            } else {
                numDirectories = contents.length;
            }

            mFilesInDir = new File[numDirectories];
            mFilenames.clear();
            for (int i = 0, counter = 0; i < numDirectories; counter++) {
                if ((mIsDirectoryChooser && contents[counter].isDirectory()) || !mIsDirectoryChooser) {
                    mFilesInDir[i] = contents[counter];
                    mFilenames.add(
                            new FileDescriptor(contents[counter].getName(), contents[counter].isDirectory()));
                    i++;
                }
            }
            Arrays.sort(mFilesInDir, new Comparator<File>() {
                @Override
                public int compare(@NotNull File aThis, @Nullable File aThat) {
                    final int BEFORE = -1;
                    final int EQUAL = 0;
                    final int AFTER = 1;
                    if (aThis == aThat) {
                        return EQUAL;
                    }
                    if (aThat == null) {
                        return BEFORE;
                    }
                    //Compare by type first
                    if (aThis.isDirectory() && !aThat.isDirectory()) {
                        return BEFORE;
                    }
                    if (!aThis.isDirectory() && aThat.isDirectory()) {
                        return AFTER;
                    }
                    //Compare by filename
                    int comparison = aThis.getName().compareTo(aThat.getName());
                    if (comparison != EQUAL) {
                        return comparison;
                    }

                    return EQUAL;
                }
            });
            Collections.sort(mFilenames);
            mSelectedDir = dir;
            mSelectedFile = null;
            if (isAdded()) {
                mTxtvSelectedFolderLabel.setText(getResources().getString(R.string.fp_selected_folder_label));
            }
            mTxtvSelectedFolder.setText(dir.getAbsolutePath());
            mListDirectoriesAdapter.notifyDataSetChanged();
            mFileObserver = createFileObserver(dir.getAbsolutePath());
            mFileObserver.startWatching();
            debug("Changed directory to %s", dir.getAbsolutePath());
        } else {
            debug("Could not change folder: contents of dir were null");
        }
    }
    refreshButtonState();
}

From source file:edu.stanford.epad.common.util.EPADFileUtils.java

/**
 * Count the total number of files in a directory with a give ending. Recursively descend down the directory
 * structure.//  w  w w  .  j a  v a  2 s.c o m
 * 
 * @param dir File
 * @param ending String
 * @return int total files with this ending.
 */
public static int countFilesWithEnding(File dir, final String ending) {
    if (!dir.isDirectory()) {
        throw new IllegalStateException("Not a directory: " + dir.getAbsolutePath());
    }

    File[] files = dir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.getName().toLowerCase().endsWith(ending);
        }
    });
    if (files == null) {
        return 0;
    }
    int count = files.length;
    for (File currFile : files) {
        if (currFile.isDirectory()) {
            count += countFilesWithEnding(currFile, ending);
        }
    }

    return count;
}

From source file:com.manydesigns.portofino.pageactions.AbstractPageAction.java

/**
 * Updates the page with values from the page configuration. Can be called to re-use the standard page
 * configuration form. Should be called only after validatePageConfiguration() returned true.
 * @return true iff the page was correctly saved.
 *///from w ww  .j  a v  a  2 s  .  c  o  m
protected boolean updatePageConfiguration() {
    EditPage edit = new EditPage();
    pageConfigurationForm.writeToObject(edit);
    Page page = pageInstance.getPage();
    page.setTitle(edit.title);
    page.setDescription(edit.description);
    page.setNavigationRoot(edit.navigationRoot.name());
    page.getLayout().setTemplate(edit.template);
    page.getDetailLayout().setTemplate(edit.detailTemplate);
    try {
        File pageFile = DispatcherLogic.savePage(pageInstance.getDirectory(), page);
        logger.info("Page saved to " + pageFile.getAbsolutePath());
    } catch (Exception e) {
        logger.error("Couldn't save page", e);
        return false; //TODO handle return value + script + session msg
    }
    if (edit.applyTemplateRecursively) {
        FileFilter filter = new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.isDirectory();
            }
        };
        updateTemplate(pageInstance.getDirectory(), filter, edit);
    }
    Subject subject = SecurityUtils.getSubject();
    if (SecurityLogic.hasPermissions(portofinoConfiguration, getPageInstance(), subject, AccessLevel.DEVELOP)) {
        updateScript();
    }
    return true;
}

From source file:interactivespaces.workbench.InteractiveSpacesWorkbench.java

/**
 * Walk over a set of folders looking for project files to build.
 *
 * @param baseDir/*from  w ww .  j  a v a  2s  .  c  o m*/
 *          base file to start looking for projects in
 * @param commands
 *          commands to run on all project files
 *
 * @return {@code true} if the tree was walked successfully
 */
private boolean doCommandsOnTree(File baseDir, List<String> commands) {
    FileFilter filter = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    };
    File[] files = baseDir.listFiles(filter);
    boolean success = true;
    if (files != null) {
        for (File possible : files) {
            success &= doCommandsOnTree(possible, commands, filter);
        }
    }

    // Walking the tree implicitly consumes all the commands, so clear them out
    // here.
    commands.clear();

    return success;
}

From source file:net.unicon.demetrius.fac.filesystem.FsResourceFactory.java

/**
 * Returns the contents of a given folder.
 * @param f//from w  w w  .  j a v  a2 s.  c o  m
 *  The <code>IFolder</code> for which the contents will be returned.
 * @return
 *  An array of <code>IResource</code> objects for the given folder.
 */
public IResource[] getContents(IFolder f) {
    // assertions
    if (f == null) {
        throw new IllegalArgumentException("The given " + "resource must not be null.");
    }

    IResource[] contents = new IResource[0];
    File dir = new File(evaluateFsPath(dataSource, f));
    ;

    File[] folderTypes = dir.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    });

    File[] fileTypes = dir.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.isFile();
        }
    });

    File[] files = null;
    if (folderTypes != null && fileTypes != null) {
        files = new File[folderTypes.length + fileTypes.length];
        System.arraycopy(folderTypes, 0, files, 0, folderTypes.length);
        System.arraycopy(fileTypes, 0, files, folderTypes.length, fileTypes.length);
    } else if (fileTypes != null) {
        files = fileTypes;
    } else if (folderTypes != null) {
        files = folderTypes;
    }

    if (files != null) {
        contents = new IResource[files.length];
        File curr = null;
        for (int i = 0; i < files.length; i++) {
            curr = files[i];
            if (curr.isDirectory()) {
                IResource resource = new FolderImpl(curr.getName(), this, 0, new Date(curr.lastModified()), f,
                        curr.isHidden());
                contents[i] = resource;

            } else {
                IResource resource = new FileImpl(curr.getName(), this, curr.length(),
                        new Date(curr.lastModified()), f, curr.isHidden(), null);
                contents[i] = resource;
            }
        }
    }

    return contents;
}

From source file:com.symbian.driver.core.controller.SymbianVisitor.java

/**
 * Installs the current task if necessary.
 * /*from www. jav a  2  s.c  om*/
 * @param aTask
 *            The current task to install.
 * @param aExecuteTransferSet
 *            The transfer set relating to the current tasks.
 * @param aBase
 *            The base repository directory to install from.
 * @return <code>true</code> if no failures occurd during the
 *         installation, <code>false</code> otherwise
 * @throws ParseException
 *             If there was a configuration exception.
 */
private Map<Exception, ESeverity> install(final Task aTask) {
    LOGGER.entering(this.getClass().getName(), "install");

    HashMap<File, File> lEmulatorHashBackup = null;
    Map<Exception, ESeverity> lExceptions = new HashMap<Exception, ESeverity>();
    TDConfig CONFIG = TDConfig.getInstance();
    String ltaskName = ((ExecuteTransferSet) aTask.getTransferSet()).getName();
    boolean lPlatSec = true;
    try {
        //lPlatSec = CONFIG.isPreference(TDConfig.PLATSEC) && !CONFIG.isPreference(TDConfig.SYS_BIN);
        lPlatSec = !CONFIG.isPreference(TDConfig.SYS_BIN);
    } catch (ParseException e) {
        LOGGER.log(Level.WARNING, "Could not get the configuration for PlatSec. Defaulting to ON");
    }

    try {

        // Install the SIS file or Repository
        if (lPlatSec) {
            // PlatSec ON

            File lBaseDirectory = getBaseDirectory(aTask);
            if (lBaseDirectory == null) {
                return lExceptions;
            }

            File[] lFile = lBaseDirectory.listFiles(new FileFilter() {
                public boolean accept(File lTestFile) {
                    if (lTestFile.getName().toLowerCase().startsWith("testdriver_") && lTestFile.getName()
                            .toLowerCase().endsWith(com.symbian.driver.core.environment.ILiterals.SIS)) {
                        return true;
                    }
                    return false;
                }
            });

            if (lFile == null) {
                LOGGER.fine("The repository is empty at: " + lBaseDirectory);
            } else if (lFile.length == 1) {

                File lSisFile = lFile[0];

                LOGGER.fine("Setting SIS File to: " + lSisFile.getCanonicalPath());

                // ////////////////////////////////////////
                //  EMULATOR  to delete: Moves the emulator files
                // Replace with buildrom -> emulatorbuild
                lEmulatorHashBackup = EmulatorPreProcessor.backupEmulator(lSisFile);

                ((ExecuteTransferSet) aTask.getTransferSet()).installSis(lSisFile);

            } else if (lFile.length > 1) {
                throw new IOException("There are too many SIS files at: " + ltaskName
                        + ". Please delete your repository and rebuild.");

            }

        } else {
            // PlatSec OFF
            LOGGER.fine("Installing Repository Directory with PlatSec Off");

            ((ExecuteTransferSet) aTask.getTransferSet()).installRepository();
        }

    } catch (IOException lIOException) {

        LOGGER.log(Level.SEVERE, "Installation/copying of repository " + ltaskName + " failed due IO Error",
                lIOException);
        lExceptions.put(lIOException, ESeverity.ERROR);

    } catch (TimeLimitExceededException lTimeLimitExceededException) {

        LOGGER.log(Level.SEVERE, "Installation/copying of repository " + ltaskName + " failed due to time out.",
                lTimeLimitExceededException);
        lExceptions.put(lTimeLimitExceededException, ESeverity.ERROR);

    } finally {
        EmulatorPreProcessor.restoreEmulator(lEmulatorHashBackup);
    }

    return lExceptions;
}

From source file:hudson.matrix.MatrixProject.java

/**
 * Rebuilds the {@link #configurations} list and
 * {@link #activeConfigurations}.//  ww w  .  j a  va2s  .  c om
 */
void rebuildConfigurations() throws IOException {
    // backward compatibility check to see if there's any data in the old structure
    // if so, bring them to the newer structure.
    File[] oldDirs = getConfigurationsDir().listFiles(new FileFilter() {
        public boolean accept(File child) {
            return child.isDirectory() && !child.getName().startsWith("axis-");
        }
    });
    //TODO seems oldDir is always null and old matrix configuration is not cleared.
    if (oldDirs != null) {
        // rename the old directory to the new one
        for (File dir : oldDirs) {
            try {
                Combination c = Combination.fromString(dir.getName());
                dir.renameTo(getRootDirFor(c));
            } catch (IllegalArgumentException e) {
                // it's not a configuration dir. Just ignore.
            }
        }
    }

    CopyOnWriteMap.Tree<Combination, MatrixConfiguration> configurations = new CopyOnWriteMap.Tree<Combination, MatrixConfiguration>();
    loadConfigurations(getConfigurationsDir(), configurations, Collections.<String, String>emptyMap());
    this.configurations = configurations;

    // find all active configurations
    Set<MatrixConfiguration> active = new LinkedHashSet<MatrixConfiguration>();
    AxisList axes = getAxes();
    if (!CollectionUtils.isEmpty(axes)) {
        for (Combination c : axes.list()) {
            String combinationFilter = getCombinationFilter();
            if (c.evalScriptExpression(axes, combinationFilter)) {
                LOGGER.fine("Adding configuration: " + c);
                MatrixConfiguration config = configurations.get(c);
                if (config == null) {
                    config = new MatrixConfiguration(this, c);
                    config.save();
                    configurations.put(config.getCombination(), config);
                }
                active.add(config);
            }
        }
    }
    this.activeConfigurations = active;
}

From source file:com.scooter1556.sms.server.controller.MediaController.java

@RequestMapping(value = "/files", method = RequestMethod.GET)
public ResponseEntity<List<Directory>> getDirectoryList(
        @RequestParam(value = "path", required = false) String path) {
    List<Directory> directories = new ArrayList<>();
    File[] files = null;/*from   w w  w  .j  av  a 2 s . c o  m*/

    // If no path is specified return roots
    if (path == null) {
        if (SystemUtils.IS_OS_WINDOWS) {
            files = File.listRoots();
        } else if (SystemUtils.IS_OS_LINUX) {
            files = new File("/").listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    return file.isDirectory();
                }
            });
        }
    } else {
        // Return directory list for given path
        File file = new File(path);

        if (!file.isDirectory()) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        files = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.isDirectory();
            }
        });
    }

    // Check if there is anything to return
    if (files == null || files.length == 0) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    // Convert files to directory list
    for (File file : files) {
        directories.add(new Directory(file.getName(), file.getAbsolutePath()));
    }

    return new ResponseEntity<>(directories, HttpStatus.OK);
}

From source file:net.dmulloy2.ultimatearena.UltimateArena.java

private void loadArenas() {
    File folder = new File(getDataFolder(), "arenas");
    File[] children = folder.listFiles(new FileFilter() {
        @Override//from   w  w w .  ja  va2s  . c o  m
        public boolean accept(File file) {
            return file.getName().endsWith(".dat");
        }
    });

    if (children == null || children.length == 0)
        return;

    for (File file : children) {
        loadArena(file);
    }

    logHandler.log("Loaded {0} arenas.", loadedArenas.size());
}