Example usage for java.io FilenameFilter FilenameFilter

List of usage examples for java.io FilenameFilter FilenameFilter

Introduction

In this page you can find the example usage for java.io FilenameFilter FilenameFilter.

Prototype

FilenameFilter

Source Link

Usage

From source file:org.italiangrid.storm.webdav.authz.vomap.VOMapDetailServiceBuilder.java

public VOMapDetailsService build() {

    if (!serviceConf.enableVOMapFiles()) {
        logger.info("VOMS Map files disabled.");
        return null;
    }/*from w  w  w.  j  a  va 2 s .c  om*/

    File configDir = new File(serviceConf.getVOMapFilesConfigDir());
    directorySanityChecks(configDir);

    File[] files = configDir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {

            return name.endsWith(VOMAPFILE_SUFFIX);

        }
    });

    if (files.length == 0) {
        logger.warn("No mapfiles found in {}. Was looking for files ending in {}", VOMAPFILE_SUFFIX);
        return null;
    }

    Set<VOMembershipProvider> providers = new HashSet<VOMembershipProvider>();
    for (File f : files) {
        try {
            String voName = FilenameUtils.removeExtension(f.getName());

            VOMembershipProvider prov = new DefaultVOMembershipProvider(voName,
                    new MapfileVOMembershipSource(voName, f));

            providers.add(prov);

        } catch (Throwable t) {
            logger.error("Error parsing mapfile {}: {}", f.getAbsolutePath(), t.getMessage(), t);
            continue;
        }
    }

    return new DefaultVOMapDetailsService(providers, serviceConf.getVOMapFilesRefreshIntervalInSeconds());
}

From source file:info.magnolia.cms.beans.config.Bootstrapper.java

/**
 * Repositories appears to be empty and the <code>"magnolia.bootstrap.dir</code> directory is configured in
 * web.xml. Loops over all the repositories and try to load any xml file found in a subdirectory with the same name
 * of the repository. For example the <code>config</code> repository will be initialized using all the
 * <code>*.xml</code> files found in <code>"magnolia.bootstrap.dir</code><strong>/config</strong> directory.
 * @param bootdirs bootstrap dir// ww  w  .  ja  va  2s  . c om
 */
protected static void bootstrapRepositories(String[] bootdirs) {

    if (log.isInfoEnabled()) {
        log.info("-----------------------------------------------------------------"); //$NON-NLS-1$
        log.info("Trying to initialize repositories from:");
        for (int i = 0; i < bootdirs.length; i++) {
            log.info(bootdirs[i]);
        }
        log.info("-----------------------------------------------------------------"); //$NON-NLS-1$
    }

    MgnlContext.setInstance(MgnlContext.getSystemContext());

    Iterator repositoryNames = ContentRepository.getAllRepositoryNames();
    while (repositoryNames.hasNext()) {
        String repository = (String) repositoryNames.next();

        Set xmlfileset = new TreeSet(new Comparator() {

            // remove file with the same name in different dirs
            public int compare(Object file1obj, Object file2obj) {
                File file1 = (File) file1obj;
                File file2 = (File) file2obj;
                String fn1 = file1.getParentFile().getName() + '/' + file1.getName();
                String fn2 = file2.getParentFile().getName() + '/' + file2.getName();
                return fn1.compareTo(fn2);
            }
        });

        for (int j = 0; j < bootdirs.length; j++) {
            String bootdir = bootdirs[j];
            File xmldir = new File(bootdir, repository);
            if (!xmldir.exists() || !xmldir.isDirectory()) {
                continue;
            }

            File[] files = xmldir.listFiles(new FilenameFilter() {

                public boolean accept(File dir, String name) {
                    return name.endsWith(DataTransporter.XML) || name.endsWith(DataTransporter.ZIP)
                            || name.endsWith(DataTransporter.GZ); //$NON-NLS-1$
                }
            });

            xmlfileset.addAll(Arrays.asList(files));

        }

        if (xmlfileset.isEmpty()) {
            log.info("No bootstrap files found in directory [{}], skipping...", repository); //$NON-NLS-1$
            continue;
        }

        log.info("Trying to import content from {} files into repository [{}]", //$NON-NLS-1$
                Integer.toString(xmlfileset.size()), repository);

        File[] files = (File[]) xmlfileset.toArray(new File[xmlfileset.size()]);
        Arrays.sort(files, new Comparator() {

            public int compare(Object file1, Object file2) {
                String name1 = StringUtils.substringBeforeLast(((File) file1).getName(), "."); //$NON-NLS-1$
                String name2 = StringUtils.substringBeforeLast(((File) file2).getName(), "."); //$NON-NLS-1$
                // a simple way to detect nested nodes
                return name1.length() - name2.length();
            }
        });

        try {
            for (int k = 0; k < files.length; k++) {

                File xmlfile = files[k];
                DataTransporter.executeBootstrapImport(xmlfile, repository);
            }

        } catch (IOException ioe) {
            log.error(ioe.getMessage(), ioe);
        } catch (OutOfMemoryError e) {
            int maxMem = (int) (Runtime.getRuntime().maxMemory() / 1024 / 1024);
            int needed = Math.max(256, maxMem + 128);
            log.error("Unable to complete bootstrapping: out of memory.\n" //$NON-NLS-1$
                    + "{} MB were not enough, try to increase the amount of memory available by adding the -Xmx{}m parameter to the server startup script.\n" //$NON-NLS-1$
                    + "You will need to completely remove the magnolia webapp before trying again", //$NON-NLS-1$
                    Integer.toString(maxMem), Integer.toString(needed));
            break;
        }

        log.info("Repository [{}] has been initialized.", repository); //$NON-NLS-1$

    }
}

From source file:com.shazam.fork.suite.TestClassScanner.java

private File[] getDexFiles(File instrumentationApkFile, File dexFilesFolder) throws IOException {
    dumpDexFilesFromApk(instrumentationApkFile, dexFilesFolder);
    return dexFilesFolder.listFiles(new FilenameFilter() {
        @Override/*from  w  w  w.  j  a  v  a  2s  .  c om*/
        public boolean accept(File dir, String name) {
            return name.startsWith("classes") && name.endsWith(".dex");
        }
    });
}

From source file:net.openbyte.gui.WelcomeFrame.java

public WelcomeFrame() {
    listItems.clear();//from w  w w  .j a  v a 2 s. c  o m
    Launch.projectNames.clear();
    Launch.nameToSolution.clear();
    initComponents();
    list1.setModel(listItems);
    try {
        xImagePanel1
                .setImage(ImageIO.read(getClass().getClassLoader().getResourceAsStream("openbytelogo.png")));
    } catch (IOException e) {
        e.printStackTrace();
    }
    File[] projectFiles = Files.WORKSPACE_DIRECTORY.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".openproj");
        }
    });
    for (File projectFile : projectFiles) {
        OpenProjectSolution solution = OpenProjectSolution.getProjectSolutionFromFile(projectFile);
        Launch.nameToSolution.put(solution.getProjectName(), solution);
        Launch.projectNames.add(solution.getProjectName());
    }
    for (String projectName : Launch.projectNames) {
        WelcomeFrame.listItems.addElement(projectName);
    }
    list1.addMouseListener(new MouseAdapter() {

        int lastSelectedIndex;

        public void mouseClicked(MouseEvent e) {

            int index = list1.locationToIndex(e.getPoint());

            if (index != -1 && index == lastSelectedIndex) {
                list1.clearSelection();
            }

            lastSelectedIndex = list1.getSelectedIndex();
        }
    });
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.comments.pipeline.DebateArgumentReader.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    File[] fileArray = sourceLocation.listFiles(new FilenameFilter() {
        @Override/*from w ww  . j  a va2s.c  o  m*/
        public boolean accept(File dir, String name) {
            return name.endsWith(".xml");
        }
    });

    if (fileArray != null) {
        this.files.addAll(Arrays.asList(fileArray));
    }
}

From source file:com.thed.launcher.EggplantZBotScriptLauncher.java

@Override
public void testcaseExecutionResult() {
    String scriptPath = LauncherUtils.getFilePathFromCommand(currentTestcaseExecution.getScriptPath());
    logger.info("Script Path is " + scriptPath);
    File scriptFile = new File(scriptPath);
    String scriptName = scriptFile.getName().split("\\.")[0];
    logger.info("Script Name is " + scriptName);
    File resultsFolder = new File(
            scriptFile.getParentFile().getParentFile().getAbsolutePath() + File.separator + "Results");
    File statisticalFile = resultsFolder.listFiles(new FilenameFilter() {
        @Override//  ww w . j a  v  a  2s. c o m
        public boolean accept(File file, String s) {
            return StringUtils.endsWith(s, "Statistics.xml");
        }
    })[0];
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        Document statisticalDoc = getDoc(statisticalFile);
        String result = xpath.compile("/statistics/script[@name='" + scriptName + "']/LastStatus/text()")
                .evaluate(statisticalDoc, XPathConstants.STRING).toString();
        logger.info("Result is " + result);
        String comments;
        if (StringUtils.equalsIgnoreCase(result, "Success")) {
            logger.info("Test success detected");
            status = currentTestcaseExecution.getTcId() + ": " + currentTestcaseExecution.getScriptId()
                    + " STATUS: Script Successfully Executed";
            currentTcExecutionResult = new Integer(1);
            comments = " Successfully executed on " + agent.getAgentHostAndIp();
        } else {
            logger.info("Test failure detected, getting error message");
            status = currentTestcaseExecution.getTcId() + ": " + currentTestcaseExecution.getScriptId()
                    + " STATUS: Script Successfully Executed";
            currentTcExecutionResult = new Integer(2);
            comments = " Error in test: ";
            String lastRunDateString = xpath
                    .compile("/statistics/script[@name='" + scriptName + "']/LastRun/text()")
                    .evaluate(statisticalDoc);
            //Date lastRunDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(lastRunDateString);
            File historyFile = new File(resultsFolder.getAbsolutePath() + File.separator + scriptName
                    + File.separator + "RunHistory.xml");
            Document historyDoc = getDoc(historyFile);
            //xpath = XPathFactory.newInstance().newXPath();
            String xpathExpr = "/runHistory[@script='" + scriptName + "']/run[contains(RunDate, '"
                    + StringUtils.substringBeforeLast(lastRunDateString, " ") + "')]/ErrorMessage/text()";
            logger.info("Using xPath to find errorMessage " + xpathExpr);
            comments += xpath.compile(xpathExpr).evaluate(historyDoc, XPathConstants.STRING);
            logger.info("Sending comments: " + comments);
        }
        if (currentTcExecutionResult != null) {
            ScriptUtil.updateTestcaseExecutionResult(url, currentTestcaseExecution, currentTcExecutionResult,
                    comments);
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error in reading process steams \n", e);
    }
}

From source file:integration.util.mongodb.BsonReader.java

protected Map<String, List<DBObject>> readBsonDirectory(File directory) {
    final Map<String, List<DBObject>> collections = new HashMap<>();

    File[] collectionListing = directory.listFiles(new FilenameFilter() {
        @Override//ww  w.ja va 2  s.c  om
        public boolean accept(File dir, String name) {
            return (name.endsWith(".bson") && !name.startsWith("system.indexes."));
        }
    });

    if (collectionListing != null) {
        for (File collection : collectionListing) {
            List<DBObject> collectionData = readBsonFile(collection.getAbsolutePath());
            collections.put(FilenameUtils.removeExtension(collection.getName()), collectionData);
        }
    }

    return collections;
}

From source file:de.banapple.maven.antlr.SyntaxDiagramMojo.java

/**
 * Creates an index file in the output directory containing all
 * generated images.//  www .  ja  va2s.c  o  m
 */
private void createIndex() {
    /* retrieve all png files */
    String[] imageFilenames = outputDirectory.list(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            return filename.endsWith("png");
        }
    });

    /* sort filenames by lower case first */
    Arrays.sort(imageFilenames);

    StringBuilder content = new StringBuilder();
    content.append("<html>");
    content.append("<body>");

    /* table of contents */
    content.append("<a name=\"top\" />");
    content.append("<ol>");
    for (String filename : imageFilenames) {
        String name = filename.substring(0, filename.length() - 4);
        content.append("<li>").append("<a href=\"#").append(name).append("\">").append(name).append("</a>")
                .append("</li>");
    }
    content.append("</ol>");

    /* images */
    for (String filename : imageFilenames) {
        String name = filename.substring(0, filename.length() - 4);
        content.append("<h2>").append(name).append("</h2>");
        content.append("<a name=\"").append(name).append("\" />");
        content.append("<img src=\"").append(filename).append("\" />");
        content.append("<br/><a href=\"#top\">up</a>");
    }
    content.append("</body>");
    content.append("</html>");

    File indexFile = new File(outputDirectory, "index.html");
    try {
        IOUtils.write(content.toString(), new FileOutputStream(indexFile));
    } catch (Exception e) {
        getLog().error("failed to generate index file", e);
        throw new RuntimeException(e);
    }
}

From source file:br.edimarmanica.trinity.extract.Extract.java

private void train(int offset) throws IOException {
    int start = ((WINDOW_SIZE - NR_SHARED_PAGES) * offset) + NR_SHARED_PAGES;
    int end = start + WINDOW_SIZE - NR_SHARED_PAGES;

    if (General.DEBUG) {
        System.out.println("Starting training");
    }/*ww w. j  a va 2  s  .  co m*/
    TokeniserConfig tokeniserConf;
    try {
        tokeniserConf = new TokeniserConfig(new File(System.getProperty("user.dir") + "/Tokeniser.cfg"));
        tokeniser = new Tokeniser(tokeniserConf);
    } catch (ParserConfigurationException | SAXException | IOException | REException ex) {
        Logger.getLogger(Extract.class.getName()).log(Level.SEVERE, null, ex);
    }

    File dir = new File(Paths.PATH_BASE + site.getPath());
    int i = 0;
    for (File fPage : dir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".html") || name.endsWith(".htm");
        }
    })) {
        if (i < NR_SHARED_PAGES || (i >= start && i < end)) {
            if (General.DEBUG) {
                System.out.println("\t Page (" + i + "): " + fPage.getName());
            }
            train(fPage);
        }
        i++;
    }

    Statistic stat = new Statistic();
    if (General.DEBUG) {
        System.out.println("Learning extraction rules...");
    }
    stat.startCPUWatch();
    String regex = Learner.learn(root, 1, 100, tokeniser);
    //System.out.println(regex);
    stat.stopCPUWatch();
    if (General.DEBUG) {
        System.out.println("CPU Learning time: " + stat.getCPUInterval() / 1.0E10D);
    }

    compileRegex(regex);
    if (General.DEBUG) {
        System.out.println("Ending training");
    }
}

From source file:WpRDFFunctionLibrary.java

public static IDMapperStack createBridgeDbMapper(Properties prop)
        throws ClassNotFoundException, IDMapperException {
    BioDataSource.init();/*from   w  ww.j a  v  a 2s .c  om*/
    Class.forName("org.bridgedb.rdb.IDMapperRdb");
    File dir = new File(prop.getProperty("bridgefiles")); //TODO Get Refector to get them directly form bridgedb.org
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".bridge");
        }
    };

    File[] bridgeDbFiles = dir.listFiles(filter);
    IDMapperStack mapper = new IDMapperStack();
    for (File bridgeDbFile : bridgeDbFiles) {
        System.out.println(bridgeDbFile.getAbsolutePath());
        mapper.addIDMapper("idmapper-pgdb:" + bridgeDbFile.getAbsolutePath());
    }
    return mapper;
}