Example usage for org.apache.commons.io.filefilter FileFilterUtils ageFileFilter

List of usage examples for org.apache.commons.io.filefilter FileFilterUtils ageFileFilter

Introduction

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

Prototype

public static IOFileFilter ageFileFilter(File cutoffReference, boolean acceptOlder) 

Source Link

Document

Returns a filter that filters files based on a cutoff reference file.

Usage

From source file:com.ning.metrics.collector.hadoop.processing.LocalSpoolManager.java

public static Collection<File> findOldSpoolDirectories(final String basePath, final long cutoff) {
    final Collection<File> files = new java.util.LinkedList<File>();
    // Candidates ("old") directories are the ones last modified more than 2 hours ago
    final File[] found = new File(basePath)
            .listFiles((FileFilter) FileFilterUtils.and(FileFilterUtils.directoryFileFilter(),
                    FileFilterUtils.ageFileFilter(System.currentTimeMillis() - cutoff, true)));

    // Can't use FileUtils.listFiles as it doesn't yield directories
    if (found != null) {
        for (final File file : found) {
            if (file.isDirectory()) {
                files.add(file);//from www  .j  av  a 2 s.c  o m
            }
        }
    }

    return files;
}

From source file:it.geosolutions.tools.io.file.FileRemover.java

public static List<File> collectOlder(final long time, final int daysAgo, final File root) {
    if (daysAgo < 0) {
        return null;
    }//from   w w  w  .  j  ava 2  s  .  c om
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(time);
    int days = cal.get(Calendar.DAY_OF_YEAR);
    if (days >= daysAgo)
        cal.set(Calendar.DAY_OF_YEAR, days - daysAgo);
    else {
        // TODO use getActualMaximum for days
        cal.set(Calendar.DAY_OF_YEAR, (354 + (days - daysAgo)));
        cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) - 1);
    }
    // cal.getTime().toString()
    final Collector coll = new Collector(FileFilterUtils.andFileFilter(FileFilterUtils.directoryFileFilter(),
            FileFilterUtils.ageFileFilter(cal.getTime(), true)), 1);
    return coll.collect(root);
}

From source file:edu.lternet.pasta.portal.HarvestReportManager.java

/**
 * Removes any harvest report that is older than the specified time-to-live
 * (ttl)./*ww  w .j av a  2s  .  c o m*/
 * 
 * @param ttl
 *            The time-to-live value in milliseconds.
 */
private void cleanExpiredReports(String dataPath, Long ttl) {
    int depthLimit = 3;
    Date now = new Date();
    Date expirationDate = new Date(now.getTime() - ttl);
    boolean acceptOlder = true;
    File harvestReportDir = new File(dataPath);
    logger.info(String.format("Cleaning expired harvest report directories under: %s", dataPath));
    FileFilter ageFileFilter = FileFilterUtils.ageFileFilter(expirationDate, acceptOlder);
    HarvestReportCleaner harvestReportCleaner = new HarvestReportCleaner(ageFileFilter, depthLimit);

    try {
        List<File> cleanedFiles = harvestReportCleaner.clean(harvestReportDir);
        int dirCount = 0;
        for (File file : cleanedFiles) {
            String pathname = file.getPath();
            logger.info(String.format("  Cleaned directory: %s", pathname));
            dirCount++;
        }
        String nounVerb = (dirCount == 1) ? "directory was" : "directories were";
        logger.info(String.format("%d %s cleaned on this pass.", dirCount, nounVerb));
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:edu.lternet.pasta.portal.DesktopDataManager.java

/**
 * Removes any uploaded desktop data that is older than the specified time-to-live
 * (ttl).//from w  ww  . j  a  v  a 2  s .co  m
 * 
 * @param ttl
 *            The time-to-live value in milliseconds.
 */
private void cleanExpiredDataFiles(String dataPath, Long ttl) {
    int depthLimit = 3;
    Date now = new Date();
    Date expirationDate = new Date(now.getTime() - ttl);
    boolean acceptOlder = true;
    File desktopDataDir = new File(dataPath);
    logger.info(String.format("Cleaning expired desktop data directories under: %s", dataPath));
    FileFilter ageFileFilter = FileFilterUtils.ageFileFilter(expirationDate, acceptOlder);
    DesktopCleaner desktopCleaner = new DesktopCleaner(ageFileFilter, depthLimit);

    try {
        List<File> cleanedFiles = desktopCleaner.clean(desktopDataDir);
        int dirCount = 0;
        for (File file : cleanedFiles) {
            String pathname = file.getPath();
            logger.info(String.format("  Cleaned desktop data directory: %s", pathname));
            dirCount++;
        }
        String nounVerb = (dirCount == 1) ? "directory was" : "directories were";
        logger.info(String.format("%d %s cleaned on this pass.", dirCount, nounVerb));
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:edu.lternet.pasta.portal.DesktopCleanerServlet.java

/**
 * Removes any archive file that is older than the specified time-to-live
 * (ttl).//w ww  . ja v  a  2s  .c  o m
 * 
 * @param ttl
 *            The time-to-live value in milliseconds.
 */
public void cleanExpiredData(String dataPath, Long ttl) {
    int depthLimit = 2;
    Date now = new Date();
    Date expirationDate = new Date(now.getTime() - ttl);
    boolean acceptOlder = true;
    File desktopDataDir = new File(dataPath);
    logger.info(String.format("Cleaning expired desktop data directories under: %s", dataPath));
    FileFilter ageFileFilter = FileFilterUtils.ageFileFilter(expirationDate, acceptOlder);
    DesktopCleaner desktopCleaner = new DesktopCleaner(ageFileFilter, depthLimit);

    try {
        List<File> cleanedFiles = desktopCleaner.clean(desktopDataDir);
        int dirCount = 0;
        for (File file : cleanedFiles) {
            String pathname = file.getPath();
            logger.info(String.format("  Cleaned directory: %s", pathname));
            dirCount++;
        }
        String nounVerb = (dirCount == 1) ? "directory was" : "directories were";
        logger.info(String.format("%d %s cleaned on this pass.", dirCount, nounVerb));
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.dominion.salud.pedicom.negocio.tools.PDFService.java

/**
 * Demonio que realiza el borrado de pdf
 *//*from   w  w w .j  ava2 s.  co m*/
@Scheduled(cron = PEDICOMConstantes._TASK_PDF_DELETE)
public void deletePDF() {
    logger.info("Comienza el borrado automatico de pdf");
    File dir = new File(PEDICOMConstantes._HOME + File.separator + "reports" + File.separator);
    logger.debug("     Directorio de borrado en: " + dir.getPath());
    Collection<File> list = FileUtils.listFiles(dir,
            FileFilterUtils.ageFileFilter(DateUtils.addDays(new Date(), -1), true), null);
    for (File fil : list) {
        if (!StringUtils.equalsIgnoreCase(fil.getName(), "No_encontrado.pdf")) {
            FileUtils.deleteQuietly(fil);
        }
    }
    logger.info("Borrado completado");
}

From source file:kr.co.leem.system.FileSystemUtils.java

/**
 *  ./*  w  w w  .ja v a 2  s .  c o m*/
 *
 * @param srcDir ?  .
 * @param destDir   .
 * @param date .(yyyy-MM-dd)
 * @param acceptOlder ? ? ?.
 * @param preserveFileDate   .
 * @see FileUtils#copyDirectory(File, File, FileFilter, boolean)
 * @see FileFilterUtils#ageFileFilter(Date)
 * @see FileFilterUtils#or(IOFileFilter, IOFileFilter)
 */
public static void copyDirectory(final String srcDir, final String destDir, final Date cutoffDate,
        final boolean acceptOlder, final boolean preserveFileDate) {
    processIO(new IOCallback<Object>() {
        public Object doInProcessIO() throws IOException, NullPointerException {
            IOFileFilter ageFilter = FileFilterUtils.ageFileFilter(cutoffDate, acceptOlder);
            FileFilter filter = FileFilterUtils.or(DirectoryFileFilter.DIRECTORY, ageFilter);
            FileUtils.copyDirectory(new File(srcDir), new File(destDir), filter, preserveFileDate);
            return null;
        }
    });
}

From source file:kr.co.leem.system.FileSystemUtils.java

/**
 * ? ?? .//from w w  w  .  j  av a2s  .  c o m
 *
 * @param dirPath  .
 * @param date based . (yyyy-MM-dd)
 * @param acceptOlder ? ?  .
 * @return ? ?.
 * @see FileUtils#listFiles(File, IOFileFilter, IOFileFilter)
 * @see FileFilterUtils#ageFileFilter(date, boolean)
 */
public static File[] getFileList(final String dirPath, final Date date, final boolean acceptOlder) {
    return processIO(new IOCallback<File[]>() {
        public File[] doInProcessIO() throws IOException, NullPointerException {
            IOFileFilter ageFileFilter = FileFilterUtils.ageFileFilter(date, acceptOlder);

            Collection<File> files = FileUtils.listFiles(new File(dirPath), ageFileFilter,
                    DirectoryFileFilter.DIRECTORY);
            return FileUtils.convertFileCollectionToFileArray(files);
        }
    });
}

From source file:org.apache.jmeter.gui.action.Save.java

/**
 * <p>//from   w  ww .  j  a  va  2  s .c  o  m
 * Create a backup copy of the specified file whose name will be
 * <code>{baseName}-{version}.jmx</code><br>
 * Where :<br>
 * <code>{baseName}</code> is the name of the file to backup without its
 * <code>.jmx</code> extension. For a file named <code>testplan.jmx</code>
 * it would then be <code>testplan</code><br>
 * <code>{version}</code> is the version number automatically incremented
 * after the higher version number of pre-existing backup files. <br>
 * <br>
 * Example: <code>testplan-000028.jmx</code> <br>
 * <br>
 * If <code>jmeter.gui.action.save.backup_directory</code> is <b>not</b>
 * set, then backup files will be created in
 * <code>${JMETER_HOME}/backups</code>
 * </p>
 * <p>
 * Backup process is controlled by the following jmeter/user properties :<br>
 * <table border=1>
 * <tr>
 * <th align=left>Property</th>
 * <th align=left>Type/Value</th>
 * <th align=left>Description</th>
 * </tr>
 * <tr>
 * <td><code>jmeter.gui.action.save.backup_on_save</code></td>
 * <td><code>true|false</code></td>
 * <td>Enables / Disables backup</td>
 * </tr>
 * <tr>
 * <td><code>jmeter.gui.action.save.backup_directory</code></td>
 * <td><code>/path/to/backup/directory</code></td>
 * <td>Set the directory path where backups will be stored upon save. If not
 * set then backups will be created in <code>${JMETER_HOME}/backups</code><br>
 * If that directory does not exist, it will be created</td>
 * </tr>
 * <tr>
 * <td><code>jmeter.gui.action.save.keep_backup_max_hours</code></td>
 * <td><code>integer</code></td>
 * <td>Maximum number of hours to preserve backup files. Backup files whose
 * age exceeds that limit should be deleted and will be added to this method
 * returned list</td>
 * </tr>
 * <tr>
 * <td><code>jmeter.gui.action.save.keep_backup_max_count</code></td>
 * <td><code>integer</code></td>
 * <td>Max number of backup files to be preserved. Exceeding backup files
 * should be deleted and will be added to this method returned list. Only
 * the most recent files will be preserved.</td>
 * </tr>
 * </table>
 * </p>
 * 
 * @param fileToBackup
 *            The file to create a backup from
 * @return A list of expired backup files selected according to the above
 *         properties and that should be deleted after the save operation
 *         has performed successfully
 */
private List<File> createBackupFile(File fileToBackup) {
    if (!BACKUP_ENABLED || !fileToBackup.exists()) {
        return EMPTY_FILE_LIST;
    }
    char versionSeparator = '-'; //$NON-NLS-1$
    String baseName = fileToBackup.getName();
    // remove .jmx extension if any
    baseName = baseName.endsWith(JMX_FILE_EXTENSION)
            ? baseName.substring(0, baseName.length() - JMX_FILE_EXTENSION.length())
            : baseName;
    // get a file to the backup directory
    File backupDir = new File(BACKUP_DIRECTORY);
    backupDir.mkdirs();
    if (!backupDir.isDirectory()) {
        log.error(
                "Could not backup file ! Backup directory does not exist, is not a directory or could not be created ! <" //$NON-NLS-1$
                        + backupDir.getAbsolutePath() + ">"); //$NON-NLS-1$
    }

    // select files matching
    // {baseName}{versionSeparator}{version}{jmxExtension}
    // where {version} is a 6 digits number
    String backupPatternRegex = Pattern.quote(baseName + versionSeparator) + "([\\d]{6})" //$NON-NLS-1$
            + Pattern.quote(JMX_FILE_EXTENSION);
    Pattern backupPattern = Pattern.compile(backupPatternRegex);
    // create a file filter that select files matching a given regex pattern
    IOFileFilter patternFileFilter = new PrivatePatternFileFilter(backupPattern);
    // get all backup files in the backup directory
    List<File> backupFiles = new ArrayList<>(FileUtils.listFiles(backupDir, patternFileFilter, null));
    // find the highest version number among existing backup files (this
    // should be the more recent backup)
    int lastVersionNumber = 0;
    for (File backupFile : backupFiles) {
        Matcher matcher = backupPattern.matcher(backupFile.getName());
        if (matcher.find() && matcher.groupCount() > 0) {
            // parse version number from the backup file name
            // should never fail as it matches the regex
            int version = Integer.parseInt(matcher.group(1));
            lastVersionNumber = Math.max(lastVersionNumber, version);
        }
    }
    // find expired backup files
    List<File> expiredFiles = new ArrayList<>();
    if (BACKUP_MAX_HOURS > 0) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR_OF_DAY, -BACKUP_MAX_HOURS);
        long expiryDate = cal.getTime().getTime();
        // select expired files that should be deleted
        IOFileFilter expiredFileFilter = FileFilterUtils.ageFileFilter(expiryDate, true);
        expiredFiles.addAll(FileFilterUtils.filterList(expiredFileFilter, backupFiles));
    }
    // sort backups from by their last modified time
    Collections.sort(backupFiles, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            long diff = o1.lastModified() - o2.lastModified();
            // convert the long to an int in order to comply with the method
            // contract
            return diff < 0 ? -1 : diff > 0 ? 1 : 0;
        }
    });
    // backup name is of the form
    // {baseName}{versionSeparator}{version}{jmxExtension}
    String backupName = baseName + versionSeparator + BACKUP_VERSION_FORMATER.format(lastVersionNumber + 1)
            + JMX_FILE_EXTENSION;
    File backupFile = new File(backupDir, backupName);
    // create file backup
    try {
        FileUtils.copyFile(fileToBackup, backupFile);
    } catch (IOException e) {
        log.error("Failed to backup file :" + fileToBackup.getAbsolutePath(), e); //$NON-NLS-1$
        return EMPTY_FILE_LIST;
    }
    // add the fresh new backup file (list is still sorted here)
    backupFiles.add(backupFile);
    // unless max backups is not set, ensure that we don't keep more backups
    // than required
    if (BACKUP_MAX_COUNT > 0 && backupFiles.size() > BACKUP_MAX_COUNT) {
        // keep the most recent files in the limit of the specified max
        // count
        expiredFiles.addAll(backupFiles.subList(0, backupFiles.size() - BACKUP_MAX_COUNT));
    }
    return expiredFiles;
}

From source file:org.jvnet.hudson.plugins.thinbackup.backup.HudsonBackup.java

private IOFileFilter getFileAgeDiffFilter() {
    IOFileFilter result = FileFilterUtils.trueFileFilter();

    if (backupType == BackupType.DIFF) {
        result = FileFilterUtils.ageFileFilter(latestFullBackupDate, false);
    }//from  w ww  .j  a v a  2s .com

    return result;
}