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:com.bluexml.tools.miscellaneous.PrepareSIDEModulesMigration.java

protected static File copyDir(File workspaceFile, File srcDir) {

    File destDir0 = new File(workspaceFile, MIGRATION_FOLDER);
    File destDir = new File(destDir0, srcDir.getName());
    try {//from w  ww .j  ava  2s  .  c  om
        FileUtils.copyDirectory(srcDir, destDir, new FileFilter() {

            public boolean accept(File pathname) {
                String name = pathname.getName();
                boolean equals = name.equals(".svn") || name.equals("target");

                return !equals;
            }
        });
        return destDir;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:edu.mayo.cts2.framework.core.plugin.FelixPluginManager.java

/**
 * Start.//w  w w .  j a  va  2  s  .co m
 *
 * @throws OsgiContainerException the osgi container exception
 */
public void start() throws OsgiContainerException {
    if (isRunning()) {
        return;
    }

    boolean suppressOsgi = this.cts2GeneralConfig.getBooleanProperty(SUPPRESS_OSGI_CONFIG_PROP_NAME,
            DEFALUE_SUPPRESS_OSGI_CONFIG_VALUE);

    // Create a case-insensitive configuration property map.
    final StringMap configMap = new StringMap(false);

    if (!suppressOsgi) {
        try {
            this.autodeployBundles(this.configInitializer.getPluginsDirectory());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        PackageScannerConfiguration scannerConfig = new DefaultPackageScannerConfiguration();
        scannerConfig.getPackageIncludes().add("edu.mayo.cts2.*");
        scannerConfig.getPackageIncludes().add("org.jaxen*");
        scannerConfig.getPackageIncludes().add("com.sun*");
        scannerConfig.getPackageIncludes().add("org.json*");
        scannerConfig.getPackageIncludes().add("org.springframework.oxm*");
        scannerConfig.getPackageExcludes().add("com.atlassian.plugins*");

        scannerConfig.getPackageExcludes().remove("org.apache.commons.logging*");
        scannerConfig.getPackageVersions().put("org.apache.commons.collections*", "3.2.1");

        String exports = exportsBuilder.getExports(scannerConfig);
        if (log.isDebugEnabled()) {
            log.debug("Exports: " + exports);
        }

        // Explicitly add the servlet exports;
        exports += ",javax.servlet;version=" + MIN_SERVLET_VERSION;
        exports += ",javax.servlet.http;version=" + MIN_SERVLET_VERSION;

        // Add the bundle provided service interface package and the core OSGi
        // packages to be exported from the class path via the system bundle.
        configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, exports);
    }

    // Explicitly specify the directory to use for caching bundles.
    File felixCache = ConfigUtils.createSubDirectory(this.configInitializer.getContextConfigDirectory(),
            ".osgi-felix-cache");

    configMap.put(FelixConstants.FRAMEWORK_STORAGE, felixCache.getPath());

    configMap.put(FelixConstants.LOG_LEVEL_PROP, String.valueOf(felixLogger.getLogLevel()));
    configMap.put(FelixConstants.LOG_LOGGER_PROP, felixLogger);
    configMap.put(FelixConstants.FRAGMENT_ATTACHMENT_RESOLVETIME, felixLogger);

    String bootDelegation = getAtlassianSpecificOsgiSystemProperty(OSGI_BOOTDELEGATION);
    if ((bootDelegation == null) || (bootDelegation.trim().length() == 0)) {
        // These exist to work around JAXP problems.  Specifically, bundles that use static factories to create JAXP
        // instances will execute FactoryFinder with the CCL set to the bundle.  These delegations ensure the appropriate
        // implementation is found and loaded.
        bootDelegation = "weblogic,weblogic.*," + "META-INF.services," + "com.yourkit,com.yourkit.*,"
                + "com.chronon,com.chronon.*," + "com.jprofiler,com.jprofiler.*,"
                + "org.apache.xerces,org.apache.xerces.*," + "org.apache.xalan,org.apache.xalan.*,"
                + "org.apache.xpath.*," + "org.apache.xml.serializer," + "org.springframework.stereotype,"
                + "org.springframework.web.bind.annotation," + "org.springframework.web.servlet," + "javax.*,"
                + "org.osgi.*," + "org.apache.felix.*," + "sun.*," + "com.sun.*," + "com.sun.xml.bind.v2,"
                + "com.icl.saxon";
    }

    configMap.put(FelixConstants.FRAMEWORK_BOOTDELEGATION, bootDelegation);
    configMap.put(FelixConstants.IMPLICIT_BOOT_DELEGATION_PROP, "false");

    configMap.put(FelixConstants.FRAMEWORK_BUNDLE_PARENT, FelixConstants.FRAMEWORK_BUNDLE_PARENT_FRAMEWORK);
    if (log.isDebugEnabled()) {
        log.debug("Felix configuration: " + configMap);
    }

    if (!suppressOsgi) {
        validateConfiguration(configMap);
    }

    try {
        final List<BundleActivator> hostServices = new ArrayList<BundleActivator>();

        for (Entry<String, Object> bean : this.applicationContext.getBeansWithAnnotation(ExportedService.class)
                .entrySet()) {
            Object service = bean.getValue();

            ExportedService annotation = service.getClass().getAnnotation(ExportedService.class);
            Class<?>[] interfaces = annotation.value();
            if (interfaces.length == 1 && interfaces[0] == Void.class) {
                interfaces = ClassUtils.getAllInterfaces(service);
            }

            hostServices.add(new HostActivator(service, interfaces));
        }

        configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, hostServices);

        // Now create an instance of the framework with
        // our configuration properties and activator.
        felix = new Felix(configMap);
        felixRunning = true;

        felix.init();

        BundleContext context = felix.getBundleContext();

        ServiceTracker tracker = new ServiceTracker(felix.getBundleContext(),
                ConfigurationAdmin.class.getName(), new ServiceTrackerCustomizer() {

                    @Override
                    public Object addingService(ServiceReference reference) {
                        ConfigurationAdmin cm = (ConfigurationAdmin) felix.getBundleContext()
                                .getService(reference);

                        try {

                            for (Entry<String, Properties> entrySet : supplementalPropetiesLoader
                                    .getOverriddenProperties().entrySet()) {

                                Configuration config = cm.getConfiguration(entrySet.getKey());

                                config.update(entrySet.getValue());

                            }

                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                        return cm;
                    }

                    @Override
                    public void modifiedService(ServiceReference reference, Object service) {
                        //
                    }

                    @Override
                    public void removedService(ServiceReference reference, Object service) {
                        //
                    }

                });

        tracker.open();

        this.trackers.add(tracker);

        if (suppressOsgi) {
            new ConfigurationManager().start(context);
        } else {
            FileFilter fileOnlyFilter = new FileFilter() {

                @Override
                public boolean accept(File file) {
                    return !file.isDirectory();
                }

            };

            for (File bundle : this.configInitializer.getPluginsDirectory().listFiles(fileOnlyFilter)) {
                Bundle installedBundle = felix.getBundleContext().installBundle(bundle.toURI().toString());
                try {
                    if (installedBundle.getHeaders().get(Constants.FRAGMENT_HOST) != null) {
                        log.info("Not Auto-starting Fragment bundle: " + installedBundle.getSymbolicName());
                    } else {
                        installedBundle.start();
                        log.info("Auto-starting system bundle: " + installedBundle.getSymbolicName());
                    }
                } catch (BundleException e) {
                    log.warn("Bundle: " + installedBundle.getSymbolicName() + " failed to start.", e);
                }
            }
        }

        felix.start();

        this.initializeNonOsgiPlugins();

        for (String bean : this.applicationContext.getBeanNamesForType(ExtensionPoint.class)) {

            ExtensionPoint extensionPoint = this.applicationContext.getBean(bean, ExtensionPoint.class);

            this.registerExtensionPoint(extensionPoint);
        }

        servletContext.setAttribute(BundleContext.class.getName(), context);

        servletContext.setAttribute(PluginManager.class.getName(), this);

    } catch (final Exception ex) {
        throw new OsgiContainerException("Unable to start OSGi container", ex);
    }
}

From source file:com.streamsets.datacollector.cluster.BaseClusterProvider.java

private static File getBootstrapJar(File bootstrapDir, final Pattern pattern) {
    Utils.checkState(bootstrapDir.isDirectory(),
            Utils.format("SDC bootstrap cluster lib does not exist: {}", bootstrapDir));
    File[] candidates = bootstrapDir.listFiles(new FileFilter() {
        @Override/*  www .  j  a v a  2  s .  co  m*/
        public boolean accept(File candidate) {
            return pattern.matcher(candidate.getName()).matches();
        }
    });
    Utils.checkState(candidates != null,
            Utils.format("Did not find jar matching {} in {}", pattern, bootstrapDir));
    Utils.checkState(candidates.length == 1,
            Utils.format("Did not find exactly one bootstrap jar: {}", Arrays.toString(candidates)));
    return candidates[0];
}

From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java

protected void copyWebDirectory(String srcDir, String destDir) throws Exception {
    // list all files except merged files
    File[] files = new File(srcDir).listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return !ExtRegistry.isMergedFile(pathname.getPath());
        }/*w ww. j a  v a 2s .co  m*/
    });
    // copy files recursively
    for (File file : files) {
        if (file.isDirectory()) {
            copyWebDirectory(file.getPath(), destDir + File.separator + file.getName());
        } else {
            CopyTask.copyFile(file, new File(destDir), true, false);
        }
    }
}

From source file:org.apache.directory.server.configuration.ApacheDS.java

/**
 * Load the existing LDIF files in alphabetic order
 * //from w w  w .  jav  a 2  s. co  m
 * @throws LdapException If we can't load the ldifs
 */
public void loadLdifs() throws LdapException {
    // LOG and bail if property not set
    if (ldifDirectory == null) {
        LOG.info("LDIF load directory not specified.  No LDIF files will be loaded.");
        return;
    }

    // LOG and bail if LDIF directory does not exists
    if (!ldifDirectory.exists()) {
        LOG.warn("LDIF load directory '{}' does not exist.  No LDIF files will be loaded.",
                getCanonical(ldifDirectory));
        return;
    }

    ensureLdifFileBase();

    // if ldif directory is a file try to load it
    if (ldifDirectory.isFile()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("LDIF load directory '{}' is a file. Will attempt to load as LDIF.",
                    getCanonical(ldifDirectory));
        }

        try {
            loadLdif(ldifDirectory);
        } catch (Exception ne) {
            // If the file can't be read, log the error, and stop
            // loading LDIFs.
            LOG.error(I18n.err(I18n.ERR_180, ldifDirectory.getAbsolutePath(), ne.getLocalizedMessage()));
            throw new LdapException(ne.getMessage(), ne);
        }
    } else {
        // get all the ldif files within the directory
        File[] ldifFiles = ldifDirectory.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                boolean isLdif = Strings.toLowerCaseAscii(pathname.getName()).endsWith(".ldif");
                return pathname.isFile() && pathname.canRead() && isLdif;
            }
        });

        // LOG and bail if we could not find any LDIF files
        if ((ldifFiles == null) || (ldifFiles.length == 0)) {
            LOG.warn("LDIF load directory '{}' does not contain any LDIF files. No LDIF files will be loaded.",
                    getCanonical(ldifDirectory));
            return;
        }

        // Sort ldifFiles in alphabetic order
        Arrays.sort(ldifFiles, new Comparator<File>() {
            public int compare(File f1, File f2) {
                return f1.getName().compareTo(f2.getName());
            }
        });

        // load all the ldif files and load each one that is loaded
        for (File ldifFile : ldifFiles) {
            try {
                LOG.info("Loading LDIF file '{}'", ldifFile.getName());
                loadLdif(ldifFile);
            } catch (Exception ne) {
                // If the file can't be read, log the error, and stop
                // loading LDIFs.
                LOG.error(I18n.err(I18n.ERR_180, ldifFile.getAbsolutePath(), ne.getLocalizedMessage()));
                throw new LdapException(ne.getMessage(), ne);
            }
        }
    }
}

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

public static File[] getAllSnapshotFiles(final ServletConfig config, final TranscodeRequest request)
        throws ProcessorException {
    FileFilter fileFilter = new FileFilter() {
        @Override// ww w. j  a  va 2 s . com
        public boolean accept(File pathname) {
            boolean matchesPid = pathname.getName().contains(request.getPid());
            boolean matchesFormat = pathname.getName()
                    .endsWith(Util.getInitParameter(config, Constants.SNAPSHOT_FINAL_FORMAT));
            return matchesFormat && matchesPid;
        }
    };
    return getOutputDir(request, config).listFiles(fileFilter);
}

From source file:org.apache.flume.test.util.StagedInstall.java

private String getRelativeTarballPath() throws Exception {
    String tarballPath = null;//  www.j  a v  a  2 s . c o  m
    File dir = new File("..");
    while (dir != null && dir.isDirectory()) {
        File testFile = new File(dir, "flume-ng-dist/target");

        if (testFile.exists() && testFile.isDirectory()) {
            LOGGER.info("Found candidate dir: " + testFile.getCanonicalPath());
            File[] candidateFiles = testFile.listFiles(new FileFilter() {

                @Override
                public boolean accept(File pathname) {
                    String name = pathname.getName();
                    if (name != null && name.startsWith("apache-flume-") && name.endsWith("-dist.tar.gz")) {
                        return true;
                    }
                    return false;
                }
            });

            // There should be at most one
            if (candidateFiles != null && candidateFiles.length > 0) {
                if (candidateFiles.length == 1) {
                    // Found it
                    File file = candidateFiles[0];
                    if (file.isFile() && file.canRead()) {
                        tarballPath = file.getCanonicalPath();
                        LOGGER.info("Found file: " + tarballPath);
                        break;
                    } else {
                        LOGGER.warn("Invalid file: " + file.getCanonicalPath());
                    }
                } else {
                    StringBuilder sb = new StringBuilder("Multiple candate tarballs");
                    sb.append(" found in directory ");
                    sb.append(testFile.getCanonicalPath()).append(": ");
                    boolean first = true;
                    for (File file : candidateFiles) {
                        if (first) {
                            first = false;
                            sb.append(" ");
                        } else {
                            sb.append(", ");
                        }
                        sb.append(file.getCanonicalPath());
                    }
                    sb.append(". All these files will be ignored.");
                    LOGGER.warn(sb.toString());
                }
            }
        }

        dir = dir.getParentFile();
    }
    return tarballPath;
}

From source file:com.properned.application.SystemController.java

public void loadFileList(File selectedFile) {
    Platform.runLater(new Runnable() {

        @Override/*from w  w  w.ja v  a2s.  c om*/
        public void run() {
            logger.info("Load the file list associated to '" + selectedFile.getAbsolutePath() + "'");

            if (MultiLanguageProperties.getInstance().getIsDirty()) {
                ButtonType result = askForSave();
                if (result.getButtonData() == ButtonData.CANCEL_CLOSE) {
                    // The file must not be loaded
                    return;
                }
            }
            Preferences.getInstance().setLastPathUsed(selectedFile.getAbsolutePath());
            String fileName = selectedFile.getName();
            String baseNameTemp = fileName.substring(0, fileName.lastIndexOf("."));

            if (fileName.contains("_")) {
                baseNameTemp = fileName.substring(0, fileName.indexOf("_"));
            }
            final String baseName = baseNameTemp;

            List<PropertiesFile> fileList = Arrays
                    .asList(selectedFile.getParentFile().listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File pathname) {
                            return pathname.isFile() && pathname.getName().startsWith(baseName)
                                    && pathname.getName().endsWith(".properties");
                        }
                    })).stream().map(new Function<File, PropertiesFile>() {
                        @Override
                        public PropertiesFile apply(File t) {
                            String language = "";
                            if (t.getName().contains("_")) {
                                language = t.getName().substring(t.getName().indexOf("_") + 1,
                                        t.getName().lastIndexOf("."));
                            }
                            return new PropertiesFile(t.getAbsolutePath(), baseName, new Locale(language));
                        }
                    }).collect(Collectors.<PropertiesFile>toList());

            try {
                multiLanguageProperties.loadFileList(baseName, fileList);
                Preferences.getInstance().addFileToRecentFileList(selectedFile.getAbsolutePath());
                Properned.getInstance().getPrimaryStage().getScene()
                        .setOnKeyReleased(new EventHandler<KeyEvent>() {
                            @Override
                            public void handle(KeyEvent event) {
                                if (event.getCode() == KeyCode.S && event.isControlDown()) {
                                    logger.info("CTRL-S detected");
                                    save();
                                    event.consume();
                                }
                            }
                        });
            } catch (IOException e) {
                Properned.getInstance().showError(MessageReader.getInstance().getMessage("error.load"), e);
            }
        }
    });
}

From source file:com.maskyn.fileeditorpro.activity.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_FILE_CODE) {

            final Uri data = intent.getData();
            final GreatUri newUri = new GreatUri(data, AccessStorageApi.getPath(this, data),
                    AccessStorageApi.getName(this, data));

            newFileToOpen(newUri, "");
        } else if (requestCode == SELECT_FOLDER_CODE) {
            FileFilter fileFilter = new FileFilter() {
                public boolean accept(File file) {
                    return file.isFile();
                }// w w w .  java  2  s.  c o  m
            };
            final Uri data = intent.getData();
            File dir = new File(data.getPath());
            File[] fileList = dir.listFiles(fileFilter);
            for (int i = 0; i < fileList.length; i++) {
                Uri particularUri = Uri.parse("file://" + fileList[i].getPath());
                final GreatUri newUri = new GreatUri(particularUri,
                        AccessStorageApi.getPath(this, particularUri),
                        AccessStorageApi.getName(this, particularUri));
                greatUris.add(newUri);

                refreshList(newUri, true, false);
                arrayAdapter.selectPosition(newUri);
            }
            if (fileList.length > 0) {
                Uri particularUri = Uri.parse("file://" + fileList[0].getPath());
                final GreatUri newUri = new GreatUri(particularUri,
                        AccessStorageApi.getPath(this, particularUri),
                        AccessStorageApi.getName(this, particularUri));
                newFileToOpen(newUri, "");
            }

        } else {

            final Uri data = intent.getData();
            final GreatUri newUri = new GreatUri(data, AccessStorageApi.getPath(this, data),
                    AccessStorageApi.getName(this, data));

            // grantUriPermission(getPackageName(), data, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            final int takeFlags = intent.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(data, takeFlags);

            if (requestCode == READ_REQUEST_CODE || requestCode == CREATE_REQUEST_CODE) {

                newFileToOpen(newUri, "");
            }

            if (requestCode == SAVE_AS_REQUEST_CODE) {

                new SaveFileTask(this, newUri, pageSystem.getAllText(mEditor.getText().toString()),
                        currentEncoding, new SaveFileTask.SaveFileInterface() {
                            @Override
                            public void fileSaved(Boolean success) {
                                savedAFile(greatUri, false);
                                newFileToOpen(newUri, "");
                            }
                        }).execute();
            }
        }

    }
}

From source file:org.apache.carbondata.processing.store.writer.AbstractFactDataWriter.java

private int initFileCount() {
    int fileInitialCount = 0;
    File[] dataFiles = new File(dataWriterVo.getStoreLocation()).listFiles(new FileFilter() {
        @Override/*  ww w. j ava 2  s .c om*/
        public boolean accept(File pathVal) {
            if (!pathVal.isDirectory() && pathVal.getName().startsWith(dataWriterVo.getTableName())
                    && pathVal.getName().contains(CarbonCommonConstants.FACT_FILE_EXT)) {
                return true;
            }
            return false;
        }
    });
    if (dataFiles != null && dataFiles.length > 0) {
        Arrays.sort(dataFiles);
        String dataFileName = dataFiles[dataFiles.length - 1].getName();
        try {
            fileInitialCount = Integer
                    .parseInt(dataFileName.substring(dataFileName.lastIndexOf('_') + 1).split("\\.")[0]);
        } catch (NumberFormatException ex) {
            fileInitialCount = 0;
        }
        fileInitialCount++;
    }
    return fileInitialCount;
}