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:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

private static void zipDir(File sourceDir, final File destFile, ZipOutputStream zos) throws IOException {
    File[] dirList = sourceDir.listFiles(new FileFilter() {
        public boolean accept(File f) {
            return !f.getName().endsWith(destFile.getName());
        }/*  ww w.j a  va 2 s  .  c o m*/
    });
    for (int i = 0; i < dirList.length; i++) {
        File f = dirList[i];
        if (f.isDirectory()) {
            zipDir(f, destFile, zos);
        } else {
            int bytesIn = 0;
            byte[] readBuffer = new byte[2156];
            FileInputStream fis = new FileInputStream(f);
            ZipEntry entry = new ZipEntry(sourceDir.getName() + File.separator + f.getName());
            zos.putNextEntry(entry);
            while ((bytesIn = fis.read(readBuffer)) != -1) {
                zos.write(readBuffer, 0, bytesIn);
            }
            fis.close();
        }
    }
}

From source file:org.apache.falcon.resource.metadata.LineageMetadataResourceTest.java

@Test
public void testSerializeGraph() throws Exception {
    LineageMetadataResource resource = new LineageMetadataResource();
    Response response = resource.serializeGraph();
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());

    // verify file exists
    String path = StartupProperties.get().getProperty("falcon.graph.serialize.path");
    File[] jsonFiles = new File(path).listFiles(new FileFilter() {
        @Override/*from ww  w  . jav a2 s . c  o m*/
        public boolean accept(File file) {
            return file.isFile() && file.getName().endsWith(".json");
        }
    });
    Assert.assertTrue(jsonFiles.length > 0);
}

From source file:com.ckfinder.connector.utils.FileUtils.java

/**
* Checks if folder has any subfolders but respects ACL and hideFolders
* setting from configuration.//from   w ww.j  a  v a 2  s  . co m
* @param dirPath path to current folder.
 * @param dir current folder being checked. Represented by File object.
 * @param configuration configuration object.
 * @param resourceType name of resource type, folder is assignd to.
 * @param currentUserRole user role.
* @return true if there are any allowed and non-hidden subfolders.
*/
public static Boolean hasChildren(String dirPath, File dir, IConfiguration configuration, String resourceType,
        String currentUserRole) {
    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };
    File[] subDirsList = dir.listFiles(fileFilter);

    if (subDirsList != null) {
        for (int i = 0; i < subDirsList.length; i++) {
            String subDirName = subDirsList[i].getName();

            if (!FileUtils.checkIfDirIsHidden(subDirName, configuration) && AccessControlUtil
                    .getInstance(configuration).checkFolderACL(resourceType, dirPath + subDirName,
                            currentUserRole, AccessControlUtil.CKFINDER_CONNECTOR_ACL_FOLDER_VIEW))
                return true;
        }
    }
    return false;
}

From source file:gr.omadak.leviathan.asp.AspParser.java

public void parseDir(File sdir, boolean vbDefault) {
    FileFilter filter = new FileFilter() {
        public boolean accept(File f) {
            boolean result = f.isDirectory();
            if (!result) {
                String name = f.getName();
                int lastDot = name.lastIndexOf('.');
                result = lastDot > 0 && "asp".equalsIgnoreCase(name.substring(lastDot + 1));
            }//from  www. j a va 2  s .co  m
            return result;
        }
    };
    Stack stack = new Stack();
    stack.push(sdir);
    while (!stack.isEmpty()) {
        File dir = (File) stack.pop();
        for (Iterator it = IteratorUtils.arrayIterator(dir.listFiles(filter)); it.hasNext();) {
            File f = (File) it.next();
            if (f.isDirectory()) {
                stack.push(f);
            } else {
                try {
                    parseFile(f, vbDefault);
                } catch (ANTLRException ae) {
                    LOG.error("Failed to parse file:" + f.getAbsolutePath(), ae);
                } catch (Exception ex) {
                    LOG.error("Failed to parse file:" + f.getAbsolutePath() + " with error", ex);
                }
            }
        }
    }
}

From source file:nu.mine.kino.jenkins.plugins.projectmanagement.ProjectSummaryAction.java

public File[] getSummaryFiles() {
    System.out.println(owner.getRootDir());
    return owner.getRootDir().listFiles(new FileFilter() {

        @Override/*from   w  w  w.j  av  a  2  s  .c  om*/
        public boolean accept(File pathname) {
            boolean flag1 = false;
            boolean flag2 = false;
            if (!StringUtils.isEmpty(name)) {
                flag1 = !pathname.isDirectory() && pathname.getName().startsWith(name);
            }
            if (!StringUtils.isEmpty(redmineFileName)) {
                flag2 = !pathname.isDirectory() && pathname.getName().startsWith(redmineFileName);
            }
            return flag1 || flag2;

        }
    });
}

From source file:de.dfki.km.perspecting.obie.experiments.RelevanceRatingExperiment.java

@Test
public void avgCorrelations() throws Exception {

    String[] corpora = new String[] { "wikinews", "wikipedia", "gutenberg", "bbc_music", "bbc_nature" };

    for (String corpus : corpora) {

        final String path = "/home/adrian/Dokumente/diss/scoobie/results/dbpedia_en2/correlation/" + corpus
                + "/";
        // final String type = "pearson.csv";
        final String[] types = new String[] { "pearson.csv", "spearman.csv" };

        for (final String type : types) {

            File folder = new File(path);
            final File[] files = folder.listFiles(new FileFilter() {

                @Override/*from ww  w.  ja v a  2  s. com*/
                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(type);
                }
            });

            DoubleMatrix2D m = new DenseDoubleMatrix2D(9, 9);
            m.assign(new DoubleFunction() {
                @Override
                public double apply(double arg0) {
                    return 0;
                }
            });

            for (File file : files) {
                BufferedReader br = new BufferedReader(new FileReader(file));
                br.readLine();
                int row = 0;

                try {
                    for (String line = br.readLine(); line != null; line = br.readLine()) {
                        String[] items = line.split("\t");

                        for (int col = 0; col < 9; col++) {
                            double d = Double.parseDouble(items[col]);
                            if (Double.isNaN(d))
                                d = 0.0;
                            if (d < 0.001)
                                d = 0.0;
                            if (d > 1)
                                d = 1;
                            m.set(row, col, m.get(row, col) + d);
                        }

                        row++;
                        if (row == 9)
                            break;
                    }
                } catch (Exception e) {
                    throw new Exception(file.getName(), e);
                }
                br.close();
                // System.out.println(m);
            }

            final double count = m.get(0, 0);

            m.assign(new DoubleFunction() {
                @Override
                public double apply(double arg0) {
                    return arg0 / count;
                }
            });

            BufferedWriter w = new BufferedWriter(new FileWriter(
                    "/home/adrian/Dokumente/diss/scoobie/results/heatmap." + corpus + "." + type + ".gnup"));
            w.append("set terminal svg size 600,600 dynamic enhanced fname 'times'  fsize 12 butt solid\n");
            w.append("set output 'heatmaps." + corpus + "." + type + ".svg'\n");
            w.append("unset key\n");
            w.append("set view map\n");
            w.append("set style data linespoints\n");
            w.append("set xtics border in scale 0,0 mirror norotate  offset character 0, 0, 0\n");
            w.append("set ytics border in scale 0,0 mirror norotate  offset character 0, 0, 0\n");
            w.append("set xrange [ -0.500000 : 8.50000 ] noreverse nowriteback\n");
            w.append("set yrange [ -0.500000 : 8.50000 ] reverse nowriteback\n");
            w.append("set palette rgbformulae 2, -7, -7\n");
            w.append("splot '-' matrix with image\n");
            Formatter f = new Formatter();
            f.setFormat("%1.1f");
            f.setColumnSeparator(" ");
            w.append("#");
            w.append(f.toString(m));
            w.close();

            // FileUtils.writeStringToFile(new
            // File("/home/adrian/Dokumente/diss/scoobie/results/bbc_wildlife/correlation/"
            // + doc[doc.length - 1] + ".pearson.csv"),
            // f.toString(matrix.pearsonCorrelationDoubleMatrix()),
            // "utf-8");
        }
    }
}

From source file:ch.elexis.core.importer.div.importers.HL7Parser.java

public void importFromDir(final File dir, final File archiveDir, Result<?> res,
        boolean bCreatePatientIfNotExists) throws IOException {
    File[] files = dir.listFiles(new FileFilter() {

        public boolean accept(File pathname) {
            if (pathname.isDirectory()) {
                if (!pathname.getName().equalsIgnoreCase(archiveDir.getName())) {
                    return true;
                }/*from w w  w.ja  v a2 s .c o m*/
            } else {
                if (pathname.getName().toLowerCase().endsWith(".hl7")) { //$NON-NLS-1$
                    return true;
                }
            }
            return false;
        }
    });
    for (File file : files) {
        if (file.isDirectory()) {
            importFromDir(file, archiveDir, res, bCreatePatientIfNotExists);
        } else {
            Result<?> r = importFile(file, archiveDir, bCreatePatientIfNotExists);
            if (res == null) {
                res = r;
            } else {
                res.add(r.getSeverity(), 1, "", null, true); //$NON-NLS-1$
            }
        }
    }
}

From source file:org.apache.flume.client.avro.ReliableSpoolingFileEventReader.java

/**
 * Returns the next file to be consumed from the chosen directory.
 * If the directory is empty or the chosen file is not readable,
 * this will return an absent option./*w  w  w.  j a v a  2 s . c  om*/
 * If the {@link #consumeOrder} variable is {@link ConsumeOrder#OLDEST}
 * then returns the oldest file. If the {@link #consumeOrder} variable
 * is {@link ConsumeOrder#YOUNGEST} then returns the youngest file.
 * If two or more files are equally old/young, then the file name with
 * lower lexicographical value is returned.
 * If the {@link #consumeOrder} variable is {@link ConsumeOrder#RANDOM}
 * then cache the directory listing to amortize retreival cost, and return
 * any arbitary file from the directory.
 */
private Optional<FileInfo> getNextFile() {
    List<File> candidateFiles = Collections.emptyList();

    if (consumeOrder != ConsumeOrder.RANDOM || candidateFileIter == null || !candidateFileIter.hasNext()) {
        /* Filter to exclude finished or hidden files */
        FileFilter filter = new FileFilter() {
            public boolean accept(File candidate) {
                String fileName = candidate.getName();
                if ((candidate.isDirectory()) || (fileName.endsWith(completedSuffix))
                        || (fileName.startsWith(".")) || ignorePattern.matcher(fileName).matches()) {
                    return false;
                }
                return true;
            }
        };
        candidateFiles = Arrays.asList(spoolDirectory.listFiles(filter));
        listFilesCount++;
        candidateFileIter = candidateFiles.iterator();
    }

    if (!candidateFileIter.hasNext()) { // No matching file in spooling directory.
        return Optional.absent();
    }

    File selectedFile = candidateFileIter.next();
    if (consumeOrder == ConsumeOrder.RANDOM) { // Selected file is random.
        return openFile(selectedFile);
    } else if (consumeOrder == ConsumeOrder.YOUNGEST) {
        for (File candidateFile : candidateFiles) {
            long compare = selectedFile.lastModified() - candidateFile.lastModified();
            if (compare == 0) { // ts is same pick smallest lexicographically.
                selectedFile = smallerLexicographical(selectedFile, candidateFile);
            } else if (compare < 0) { // candidate is younger (cand-ts > selec-ts)
                selectedFile = candidateFile;
            }
        }
    } else { // default order is OLDEST
        for (File candidateFile : candidateFiles) {
            long compare = selectedFile.lastModified() - candidateFile.lastModified();
            if (compare == 0) { // ts is same pick smallest lexicographically.
                selectedFile = smallerLexicographical(selectedFile, candidateFile);
            } else if (compare > 0) { // candidate is older (cand-ts < selec-ts).
                selectedFile = candidateFile;
            }
        }
    }

    return openFile(selectedFile);
}

From source file:de.blizzy.documentr.access.UserStore.java

/**
 * Returns the user that has an OpenID whose real ID is equal to the specified OpenID.
 *
 * @throws UserNotFoundException when the user could not be found
 *///from  ww w  .j a  v  a2  s  . c  o  m
public User getUserByOpenId(String openId) throws IOException {
    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);
        File workingDir = RepositoryUtil.getWorkingDir(repo.r());
        FileFilter filter = new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.isFile() && file.getName().endsWith(USER_SUFFIX);
            }
        };
        for (File file : workingDir.listFiles(filter)) {
            String loginName = StringUtils.substringBeforeLast(file.getName(), USER_SUFFIX);
            String json = FileUtils.readFileToString(file, Charsets.UTF_8);
            User user = getUser(loginName, json);
            for (OpenId id : user.getOpenIds()) {
                if (id.getRealId().equals(openId)) {
                    return user;
                }
            }
        }

        throw new OpenIdNotFoundException(openId);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:org.b3log.latke.client.LatkeClient.java

/**
 * Gets repository names from backup directory.
 * /*from w w  w. j ava2 s .c o m*/
 * <p>
 * The returned repository names is the sub-directory names of the backup directory.
 * </p>
 * 
 * @return repository backup directory name
 */
private static Set<String> getRepositoryNamesFromBackupDir() {
    final File[] repositoryBackupDirs = backupDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(final File file) {
            return file.isDirectory();
        }
    });

    final Set<String> ret = new HashSet<String>();

    for (int i = 0; i < repositoryBackupDirs.length; i++) {
        final File file = repositoryBackupDirs[i];

        ret.add(file.getName());
    }

    return ret;
}