Example usage for org.apache.commons.io.filefilter DirectoryFileFilter INSTANCE

List of usage examples for org.apache.commons.io.filefilter DirectoryFileFilter INSTANCE

Introduction

In this page you can find the example usage for org.apache.commons.io.filefilter DirectoryFileFilter INSTANCE.

Prototype

IOFileFilter INSTANCE

To view the source code for org.apache.commons.io.filefilter DirectoryFileFilter INSTANCE.

Click Source Link

Document

Singleton instance of directory filter.

Usage

From source file:com.thruzero.common.core.fs.HierarchicalFileWalker.java

/**
 * Constructs a walker for the given {@code rootDirectory} using the given {@code filter} and {@code sortDirection}. If the {@code filter} is an instance of
 * {@code FileAndDirectoryFilter}, then the {@code fileFilter} component will be used to filter files and the {@code directoryFilter} component will be used
 * to filter directories. Otherwise, directories are implicitly accepted and files are filtered using the given {@code filter}. If the given {@code filter} is
 * null, then all files and directories will be processed.
 * /*ww w . jav a 2  s . co  m*/
 * @param rootDirectory
 *          starting point.
 * @param filter
 *          use {@link org.apache.commons.io.filefilter.TrueFileFilter#INSTANCE} to process all files.
 * @param sortDirection
 *          if present, files will be sorted in the direction indicated; otherwise, no sorting will take place.
 */
public HierarchicalFileWalker(final File rootDirectory, final FileFilter filter,
        final SortDirection sortDirection) {
    this.rootDirectory = rootDirectory;
    if (filter == null) {
        // default filter returns everything
        this.filter = new FileAndDirectoryFilter((FileFilter) DirectoryFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
    } else if (filter instanceof FileAndDirectoryFilter) {
        this.filter = (FileAndDirectoryFilter) filter;
    } else {
        this.filter = new FileAndDirectoryFilter(DirectoryFileFilter.INSTANCE, filter);
    }
    this.fileSortComparator = new FileSortComparator(sortDirection);
}

From source file:de.vandermeer.skb.datatool.commons.DataSetLoader.java

/**
 * Loads a data set with entries, does consistency checks, marks errors, translates encodings.
 * The local link map will be cleared./*from  www  . j  ava2  s  . co m*/
 * @param entryType the data entry type
 * @param excluded a set of characters excluded from translations, null or empty if not applicable
 * @return a fully loaded, checked data set on success, null on error (errors are logged)
 */
default DataSet<E> loadFiles(DataEntryType entryType, String[] excluded) {
    IOFileFilter fileFilter = new WildcardFileFilter(
            new String[] { "*." + entryType.getInputFileExtension() + ".json" });
    DirectoryLoader dl = new CommonsDirectoryWalker(this.getCs().getInputDir(), DirectoryFileFilter.INSTANCE,
            fileFilter);
    if (dl.getLoadErrors().size() > 0) {
        Skb_Console.conError("{}: errors loading files from directory <{}>\n{}", new Object[] {
                this.getCs().getAppName(), this.getCs().getInputDir(), dl.getLoadErrors().render() });
        return null;
    }

    DataSet<E> ds = this.newSetInstance();
    FileSourceList fsl = dl.load();
    ds.load(fsl.getSource(), entryType.getInputFileExtension());
    return ds;
}

From source file:ijfx.core.imagedb.DefaultExplorerService.java

public static IOFileFilter getDirectoryFilter() {
    return DirectoryFileFilter.INSTANCE;
}

From source file:com.hp.application.automation.tools.run.SvExportBuilder.java

/**
 * Cleans all sub-folders containing *.vproj file.
 *///from  w w w .j a  v a2  s.c  om
private void cleanTargetDirectory(PrintStream logger, String targetDirectory) throws IOException {
    File target = new File(targetDirectory);
    if (target.exists()) {
        File[] subfolders = target.listFiles((FilenameFilter) DirectoryFileFilter.INSTANCE);
        if (subfolders.length > 0) {
            logger.println("  Cleaning target directory...");
        }
        for (File subfolder : subfolders) {
            if (subfolder.listFiles((FilenameFilter) new SuffixFileFilter(".vproj")).length > 0) {
                logger.println("    Deleting subfolder of target directory: " + subfolder.getAbsolutePath());
                FileUtils.deleteDirectory(subfolder);
            } else {
                logger.println("    Skipping delete of directory '" + subfolder.getAbsolutePath()
                        + "' because it does not contain any *.vproj file.");
            }
        }
    }
}

From source file:me.neatmonster.spacertk.actions.FileActions.java

/**
 * Gets a list of directories in a directory
 * @param directory Base directory/*from   w ww.  ja va2 s.  com*/
 * @return List of directories
 */
@Action(aliases = { "listDirectories", "listDirs" })
public List<String> listDirectories(final String directory) {
    return Arrays.asList(new File(directory).list(DirectoryFileFilter.INSTANCE));
}

From source file:com.legstar.cixs.jaxws.gen.Jaxws2CixsGeneratorTest.java

/**
 * Test all standard cases.//from www .  j ava  2s.  c  o m
 * 
 * @throws Exception if generation fails
 */
public void testAllStandard() throws Exception {
    String[] dirs = COXB_DIR.list(DirectoryFileFilter.INSTANCE);
    for (int i = 0; i < dirs.length; i++) {
        String serviceName = FilenameUtils.getBaseName(dirs[i]);
        if (!NON_STANDARD_COXB.contains(serviceName)) {
            generateAndCheck(serviceName, "Dfhcommarea", "Dfhcommarea", false);
        }
    }
}

From source file:com.qwazr.search.index.SchemaInstance.java

SchemaInstance(ExecutorService executorService, File schemaDirectory) throws IOException, ServerException,
        InterruptedException, ReflectiveOperationException, URISyntaxException {
    this.executorService = executorService;
    this.schemaDirectory = schemaDirectory;
    if (!schemaDirectory.exists())
        schemaDirectory.mkdir();//from   www  .j  av a2 s . co  m
    if (!schemaDirectory.exists())
        throw new IOException("The directory does not exist: " + schemaDirectory.getName());
    indexMap = new ConcurrentHashMap<String, IndexInstance>();

    settingsFile = new File(schemaDirectory, SETTINGS_FILE);
    settingsDefinition = settingsFile.exists()
            ? JsonMapper.MAPPER.readValue(settingsFile, SchemaSettingsDefinition.class)
            : SchemaSettingsDefinition.EMPTY;
    checkSettings();

    File[] directories = schemaDirectory.listFiles((FileFilter) DirectoryFileFilter.INSTANCE);
    if (directories == null)
        return;
    for (File indexDirectory : directories)
        indexMap.put(indexDirectory.getName(), IndexInstance.newInstance(this, indexDirectory, null));
    mayBeRefresh();
}

From source file:net.sf.mavenjython.JythonMojo.java

/**
 * Strategy A: include jython in plugin. Extract on the run.
 * /*from  w ww . j a  v a 2 s.  c  o m*/
 * Strategy B: Project also has dependency on jython. We find that jar and
 * extract it and work from there.
 * 
 * B has the benefit that we don't have to update this plugin for every
 * version and the user needs the jython dependency anyway to call the
 * Python Console
 */
public void execute() throws MojoExecutionException {
    setupVariables();

    extractJarToDirectory(jythonArtifact.getFile(), temporaryBuildDirectory);

    // now what? we have the jython content, now we need
    // easy_install
    getLog().info("installing easy_install ...");
    try {
        if (OVERRIDE || !setuptoolsJar.exists()) {
            FileUtils.copyInputStreamToFile(setuptoolsResource.openStream(), setuptoolsJar);
        }
    } catch (IOException e) {
        throw new MojoExecutionException("copying setuptools failed", e);
    }
    extractJarToDirectory(setuptoolsJar, new File(sitepackagesdir, SETUPTOOLS_EGG));
    try {
        IOUtils.write("./" + SETUPTOOLS_EGG + "\n",
                new FileOutputStream(new File(sitepackagesdir, "setuptools.pth")));
    } catch (IOException e) {
        throw new MojoExecutionException("writing path entry for setuptools failed", e);
    }
    getLog().info("installing easy_install done");

    if (libraries == null) {
        getLog().info("no python libraries requested");
    } else {
        getLog().info("installing requested python libraries");
        // then we need to call easy_install to install the other
        // dependencies.
        runJythonScriptOnInstall(temporaryBuildDirectory,
                getEasyInstallArgs("Lib/site-packages/" + SETUPTOOLS_EGG + "/easy_install.py"));
        getLog().info("installing requested python libraries done");
    }

    getLog().info("copying requested libraries");
    /**
     * we installed the packages into our temporary build directory now we
     * want to move these libraries into outputDirectory/Lib
     * 
     * <pre>
     * mv --no-override temporaryBuildDirectory/Lib/site-packages/*.egg/* outputDirectory/Lib/
     * </pre>
     */
    for (File i : sitepackagesdir.listFiles(
            (FileFilter) new AndFileFilter(DirectoryFileFilter.INSTANCE, new SuffixFileFilter(".egg")))) {
        getLog().info("copying " + i + " into " + new File(outputDirectory, "Lib"));
        try {
            FileUtils.deleteDirectory(new File(installlibdir, i.getName()));
        } catch (IOException e) {
        }
        try {
            FileUtils.copyDirectory(i, installlibdir);
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "copying " + i + " to " + new File(outputDirectory, "Lib") + " failed", e);
        }
    }

    /**
     * Setuptools installs a site.py for every package. This might conflict
     * with the jython installation. All it does anyway is help look for
     * eggs, so it wouldn't help us. Errors are ignored here.
     */
    new File(installlibdir, "site.py").delete();
    new File(installlibdir, "site$py.class").delete();
    getLog().info("copying requested libraries done");

    /**
     * If the project does not want its python sources to be in Lib/ it
     * needs to call
     * 
     * PySystemState.addPaths(path, jarFileName + "/myLibFolder");
     * 
     * before starting Python up.
     */
}

From source file:com.xse.optstack.persconftool.base.persistence.PersConfImport.java

/**
 * Actually starts the import of the persconf configuration at the location specified on construction of this
 * importer instance./*from w  w  w. j a  va  2  s .  c  o m*/
 *
 * @return OK_STATUS if the import did fully succeed, any other {@link IStatus} instance if there have been errors
 *         or warnings or the import had to be cancelled due to serious problems.
 */
public IStatus importConfig() {
    final File resourceFolder = new File(
            this.rootFolder.getAbsolutePath() + File.separator + PersConfDefinitions.RESOURCE_FOLDER_NAME);
    if (resourceFolder.exists() && resourceFolder.canExecute()) {
        final Resource resource = this.configResource.getResource();

        final Map<String, EApplication> applicationMap = new HashMap<>();

        boolean hasRootItems = false;
        boolean hasWarnings = false;
        boolean hasErrors = false;
        for (final EGroupType groupType : EGroupType.values()) {
            final File groupFile = new File(
                    resourceFolder.getAbsolutePath() + File.separator + groupType.getLiteral().toLowerCase());
            if (groupFile.exists() && groupFile.canExecute()) {
                hasRootItems = true;

                final EApplicationGroup applicationGroup = PersconfFactory.eINSTANCE.createEApplicationGroup();
                applicationGroup.setType(groupType);
                resource.getContents().add(applicationGroup);

                final Map<String, EInstallRule> installRulesMapping = new HashMap<>();
                final File installRulesFile = new File(
                        groupFile + File.separator + PersConfDefinitions.INSTALL_RULES_FILE);
                if (installRulesFile.exists() && installRulesFile.canRead()) {
                    final GsonBuilder gsonBuilder = new GsonBuilder();
                    final Gson gson = gsonBuilder.create();
                    try (final FileReader reader = new FileReader(installRulesFile.getAbsolutePath())) {
                        final JsonObject fromJson = gson.fromJson(reader, JsonObject.class);
                        for (final Entry<String, JsonElement> entry : fromJson.entrySet()) {
                            final EInstallRule installRule = EInstallRule.get(entry.getValue().getAsString()
                                    .substring(PersConfDefinitions.INSTALL_RULE_PREFIX.length()));
                            if (installRule != null) {
                                installRulesMapping.put(entry.getKey(), installRule);
                            } else {
                                Logger.warn(Activator.PLUGIN_ID,
                                        "Invalid installation rule definition '"
                                                + entry.getValue().getAsString() + "' in group " + groupType
                                                + " group.");
                                hasWarnings = true;
                            }
                        }
                    } catch (final Exception e) {
                        Logger.error(Activator.PLUGIN_ID, "Error parsing " + installRulesFile.getName() + " of "
                                + groupType
                                + " group. Does that file contain valid JSON (e.g. no trailing commas)?", e);
                        hasErrors = true;
                    }
                }

                final File[] groupFiles = groupFile.listFiles((FileFilter) DirectoryFileFilter.INSTANCE);
                if (groupFiles != null) {
                    for (final File appFolder : groupFiles) {
                        if (appFolder.exists() && appFolder.canExecute()) {
                            final EApplication application = PersconfFactory.eINSTANCE.createEApplication();
                            application.setName(appFolder.getName());
                            applicationMap.put(application.getName(), application);
                            if (installRulesMapping.containsKey(appFolder.getName())) {
                                application.setInstallRule(installRulesMapping.get(appFolder.getName()));
                            }
                            applicationGroup.getApplications().add(application);

                            final Map<String, EResource> resources = new HashMap<>();

                            final File installExceptionsFile = new File(appFolder.getAbsolutePath()
                                    + File.separator + PersConfDefinitions.INSTALL_EXCEPTIONS_FILE);
                            if (installExceptionsFile.exists() && installExceptionsFile.canRead()) {
                                final GsonBuilder gsonBuilder = new GsonBuilder();
                                final Gson gson = gsonBuilder.create();
                                try (final FileReader reader = new FileReader(
                                        installExceptionsFile.getAbsolutePath())) {
                                    final JsonObject fromJson = gson.fromJson(reader, JsonObject.class);
                                    for (final Entry<String, JsonElement> entry : fromJson.entrySet()) {
                                        final EInstallException installException = EInstallException
                                                .get(entry.getValue().getAsString().substring(
                                                        PersConfDefinitions.INSTALL_EXCEPTION_PREFIX.length()));
                                        if (installException != null) {
                                            final EResource res = createResource(entry.getKey());
                                            res.setInstallException(installException);
                                            application.getResources().add(res);
                                            resources.put(entry.getKey(), res);
                                        } else {
                                            Logger.warn(Activator.PLUGIN_ID,
                                                    "Invalid installation exception definition: "
                                                            + entry.getValue().getAsString()
                                                            + " of application '" + application.getName()
                                                            + "'.");
                                            hasWarnings = true;
                                        }
                                    }
                                } catch (final Exception e) {
                                    Logger.error(Activator.PLUGIN_ID, "Error parsing install exceptions file '"
                                            + installExceptionsFile.getName() + "' of application '"
                                            + application.getName()
                                            + "'. Does that file contain valid JSON (e.g. no trailing commas)?",
                                            e);
                                    hasErrors = true;
                                }
                            }

                            final File resouceConfigurationFile = new File(appFolder.getAbsolutePath()
                                    + File.separator + PersConfDefinitions.RESOURCE_CONFIGURATION_FILE);
                            if (resouceConfigurationFile.exists() && resouceConfigurationFile.canRead()) {
                                final GsonBuilder gsonBuilder = new GsonBuilder();
                                final Gson gson = gsonBuilder.create();
                                try (final FileReader reader = new FileReader(
                                        resouceConfigurationFile.getAbsolutePath())) {
                                    final JsonObject fromJson = gson.fromJson(reader, JsonObject.class);
                                    final JsonElement resourcesNode = fromJson
                                            .get(PersConfDefinitions.RESOURCES_KEY_NAME);
                                    final JsonElement versionElement = fromJson
                                            .get(PersConfDefinitions.VERSION_KEY_NAME);
                                    if (versionElement != null) {
                                        application.setVersion(versionElement.getAsString());
                                    }
                                    if (resourcesNode != null) {
                                        for (final Entry<String, JsonElement> entry : resourcesNode
                                                .getAsJsonObject().entrySet()) {
                                            if (!resources.containsKey(entry.getKey())) {
                                                final EResource res = createResource(entry.getKey());
                                                resources.put(entry.getKey(), res);
                                                application.getResources().add(res);
                                            }
                                            final EResource res = resources.get(entry.getKey());

                                            if (PersConfImport.handleConfigEntries(entry, res)) {
                                                hasWarnings = true;
                                            }
                                        }
                                    }
                                } catch (final Exception e) {
                                    Logger.error(Activator.PLUGIN_ID,
                                            "Error parsing resource configuration file of application '"
                                                    + application.getName()
                                                    + "'. Does that file contain valid JSON (e.g. no trailing commas)?",
                                            e);
                                    hasErrors = true;
                                }
                            } else {
                                Logger.warn(Activator.PLUGIN_ID, "Unable to read resource configuration file: "
                                        + resouceConfigurationFile.getName());
                                hasWarnings = true;
                            }

                            final File configDefaultFile = new File(appFolder.getAbsolutePath() + File.separator
                                    + PersConfDefinitions.KEY_FOLDER + File.separator
                                    + PersConfDefinitions.CONFIGURABLE_DEFAULTS_FILE);
                            if (PersConfImport.handleDefaultDataEntry(configDefaultFile,
                                    PersconfPackage.ECONFIGURATION__CONFIG_DEFAULT, resources, application)) {
                                hasWarnings = true;
                            }

                            final File factoryDefaultFile = new File(appFolder.getAbsolutePath()
                                    + File.separator + PersConfDefinitions.KEY_FOLDER + File.separator
                                    + PersConfDefinitions.FACTORY_DEFAULTS_FILE);
                            if (PersConfImport.handleDefaultDataEntry(factoryDefaultFile,
                                    PersconfPackage.ECONFIGURATION__FACTORY_DEFAULT, resources, application)) {
                                hasWarnings = true;
                            }
                        }
                    }
                }

                final File ownershipConfigurationFile = new File(
                        groupFile + File.separator + PersConfDefinitions.OWNERSHIP_CONFIGURATION_FILE);
                if (ownershipConfigurationFile.exists() && ownershipConfigurationFile.canRead()) {
                    final GsonBuilder gsonBuilder = new GsonBuilder();
                    final Gson gson = gsonBuilder.create();

                    try (final FileReader reader = new FileReader(
                            ownershipConfigurationFile.getAbsolutePath())) {
                        final JsonObject fromJson = gson.fromJson(reader, JsonObject.class);

                        for (final Entry<String, JsonElement> applicationEntry : fromJson.entrySet()) {
                            final String applicationName = applicationEntry.getKey();

                            // Find application by name:
                            final EApplication application = applicationMap.get(applicationName);
                            if (application == null)
                                continue;

                            try {
                                for (final Entry<String, JsonElement> ownershipEntry : applicationEntry
                                        .getValue().getAsJsonObject().entrySet()) {
                                    final String ownershipTypeName = ownershipEntry.getKey();
                                    final String ownershipValueString = String
                                            .valueOf(ownershipEntry.getValue()).replaceAll("\"", "");

                                    switch (ownershipTypeName) {
                                    case PersConfDefinitions.USERNAME_KEY_NAME:
                                        application.setUserName(ownershipValueString);
                                        break;
                                    case PersConfDefinitions.GROUPNAME_KEY_NAME:
                                        application.setGroupName(ownershipValueString);
                                        break;
                                    case PersConfDefinitions.USERID_KEY_NAME:
                                        if (ownershipValueString.equals(""))
                                            application.setUserId(null);
                                        else {
                                            try {
                                                final Integer ownerShipValue = Integer
                                                        .valueOf(ownershipValueString);
                                                application.setUserId(ownerShipValue);
                                            } catch (NumberFormatException e) {
                                                Logger.warn(Activator.PLUGIN_ID,
                                                        "Cannot read ownership configuration entry: Value for UserID cannot be parsed as integer: "
                                                                + ownershipValueString);
                                                hasWarnings = true;
                                            }
                                        }
                                        break;
                                    case PersConfDefinitions.GROUPID_KEY_NAME:
                                        if (ownershipValueString.equals(""))
                                            application.setGroupId(null);
                                        else {
                                            try {
                                                final Integer ownerShipValue = Integer
                                                        .valueOf(ownershipValueString);
                                                application.setGroupId(ownerShipValue);
                                            } catch (NumberFormatException e) {
                                                Logger.warn(Activator.PLUGIN_ID,
                                                        "Cannot read ownership configuration entry: Value for GroupID cannot be parsed as integer: "
                                                                + ownershipValueString);
                                                hasWarnings = true;
                                            }
                                        }
                                        break;
                                    default:
                                        Logger.warn(Activator.PLUGIN_ID,
                                                "Unknown identifier in ownership configuration file: "
                                                        + ownershipTypeName);
                                        hasWarnings = true;
                                        break;
                                    }
                                }
                            } catch (IllegalStateException e) {
                                Logger.warn(Activator.PLUGIN_ID,
                                        "Error while parsing the ownership configuration file: Cannot read sub-entries of application "
                                                + applicationName);
                            }
                        }
                    } catch (final Exception e) {
                        Logger.error(Activator.PLUGIN_ID,
                                "Error parsing ownership configuration file. Does that file contain valid JSON (e.g. no trailing commas)?",
                                e);
                        hasErrors = true;
                    }
                } else {
                    Logger.warn(Activator.PLUGIN_ID, "Unable to read resource configuration file: "
                            + ownershipConfigurationFile.getName());
                    hasWarnings = true;
                }
            } else {
                // add missing application groups
                final EApplicationGroup applicationGroup = PersconfFactory.eINSTANCE.createEApplicationGroup();
                applicationGroup.setType(groupType);
                resource.getContents().add(applicationGroup);
                Logger.warn(Activator.PLUGIN_ID, "No configuration items for " + groupType + ".");
                hasWarnings = true;
            }
        }

        if (!hasRootItems) {
            return new Status(IStatus.CANCEL, Activator.PLUGIN_ID,
                    "Directory does not contain a valid persistency configuration structure.");
        }

        this.importAppSizes(applicationMap);

        if (hasErrors) {
            return new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "The configuration " + this.rootFolder + " contains errors.");
        } else if (hasWarnings) {
            return new Status(IStatus.WARNING, Activator.PLUGIN_ID,
                    "The configuration " + this.rootFolder + " contains warnings.");
        } else {
            return Status.OK_STATUS;
        }
    } else {
        return new Status(IStatus.CANCEL, Activator.PLUGIN_ID,
                "Directory does not contain a '" + PersConfDefinitions.RESOURCE_FOLDER_NAME + "' folder.");
    }
}

From source file:edu.wisc.doit.tcrypt.ant.filter.AntTasksTest.java

private Map<String, File> getAllFiles(File dir) throws Exception {
    final Collection<File> expectedFiles = FileUtils.listFilesAndDirs(dir, TrueFileFilter.INSTANCE,
            DirectoryFileFilter.INSTANCE);

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

    for (final File f : expectedFiles) {
        final String relativePath = org.apache.tools.ant.util.FileUtils.getRelativePath(dir, f);

        result.put(relativePath, f);//from ww  w .  j  a  v a2  s .  c  o  m
    }

    return result;
}