Java 类org.apache.commons.io.filefilter.FileFilterUtils 实例源码

项目:openrasp    文件:JsPluginManager.java   
/**
 * 更新插件引擎
 * <p>
 * 检测脚本变化时更新
 * <p>
 * 当新插件引擎初始化成功之后再替换旧插件引擎
 *
 * @throws Exception
 */
private synchronized static void updatePlugin() throws Exception {
    // 清空 algorithm.config 配置
    Config.getConfig().setAlgorithmConfig("{}");
    boolean oldValue = HookHandler.enableHook.getAndSet(false);
    File pluginDir = new File(Config.getConfig().getScriptDirectory());
    LOGGER.debug("checker directory: " + pluginDir.getAbsolutePath());
    if (!pluginDir.isDirectory()) {
        pluginDir.mkdir();
    }
    File[] pluginFiles = pluginDir.listFiles((FileFilter) FileFilterUtils.suffixFileFilter(".js"));
    List<CheckScript> scripts = new LinkedList<CheckScript>();
    for (File file : pluginFiles) {
        try {
            scripts.add(new CheckScript(file));
        } catch (Exception e) {
            LOGGER.error("", e);
        }
    }

    JSContextFactory.setCheckScriptList(scripts);

    HookHandler.enableHook.set(oldValue);
}
项目:convertigo-engine    文件:MobileBuilder.java   
private void updateConfigurationFiles() throws EngineException {
    try {
        IOFileFilter fileFilter = FileFilterUtils.or(FileFilterUtils.suffixFileFilter("json"),FileFilterUtils.suffixFileFilter("xml"),FileFilterUtils.suffixFileFilter("js"));
        IOFileFilter dirFilter = FileFilterUtils.or(FileFilterUtils.nameFileFilter("config"));
        for (File f: FileUtils.listFiles(ionicWorkDir, fileFilter, dirFilter)) {
            String content = FileUtils.readFileToString(f, "UTF-8");
            content = content.replaceAll("../DisplayObjects","../../DisplayObjects");
            content = content.replaceAll("../Flashupdate","../../Flashupdate");
            writeFile(f, content, "UTF-8");
        }
        Engine.logEngine.debug("(MobileBuilder) Configuration files updated for ionic project '"+ project.getName() +"'");
    }
    catch (Exception e) {
        throw new EngineException("Unable to update configuration files for ionic project '"+ project.getName() +"'",e);
    }
}
项目:util4j    文件:FileMonitor.java   
/**
 * 只监控文件发送变化,如果是子目录的文件改变,则目录会变,由于没有过滤目录发生变化,则目录下的文件改变不会监控到
 * @param dir
 * @throws Exception 
 */
public void check1(String dir) throws Exception
{
    File directory = new File(dir);
    // 轮询间隔 5 秒
    long interval = TimeUnit.SECONDS.toMillis(5);
    // 创建一个文件观察器用于处理文件的格式
    IOFileFilter filter=FileFilterUtils.or(FileFilterUtils.suffixFileFilter(".class"),
            FileFilterUtils.suffixFileFilter(".jar"));
    FileAlterationObserver observer = new FileAlterationObserver(directory,filter);
    //设置文件变化监听器
    observer.addListener(new MyFileListener());
    FileAlterationMonitor monitor = new FileAlterationMonitor(interval);
    monitor.addObserver(observer);//文件观察
    monitor.start();
}
项目:util4j    文件:FileMonitor.java   
public void check2(String dir) throws Exception
    {
        File directory = new File(dir);
        // 轮询间隔 5 秒
        long interval = TimeUnit.SECONDS.toMillis(5);
        //后缀过滤器
        IOFileFilter filefilter=FileFilterUtils.or(FileFilterUtils.suffixFileFilter(".class"),
                FileFilterUtils.suffixFileFilter(".jar"));
        //子目录的后缀
        IOFileFilter subFilefilter=FileFilterUtils.or(FileFilterUtils.directoryFileFilter(),filefilter);
        //根目录和子目录变化
        IOFileFilter filter = FileFilterUtils.or(filefilter,subFilefilter);
        FileAlterationObserver observer = new FileAlterationObserver(directory,filter);
        //设置文件变化监听器
        observer.addListener(new MyFileListener());
        FileAlterationMonitor monitor = new FileAlterationMonitor(interval);
        monitor.addObserver(observer);//文件观察
        monitor.start();
//      monitor.addObserver(observer);//文件观察,如果在start后面加,则会触发所有文件创建
    }
项目:mdetect    文件:FileScanUtils.java   
public static List<String> findGitRepos(String dirPath) {
    File dir = new File(dirPath);
    IOFileFilter gitDirFilter = (IOFileFilter) FileFilterUtils.suffixFileFilter(".git");
    IOFileFilter notFile = FileFilterUtils.notFileFilter(TrueFileFilter.INSTANCE);
    IOFileFilter compositeFilter = FileFilterUtils.and(notFile, gitDirFilter);

    List<File> files = (List<File>) FileUtils.listFilesAndDirs(dir,compositeFilter,DirectoryFileFilter.INSTANCE);
    List<String> results = new ArrayList<String>();
    for(File f: files) {
        try {
            if(!f.getCanonicalPath().endsWith("/.git"))
                continue;

            String gitStripped = f.getCanonicalPath().replace("/.git", "");
            System.out.println(gitStripped);
            results.add(gitStripped);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return results;
}
项目:mdetect    文件:FileScanUtils.java   
public static List<String> findFilesToAnalyze(String dirPath) {
    IOFileFilter gitFilter = FileFilterUtils.notFileFilter(
                    FileFilterUtils.nameFileFilter(".git")
            );
    File dir = new File(dirPath);
    String[] phpExt = new String[] {"php"};
    IOFileFilter phpFilter = new SuffixFileFilter(phpExt, IOCase.INSENSITIVE);
    List<File> files = (List<File>) FileUtils.listFiles(dir, phpFilter, gitFilter);
    List<String> results = new ArrayList<String>();
    for (File f : files) {
        try {
            results.add(f.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return results;
}
项目:gradle-mobile-plugin    文件:ReportGitCommitInfoTask.java   
private File getSubdirWithLatestCommit(File rootDir) {
    File resultDir = rootDir;
    long latestTimestamp = GitUtil.getCheckedoutCommitTimestamp(rootDir);
    File [] dirs = rootDir.listFiles((FileFilter) FileFilterUtils.directoryFileFilter());
    if (dirs != null) {
        for (File dir : dirs) {
            logger.debug("  checking timestamp for '{}'", dir);
            long dirTimestamp = GitUtil.getCheckedoutCommitTimestamp(dir);
            if (dirTimestamp > latestTimestamp) {
                resultDir = dir;
                latestTimestamp = dirTimestamp;
            }
        }
    }
    return resultDir;
}
项目:japi    文件:ProjectImpl.java   
@Override
public List<IPackage> getPackages() {
    String masterProjectActionPath = JapiClient.getConfig().getPrefixPath() + JapiClient.getConfig().getProjectJavaPath() + JapiClient.getConfig().getPostfixPath() + "/" + JapiClient.getConfig().getActionReletivePath();
    File actionFold = new File(masterProjectActionPath);
    if (!actionFold.exists()) {
        throw new JapiException(masterProjectActionPath + " fold not exists.");
    }
    final IOFileFilter dirFilter = FileFilterUtils.asFileFilter(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    });
    Collection<File> folds = FileUtils.listFilesAndDirs(actionFold, dirFilter, TrueFileFilter.INSTANCE);
    List<IPackage> packages = new ArrayList<>(folds.size());
    for (File fold : folds) {
        if (!fold.getAbsolutePath().equals(actionFold.getAbsolutePath())) {
            PackageImpl packageImpl = new PackageImpl();
            packageImpl.setPackageFold(fold);
            packages.add(packageImpl);
        }
    }
    return packages;
}
项目:japi    文件:PackageImpl.java   
@Override
public List<IAction> getActions() {
    final IOFileFilter dirFilter = FileFilterUtils.asFileFilter(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getName().endsWith(".java") && !pathname.getName().equals("package-info.java");
        }
    });
    Collection<File> actionFiles = FileUtils.listFiles(packageFold, dirFilter, null);
    List<IAction> actions = new ArrayList<>();
    for (File actionFile : actionFiles) {
        ActionImpl action = new ActionImpl();
        action.setActionFile(actionFile);
        actions.add(action);
    }
    return actions;
}
项目:PEP---Notes    文件:DataBackupIntentService.java   
/**
 * Import attachments from backup folder
 */
private boolean importAttachments(File backupDir) {
    File attachmentsDir = StorageHelper.getAttachmentDir(this);
    // Moving back
    File backupAttachmentsDir = new File(backupDir, attachmentsDir.getName());
    if (!backupAttachmentsDir.exists()) return true;
    boolean result = true;
    Collection list = FileUtils.listFiles(backupAttachmentsDir, FileFilterUtils.trueFileFilter(),
            TrueFileFilter.INSTANCE);
    Iterator i = list.iterator();
    int imported = 0;
    File file = null;
    while (i.hasNext()) {
        try {
            file = (File) i.next();
            FileUtils.copyFileToDirectory(file, attachmentsDir, true);
            mNotificationsHelper.setMessage(TextHelper.capitalize(getString(R.string.attachment)) + " " + imported++ + "/" + list.size())
                    .show();
        } catch (IOException e) {
            result = false;
            Log.e(Constants.TAG, "Error importing the attachment " + file.getName());
        }
    }
    return result;
}
项目:textokit-core    文件:AXML2XMI.java   
private void run() throws ResourceInitializationException, IOException, SAXException {
    Collection<File> inputFiles =
            FileUtils.listFiles(inputDir, FileFilterUtils.suffixFileFilter(".xml"), null);
    if (inputFiles.isEmpty()) {
        return;
    }
    TypeSystemDescription tsd = TypeSystemDescriptionFactory
            .createTypeSystemDescription(typeSystemDescName);
    CAS cas = CasCreationUtils.createCas(tsd, null, null);
    for (File inputFile : inputFiles) {
        AXMLReader.read(inputFile, cas);
        File outFile = getOutputFile(inputFile);
        OutputStream out = FileUtils.openOutputStream(outFile);
        try {
            XmiCasSerializer.serialize(cas, null, out, true, null);
        } finally {
            out.close();
            cas.reset();
        }
    }
}
项目:textokit-core    文件:BratCollectionReader.java   
@Override
public void initialize(UimaContext ctx) throws ResourceInitializationException {
    super.initialize(ctx);
    // initialize mappingFactory
    mappingFactory = InitializableFactory.create(ctx, mappingFactoryClassName,
            BratUimaMappingFactory.class);
    // make bratDocIter
    File[] annFiles = bratCollectionDir.listFiles(
            (FileFilter) FileFilterUtils.suffixFileFilter(BratDocument.ANN_FILE_SUFFIX));
    List<BratDocument> bratDocs = Lists.newArrayListWithExpectedSize(annFiles.length);
    for (File annFile : annFiles) {
        String docBaseName = FilenameUtils.getBaseName(annFile.getPath());
        BratDocument bratDoc = new BratDocument(bratCollectionDir, docBaseName);
        if (bratDoc.exists()) {
            bratDocs.add(bratDoc);
        } else {
            throw new IllegalStateException(String.format(
                    "Missing txt file for %s", annFile));
        }
    }
    totalDocsNum = bratDocs.size();
    bratDocIter = bratDocs.iterator();
}
项目:project-build-plugin    文件:FileLogForwarder.java   
public synchronized void activate() throws MojoExecutionException
{   
  IOFileFilter logFilter = FileFilterUtils.and(
          FileFilterUtils.fileFileFilter(),
          FileFilterUtils.nameFileFilter(engineLog.getName()));
  FileAlterationObserver fileObserver = new FileAlterationObserver(engineLog.getParent(), logFilter);
  fileObserver.addListener(new LogModificationListener());
  monitor = new FileAlterationMonitor(100);
  monitor.addObserver(fileObserver);
  try
  {
    monitor.start();
  }
  catch (Exception ex)
  {
    throw new MojoExecutionException("Failed to activate deploy log forwarder", ex);
  }
}
项目:me3modmanager    文件:RestoreFilesWindow.java   
/**
 * Deletes all non-standard DLC folders from the BioGAme/DLC directory
 * using the known list of DLCs
 */
private boolean removeCustomDLC() {
    // TODO Auto-generated method stub
    File rootFolder = new File(ModManager.appendSlash(RestoreFilesWindow.this.BioGameDir) + "DLC");
    if (rootFolder.exists()) {
        File[] folders = rootFolder.listFiles((FileFilter) FileFilterUtils.directoryFileFilter());
        for (File dlcfolder : folders) {
            String foldername = dlcfolder.getName();
            if (!ModTypeConstants.getStandardDLCFolders().contains(foldername)) {
                try {
                    FileUtils.deleteDirectory(dlcfolder);
                    ModManager.debugLogger.writeMessage("Deleted DLC folder: " + dlcfolder.getAbsolutePath());
                } catch (IOException e) {
                    ModManager.debugLogger.writeErrorWithException("Unabled to delete DLC folder: " + dlcfolder, e);
                    return false;
                }
            }
        }

        ModManager.debugLogger.writeMessage("Deleted all Custom DLC folders (if there were any)");
        publish(Integer.toString(completed));
        return true;
    } else {
        return false;
    }
}
项目:adalid    文件:FileBrowser.java   
private IOFileFilter fileFilter() {
    IOFileFilter fileFileFilter = FileFilterUtils.fileFileFilter();
    IOFileFilter[] noes = new IOFileFilter[]{
        new RegexFileFilter(B + X + D + "class" + E),
        new RegexFileFilter(B + X + D + "db" + E),
        new RegexFileFilter(B + X + D + "ear" + E),
        new RegexFileFilter(B + X + D + "err" + E),
        new RegexFileFilter(B + X + D + "gif" + E),
        new RegexFileFilter(B + X + D + "jar" + E),
        new RegexFileFilter(B + X + D + "jpg" + E),
        new RegexFileFilter(B + X + D + "lnk" + E),
        new RegexFileFilter(B + X + D + "log" + E),
        new RegexFileFilter(B + X + D + "nbm" + E),
        new RegexFileFilter(B + X + D + "out" + E),
        new RegexFileFilter(B + X + D + "png" + E),
        new RegexFileFilter(B + X + D + "war" + E),
        new RegexFileFilter(B + X + D + "zip" + E)
    };
    IOFileFilter noesFileFilter = FileFilterUtils.notFileFilter(FileFilterUtils.or(noes));
    IOFileFilter filter = FileFilterUtils.and(fileFileFilter, noesFileFilter);
    return filter;
}
项目:artifactory    文件:StartArtifactoryDev.java   
/**
 * Copy newer files from the standalone dir to the working artifactory home dir
 */
private static void copyNewerDevResources(File devEtcDir, File artHome) throws IOException {
    File homeEtcDir = new File(artHome, "etc");
    IOFileFilter fileFilter = new NewerFileFilter(devEtcDir, homeEtcDir);
    fileFilter = FileFilterUtils.makeSVNAware(fileFilter);
    FileUtils.copyDirectory(devEtcDir, homeEtcDir, fileFilter, true);
    updateDefaultMimetypes(homeEtcDir);
    deleteHaProps(homeEtcDir);
    /**
     * If the bootstrap already exists, it means it's not the first startup, so don't keep the original config file
     * or the etc folder will flood with bootstrap files
     */
    if (new File(homeEtcDir, ArtifactoryHome.ARTIFACTORY_CONFIG_BOOTSTRAP_FILE).exists()) {
        new File(homeEtcDir, ArtifactoryHome.ARTIFACTORY_CONFIG_FILE).delete();
    }
}
项目:spring-dynamic    文件:DelLastUpdated.java   
private static void delFileRecr(File[] dirs, File[] files) { 
    if (dirs != null && dirs.length > 0) { 
        for(File dir: dirs){ 
            File[] childDir = dir.listFiles((FilenameFilter) FileFilterUtils 
            .directoryFileFilter()); 
            File[] childFiles = dir.listFiles((FilenameFilter) FileFilterUtils 
            .suffixFileFilter(FILE_SUFFIX)); 
            delFileRecr(childDir,childFiles); 
        } 
    } 
    if(files!=null&&files.length>0){ 
        for(File file: files){ 
            if(file.delete()){ 
                System.out.println("File: ["+file.getName()+"] has been deleted."); 
            } 
        } 
    } 
}
项目:celerio    文件:IOUtil.java   
/**
 * Recurse in the folder to get the list all files and folders
 * <ul>
 * <li>do not recurse in svn folder</li>
 * <li>do not recurse in cvs folder</li>
 * <li>do not match .bak files</li>
 * <li>do not match .old files</li>
 * </ul>
 *
 * @param folder       the folder to parse
 * @param ioFileFilter additionnal IOFilter
 */
@SuppressWarnings("unchecked")
public Collection<String> listFiles(File folder, IOFileFilter ioFileFilter) {
    if (ioFileFilter == null) {
        ioFileFilter = FileFilterUtils.fileFileFilter();
    }
    OrFileFilter oldFilesFilter = new OrFileFilter();
    for (String exclude : DEFAULT_EXCLUDES_SUFFIXES) {
        oldFilesFilter.addFileFilter(FileFilterUtils.suffixFileFilter(exclude));
    }
    IOFileFilter notOldFilesFilter = FileFilterUtils.notFileFilter(oldFilesFilter);

    Collection<File> files = FileUtils.listFiles(folder, FileFilterUtils.andFileFilter(ioFileFilter, notOldFilesFilter),
            FileFilterUtils.makeSVNAware(FileFilterUtils.makeCVSAware(null)));
    Collection<String> ret = newArrayList();
    for (File file : files) {
        ret.add(file.getAbsolutePath());
    }
    return ret;
}
项目:cleartk    文件:EvaluateNamedEntityChunker.java   
public static void main(String[] args) throws Exception {
  Options options = CliFactory.parseArguments(Options.class, args);

  // find training files
  List<File> trainFiles = new ArrayList<File>(FileUtils.listFiles(
      options.getTrainDirectory(),
      new MascTextFileFilter(),
      FileFilterUtils.falseFileFilter()));

  // run cross validation
  EvaluateNamedEntityChunker evaluator = new EvaluateNamedEntityChunker(
      options.getModelsDirectory());
  List<AnnotationStatistics<String>> foldStats = evaluator.crossValidation(trainFiles, 2);
  AnnotationStatistics<String> crossValidationStats = AnnotationStatistics.addAll(foldStats);

  System.err.println("Cross Validation Results:");
  System.err.print(crossValidationStats);
  System.err.println();
  System.err.println(crossValidationStats.confusions());
  System.err.println();

  // train and save a model using all the data
  evaluator.trainAndTest(trainFiles, Collections.<File> emptyList());
}
项目:seauto    文件:PathUtils.java   
/**
 * Search for a specific file nested inside of a specific path
 * 
 * @param path
 *          - path that contains the file
 * @param fileName
 *          - file name of the file
 * @return - the file that was found
 * 
 * @throws IllegalStateException
 *           - if more then one file with that specific name was found.
 */
public static File getFileInPath(final String path, final String fileName)
{
  File dir = new File(path);

  // find the correct file
  List<File> files = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(fileName), TrueFileFilter.TRUE);

  LOG.debug("Files found: {}", Arrays.asList(files));

  if (files.size() != 1) {
    throw new IllegalStateException(String.format("Searching for a file '%s' did not result in the correct number of files! Found %d, expected %d", fileName, files.size(), 1));
  }

  return files.get(0);
}
项目:Genji    文件:LaTeXMeetingDatasourceTest.java   
/**
 * Run the LaTeXMeetingDatasource() constructor test.
 *
 * @generatedBy CodePro at 03.05.15 12:19
 */
@Test
public void testLaTeXMeetingDatasourceTestPrepareDirs()
    throws Exception {
    LaTeXMeetingDatasource ds = new LaTeXMeetingDatasource();
    String LATEXDIR = "homet" + File.separator + "Reports" + File.separator + "LaTeX";
    String LATEX_TMP_DIR = LATEXDIR + File.separator + "tmp" + String.valueOf(new Date().getTime());
    String templateDir = "homet" + File.separator + "ExportTemplates" + File.separator + "latexTemplates"+File.separator + "Requirements";
    ReportBeansToLaTeXConverter rc = new ReportBeansToLaTeXConverter();

    rc.prepareDirectories(new File(templateDir));

    Collection<File> files = FileUtils.listFilesAndDirs(new File(LATEXDIR), FileFilterUtils.trueFileFilter(),
                                                                            FileFilterUtils.trueFileFilter());

    assertEquals(2, files.size());
}
项目:tassal    文件:FilesetSplit.java   
/**
 * @param args
 */
public static void main(final String[] args) {
    if (args.length < 7) {
        System.err
                .println("Usage fromDirectory toDirectory fileSuffix <<segmentName_i> <weight_i> ...>");
        System.exit(-1);
    }

    final File fromDirectory = new File(args[0]);
    final File toDirectory = new File(args[1]);

    final IOFileFilter fileFilter = FileFilterUtils
            .suffixFileFilter(args[2]);

    final Map<String, Double> segments = Maps.newHashMap();

    for (int i = 3; i < args.length; i += 2) {
        segments.put(args[i], Double.valueOf(args[i + 1]));
    }

    LOGGER.info("Splitting files in segments " + segments);
    splitFiles(fromDirectory, toDirectory, segments, fileFilter,
            UNIFORM_FILE_WEIGHT);
}
项目:aem-dependencies    文件:DependenciesGenerator.java   
public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        throw new IllegalArgumentException("Please specify path to the felix directory. " +
                "Usually it is located under 'crx-quickstart/launchpad/felix'.");
    }
    File rootFolder = new File(args[0]);
    if (rootFolder.exists() && rootFolder.isDirectory() && rootFolder.canRead()) {
        Collection<File> bundles = FileUtils.listFiles(rootFolder,
                FileFilterUtils.nameFileFilter("bundle.jar"),
                FileFilterUtils.directoryFileFilter());
        for (File bundle : bundles) {
            processBundle(bundle);
        }
        Collections.sort(deps);
        System.out.println("**********************************************************************");
        for (Dependency dep : deps) {
            System.out.println(dep);
        }
    } else {
        throw new IllegalArgumentException("Path does not exist or it is not an accessible folder.");
    }
}
项目:OLE-INST    文件:BatchFileLookupableHelperServiceImpl.java   
protected IOFileFilter getPathBasedFileFilter() {
    List<File> selectedFiles = getSelectedDirectories(getSelectedPaths());
    if (selectedFiles.isEmpty()) {
        return null;
    }
    IOFileFilter fileFilter = null;
    for (File selectedFile : selectedFiles) {
        IOFileFilter subFilter = new SubDirectoryFileFilter(selectedFile);
        if (fileFilter == null) {
            fileFilter = subFilter;
        }
        else {
            fileFilter = FileFilterUtils.orFileFilter(fileFilter, subFilter);
        }
    }
    return fileFilter;
}
项目:st-toolset    文件:AbstractI18nService.java   
public AbstractI18nService() {
    final String[] bundleNames = getBundles();
    if (bundleNames == null || bundleNames.length == 0) {
        return;
    }
    bundles = new HashMap<>();
    final File folder = new File(getPropertiesPath());
    final String suffix = ".properties";
    for (String name: bundleNames) {
        final String prefix = name + "_";
        final File[] files = folder.listFiles((FilenameFilter) FileFilterUtils.and(
                FileFilterUtils.prefixFileFilter(prefix), FileFilterUtils.suffixFileFilter(suffix)));
        Map<String, Properties> values = new HashMap();
        bundles.put(name, values);
        for (File file: files) {
            final String lang = file.getName().replace(prefix, "").replace(suffix, "");
            try (Reader propertiesFileReader = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
                final Properties properties = new Properties();
                properties.load(propertiesFileReader);
                values.put(lang, properties);
            } catch (IOException e) {
                throw new RuntimeException("Can't load i18n file", e);
            }
        }
    }
}
项目:kfs    文件:BatchFileLookupableHelperServiceImpl.java   
protected IOFileFilter getPathBasedFileFilter() {
    List<File> selectedFiles = getSelectedDirectories(getSelectedPaths());
    if (selectedFiles.isEmpty()) {
        return null;
    }
    IOFileFilter fileFilter = null;
    for (File selectedFile : selectedFiles) {
        IOFileFilter subFilter = new SubDirectoryFileFilter(selectedFile);
        if (fileFilter == null) {
            fileFilter = subFilter;
        }
        else {
            fileFilter = FileFilterUtils.orFileFilter(fileFilter, subFilter);
        }
    }
    return fileFilter;
}
项目:kfs    文件:LicenseHeaderUpdate.java   
public static void handleJavaStyleComments( String baseDir ) throws Exception {
    IOFileFilter sourceFileFilter = FileFilterUtils.orFileFilter(
            FileFilterUtils.suffixFileFilter("java"),
            FileFilterUtils.suffixFileFilter("js") );
    sourceFileFilter = FileFilterUtils.orFileFilter(
            sourceFileFilter,
            FileFilterUtils.suffixFileFilter("css") );
    sourceFileFilter = FileFilterUtils.orFileFilter(
            sourceFileFilter,
            FileFilterUtils.suffixFileFilter("groovy") );
    sourceFileFilter = FileFilterUtils.makeSVNAware(sourceFileFilter);
    sourceFileFilter = FileFilterUtils.makeFileOnly(sourceFileFilter);

    LicensableFileDirectoryWalker dw = new LicensableFileDirectoryWalker(sourceFileFilter, "/*", " * ", " */");
    Collection<String> results = dw.run( baseDir );
    System.out.println( results );
}
项目:kfs    文件:LicenseHeaderUpdate.java   
public static void handleXMLStyleComments( String baseDir ) throws Exception {
    IOFileFilter sourceFileFilter = FileFilterUtils.orFileFilter(
            FileFilterUtils.suffixFileFilter("xml"),
            FileFilterUtils.suffixFileFilter("jrxml") );
    sourceFileFilter = FileFilterUtils.orFileFilter(
            sourceFileFilter,
            FileFilterUtils.suffixFileFilter("html") );
    sourceFileFilter = FileFilterUtils.orFileFilter(
            sourceFileFilter,
            FileFilterUtils.suffixFileFilter("htm") );
    sourceFileFilter = FileFilterUtils.orFileFilter(
            sourceFileFilter,
            FileFilterUtils.suffixFileFilter("xsd") );
    sourceFileFilter = FileFilterUtils.orFileFilter(
            sourceFileFilter,
            FileFilterUtils.suffixFileFilter("tld") );
    sourceFileFilter = FileFilterUtils.makeSVNAware(sourceFileFilter);
    sourceFileFilter = FileFilterUtils.makeFileOnly(sourceFileFilter);

    LicensableFileDirectoryWalker dw = new LicensableFileDirectoryWalker(sourceFileFilter, "<!--", "   - ", " -->");
    Collection<String> results = dw.run( baseDir );
    System.out.println( results );
}
项目:dbflute-intro    文件:TestConnectionLogic.java   
private Driver prepareJdbcDriver(String dbfluteVersion, OptionalThing<String> jdbcDriverJarPath, DatabaseInfoMap databaseInfoMap)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, MalformedURLException {
    final List<URL> urls = new ArrayList<URL>();
    if (jdbcDriverJarPath.isPresent()) {
        final String jarPath = jdbcDriverJarPath.get();
        final URL fileUrl = new File(jarPath).toURI().toURL();
        urls.add(fileUrl);
    } else {
        final File libDir = enginePhysicalLogic.findLibDir(dbfluteVersion);
        if (libDir.isDirectory()) {
            for (File existingJarFile : FileUtils.listFiles(libDir, FileFilterUtils.suffixFileFilter(".jar"), null)) {
                try {
                    urls.add(existingJarFile.toURI().toURL());
                } catch (MalformedURLException e) { // no way
                    throw new IllegalStateException("Failed to create the URL for the jar file: " + existingJarFile.getPath());
                }
            }
        }
    }
    final URLClassLoader loader = URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]));
    final String jdbcDriver = databaseInfoMap.getDriver();

    @SuppressWarnings("unchecked")
    final Class<Driver> driverClass = (Class<Driver>) loader.loadClass(jdbcDriver);
    return driverClass.newInstance();
}
项目:roboconf-platform    文件:TemplateWatcher.java   
@Override
public void onStart( final FileAlterationObserver observer ) {

    if( this.alreadyStarted.getAndSet( true ))
        return;

    this.logger.fine("Initial provisioning of templates...");
    final Collection<File> templateFiles = FileUtils.listFiles(
            this.templateDir,

            // Find readable template files.
            FileFilterUtils.and(
                    FileFilterUtils.suffixFileFilter( ".tpl" ),
                    CanReadFileFilter.CAN_READ),

            // Directory filter: go through the root template directory and its direct children.
            new TemplateDirectoryFileFilter( this.templateDir ));

    process( templateFiles );
}
项目:codemining-utils    文件:FilesetSplit.java   
/**
 * @param args
 */
public static void main(final String[] args) {
    if (args.length < 7) {
        System.err
                .println("Usage fromDirectory toDirectory fileSuffix <<segmentName_i> <weight_i> ...>");
        System.exit(-1);
    }

    final File fromDirectory = new File(args[0]);
    final File toDirectory = new File(args[1]);

    final IOFileFilter fileFilter = FileFilterUtils
            .suffixFileFilter(args[2]);

    final Map<String, Double> segments = Maps.newHashMap();

    for (int i = 3; i < args.length; i += 2) {
        segments.put(args[i], Double.valueOf(args[i + 1]));
    }

    LOGGER.info("Splitting files in segments " + segments);
    splitFiles(fromDirectory, toDirectory, segments, fileFilter,
            UNIFORM_FILE_WEIGHT);
}
项目:javaccPlugin    文件:CompiledJavaccFile.java   
private File scanSourceFiles(String compiledJavaccFilePackage, Collection<File> sourceFiles) {
    for (File sourceFile : sourceFiles) {
        logger.debug("Scanning source file [{}] looking for a file named [{}] in package [{}]", sourceFile, compiledJavaccFile.getName(), compiledJavaccFilePackage);
        if (sourceFile.isDirectory()) {
            Collection<File> childFiles = FileUtils.listFiles(sourceFile, FileFilterUtils.suffixFileFilter(".java"), TrueFileFilter.TRUE);
            File matchingChildFile = scanSourceFiles(compiledJavaccFilePackage, childFiles);
            if (matchingChildFile != null) {
                return matchingChildFile;
            }
        } else {
            if (FilenameUtils.isExtension(sourceFile.getName(), "java") && compiledJavaccFile.getName().equals(sourceFile.getName())) {
                String packageName = getPackageName(sourceFile);

                if (compiledJavaccFilePackage.equals(packageName)) {
                    return sourceFile;
                }
            }
        }
    }

    return null;
}
项目:jboss-fuse-examples    文件:BodyToFileErrorStrategyGetBackedupTest.java   
@Test
public void getBackedupLinesMultpleHandlesAndGets() throws MalformedURLException {
    String pathToPersistenceStore = rootDirectory + "/BodyToFileErrorStrategy/getBackedupLinesMultpleHandlesAndGets";
    AmqErrorStrategy<String[]> strategy = new BodyToFileErrorStrategy(pathToPersistenceStore);

    for (int i = 0; i < 10; i++) {
        strategy.handle(new JMSException("Because"), "Test", new Object[] {"gareth", "healy" + i});
        List<String[]> answer = strategy.getBackedupLines("Test");

        Assert.assertNotNull(answer);
        Assert.assertEquals(1, answer.size());
        Assert.assertArrayEquals(new Object[] {"gareth", "healy" + i}, answer.get(0));
    }

    File directory = FileUtils.toFile(new URL("file:" + pathToPersistenceStore + "/.complete"));
    Collection<File> files = FileUtils.listFiles(directory, FileFilterUtils.fileFileFilter(), null);

    Assert.assertNotNull(files);
    Assert.assertEquals(10, files.size());
}
项目:CustomThings    文件:ConfigHandler.java   
private static void addCustoms(ResourcePackAssembler assembler)
{
    initialize("recordMusic");
    JsonObject root = new JsonObject();
    for (File f : new File(baseDir.getAbsolutePath() + "/recordMusic").listFiles((FileFilter) FileFilterUtils.suffixFileFilter(".ogg")))
    {
        assembler.addCustomFile("assets/minecraft/sounds/records", f); // add record .ogg
        JsonObject event = new JsonObject();
        event.addProperty("category", "record"); // put under the "record" category for sound options
        JsonArray sounds = new JsonArray(); // array of sounds (will only ever be one)
        JsonObject sound = new JsonObject(); // sound object (instead of primitive to use 'stream' flag)
        sound.addProperty("name", "records/" + getSimpleName(f)); // path to file
        sound.addProperty("stream", true); // prevents lag for large files
        sounds.add(sound);
        event.add("sounds", sounds);
        root.add("records." + CustomThings.MODID + "." + getSimpleName(f), event); // event name (same as name sent to ItemCustomRecord)
    }
    assembler.addCustomFile("assets/minecraft", EnderFileUtils.writeToFile(baseDir.getAbsolutePath() + "/recordMusic/sounds.json", gson.toJson(root)));
}
项目:proctor    文件:SvnWorkspaceProviderImpl.java   
@Override
public void run() {
    try {
        if(!shutdown.get()) {
            LOGGER.info("Actively cleaning up directories older than " + TimeUnit.MILLISECONDS.toHours(cleanupAgeMillis) + " hours");
            final IOFileFilter olderThanFilter = FileFilterUtils.asFileFilter(olderThanFileFilter(cleanupAgeMillis));
            final IOFileFilter tempDirFilter =
                FileFilterUtils.prefixFileFilter(prefix);

            /**
             * Delete directories that are:
             * older than [clean up age millis]
             * starts with temp-dir-prefix
             */
            final IOFileFilter deleteAfterMillisFilter = FileFilterUtils.makeDirectoryOnly(
                FileFilterUtils.andFileFilter(olderThanFilter, tempDirFilter)
            );
            deleteUserDirectories(rootDirectory, deleteAfterMillisFilter);
        } else {
            LOGGER.info("Currently shutdown, skipping older-than directory cleanup");
        }
    } catch (Exception e) {
        LOGGER.error("Unhandled Exception during directory cleanup", e);
    }
}
项目:proctor    文件:LocalDirectoryCore.java   
@Override
public TestVersionResult determineVersions(String fetchRevision) throws StoreException.ReadException {
    final File testDir = new File(baseDir + File.separator + testDefinitionsDirectory);
    // List all of the directories, excluding the directories created by svn (implementation is ignoring directories named '.svn'
    final File[] testDefFiles = testDir.listFiles( (FileFilter) FileFilterUtils.makeSVNAware(FileFilterUtils.directoryFileFilter()) );
    final List<TestVersionResult.Test> tests = Lists.newArrayListWithExpectedSize(testDefFiles.length);
    for (final File testDefFile : testDefFiles) {
        final String testName = testDefFile.getName();
        tests.add(new TestVersionResult.Test(testName, fetchRevision));
    }

    return new TestVersionResult(
        tests,
        new Date(System.currentTimeMillis()),
        System.getenv("USER"),
        String.valueOf(System.currentTimeMillis()),
        ""
    );
}
项目:proctor    文件:AbstractProctorMojo.java   
void createTotalSpecifications(final File dir, final String packageDirectory) throws MojoExecutionException {

        if (dir.equals(null)) {
            throw new MojoExecutionException("Could not read from directory " + dir.getPath());
        }
        final File[] files = dir.listFiles();
        if (files == null) {
            return;
        }
        final File[] providedContextFiles = dir.listFiles((java.io.FileFilter) FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter(), FileFilterUtils.nameFileFilter("providedcontext.json")));
        if (providedContextFiles.length == 1) {
            final File parent = providedContextFiles[0].getParentFile();
            final File outputDir = new File(getSpecificationOutput() + File.separator + packageDirectory.substring(0,packageDirectory.lastIndexOf(File.separator)));
            outputDir.mkdirs();
            try {
                generateTotalSpecification(parent, outputDir);
            } catch (final CodeGenException e) {
                throw new MojoExecutionException("Couldn't create total specification",e);
            }
        }
        for (File entry : dir.listFiles()) {
            if (entry.isDirectory()) {
                createTotalSpecifications(entry, (packageDirectory == null) ? entry.getName() : packageDirectory + File.separator + entry.getName());
            }
        }
    }
项目:jackrabbit-migration    文件:PathTransformer.java   
/**
 * repo directory path
 * @param repoPath
 * @return
 */
public static String[] transform(String repoPath) {
    if (repoPath.isEmpty())
        return new String[] {};
    String parent="";
    if (repoPath.endsWith("/*")) {
        parent=repoPath.substring(0, Math.max(1, repoPath.length()-2));
    } 
    if (parent.isEmpty())
        return new String[]{repoPath};
    File dir=new File(parent);
    if (!dir.exists()) 
        return new String[] {};
    List<String> files=new ArrayList<String>();
    for (String f:dir.list(FileFilterUtils.directoryFileFilter())) {
        files.add(parent+"/"+f);
    }
    return files.toArray(new String[0]);
}
项目:metka    文件:StartupScanner.java   
/**
 * Gathers data configurations from file and saves them to database
 */
@PostConstruct
public void scanForConfigurations() {
    Logger.debug(getClass(), "Scanning for configurations.");
    File confDir = new File(rootFolder+"configuration");

    Collection<File> files = FileUtils.listFiles(confDir, FileFilterUtils.suffixFileFilter(".json"), TrueFileFilter.TRUE);

    for (File file : files) {
        Pair<SerializationResults, Configuration> conf = json.deserializeDataConfiguration(file);
        if(conf.getLeft() != SerializationResults.DESERIALIZATION_SUCCESS) {
            Logger.error(getClass(), "Failed at deserializing "+file.getName());
            continue;
        }
        Pair<ReturnResult, Configuration> existing = configRepo.findConfiguration(conf.getRight().getKey());
        if(existing.getLeft() != ReturnResult.CONFIGURATION_FOUND && existing.getLeft() != ReturnResult.DATABASE_DISCREPANCY) {
            configRepo.insert(conf.getRight());
        }
    }

    postConstructs++;
    if(postConstructs == 3) {
        sendAmqpProcessMessage();
    }
}
项目:metka    文件:StartupScanner.java   
/**
 * Gathers gui-configuration from file and saves them to database
 */
@PostConstruct
public void scanForGUIConfigurations() {
    Logger.debug(getClass(), "Scanning for gui configurations.");
    File guiDir = new File(rootFolder+"gui");

    Collection<File> files = FileUtils.listFiles(guiDir, FileFilterUtils.suffixFileFilter(".json"), TrueFileFilter.TRUE);

    for (File file : files) {
        Pair<SerializationResults, GUIConfiguration> gui = json.deserializeGUIConfiguration(file);

        if(gui.getLeft() != SerializationResults.DESERIALIZATION_SUCCESS) {
            Logger.error(getClass(), "Failed at deserializing "+file.getName());
            continue;
        }
        Pair<ReturnResult, GUIConfiguration> existing = configRepo.findGUIConfiguration(gui.getRight().getKey());
        if(existing.getLeft() != ReturnResult.CONFIGURATION_FOUND && existing.getLeft() != ReturnResult.DATABASE_DISCREPANCY) {
            configRepo.insert(gui.getRight());
        }
    }

    postConstructs++;
    if(postConstructs == 3) {
        sendAmqpProcessMessage();
    }
}