Example usage for org.apache.commons.io.filefilter AgeFileFilter AgeFileFilter

List of usage examples for org.apache.commons.io.filefilter AgeFileFilter AgeFileFilter

Introduction

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

Prototype

public AgeFileFilter(File cutoffReference) 

Source Link

Document

Constructs a new age file filter for files older than (at or before) a certain File (whose last modification time will be used as reference).

Usage

From source file:com.polarion.pso.license.FetchUserLicenseTypeServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    ISecurityService securityService = (ISecurityService) PlatformContext.getPlatform()
            .lookupService(ISecurityService.class);
    ITrackerService trackerService = (ITrackerService) PlatformContext.getPlatform()
            .lookupService(ITrackerService.class);

    String userId = securityService.getCurrentUser();
    String userName = trackerService.getTrackerUser(userId).getName();

    long cutoff = System.currentTimeMillis() - (1000);
    File directory = new File("./logs/main");

    FileFilter wcFilter = new WildcardFileFilter("log4j-licensing-*.log");
    AgeFileFilter ageFilter = new AgeFileFilter(cutoff);
    FileFilter andFilter = new org.apache.commons.io.filefilter.AndFileFilter((IOFileFilter) ageFilter,
            (IOFileFilter) wcFilter);/* w  w  w.  ja v a  2 s .  c om*/

    Collection<File> matches = FileUtils.listFiles(directory, (IOFileFilter) andFilter, null);

    if (!matches.isEmpty()) {

        File myFile = matches.iterator().next();
        RandomAccessFile licFile = new RandomAccessFile(myFile, "r");

        // Read the last 1024 bytes
        Long fileLength = licFile.length();
        Long offSet = fileLength - 1024;
        byte[] bStr = new byte[1024];
        licFile.seek(offSet);
        licFile.read(bStr);
        licFile.close();

        String logString = new java.lang.String(bStr);

        String[] lineArray = logString.split("\n");

        String searchString = "INFO  PolarionLicensing  - User \'" + userId + "\' logged in";
        Boolean found = false;
        Integer size = lineArray.length - 1;
        String licType = directory.toString();

        for (int i = size; i >= 0; i--) {
            String line = lineArray[i];
            if (line.contains(searchString) && found == false) {
                found = true;
                i = -1;
                Integer startIndex = line.indexOf(searchString) + searchString.length() + 6;
                licType = line.substring(startIndex);
                licType = licType.replace("\r", "");
                licType = licType.trim();
            }
        }

        req.setAttribute("userId", userName);
        req.setAttribute("licType", licType);
    } else {
        req.setAttribute("userId", userName);
        req.setAttribute("licType", "Not Found");
    }

    getServletContext().getRequestDispatcher("/currentUserLicenseType.jsp").forward(req, resp);
}

From source file:fm.last.citrine.service.LogFileManagerImpl.java

@Override
public void deleteBefore(DateTime deleteBefore) throws IOException {
    log.debug("Deleting log files older than " + deleteBefore + " from " + baseLogFolder);
    File[] filesToDelete = baseLogFolder
            .listFiles((FileFilter) new AndFileFilter(logFileFilter, new AgeFileFilter(deleteBefore.toDate())));
    for (File fileToDelete : filesToDelete) {
        if (log.isDebugEnabled()) {
            log.debug("Deleting " + fileToDelete);
        }/*w ww.ja  v a  2 s  .  c o  m*/
        FileUtils.forceDelete(fileToDelete);
    }
}

From source file:com.ec2box.manage.action.UploadAndPushAction.java

@Action(value = "/admin/push", results = { @Result(name = "success", location = "/admin/upload_result.jsp") })
public String push() {

    Long userId = AuthUtil.getUserId(servletRequest.getSession());
    Long sessionId = AuthUtil.getSessionId(servletRequest.getSession());
    try {/*from w  w w.j a v  a  2  s. com*/

        //get next pending system
        pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
        if (pendingSystemStatus != null) {
            //get session for system
            SchSession session = null;
            for (Integer instanceId : SecureShellAction.getUserSchSessionMap().get(sessionId).getSchSessionMap()
                    .keySet()) {

                //if host system id matches pending system then upload
                if (pendingSystemStatus.getId().equals(SecureShellAction.getUserSchSessionMap().get(sessionId)
                        .getSchSessionMap().get(instanceId).getHostSystem().getId())) {
                    session = SecureShellAction.getUserSchSessionMap().get(sessionId).getSchSessionMap()
                            .get(instanceId);
                }
            }

            if (session != null) {

                //push upload to system
                currentSystemStatus = SSHUtil.pushUpload(pendingSystemStatus, session.getSession(),
                        UPLOAD_PATH + "/" + uploadFileName, pushDir + "/" + uploadFileName);

                //update system status
                SystemStatusDB.updateSystemStatus(currentSystemStatus, userId);

                pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
            }

        }

        //if push has finished to all servers then delete uploaded file
        if (pendingSystemStatus == null) {
            File delFile = new File(UPLOAD_PATH, uploadFileName);
            FileUtils.deleteQuietly(delFile);

            //delete all expired files in upload path
            File delDir = new File(UPLOAD_PATH);
            if (delDir.isDirectory()) {

                //set expire time to delete all files older than 48 hrs
                Calendar expireTime = Calendar.getInstance();
                expireTime.add(Calendar.HOUR, -48);

                Iterator<File> filesToDelete = FileUtils.iterateFiles(delDir,
                        new AgeFileFilter(expireTime.getTime()), TrueFileFilter.TRUE);
                while (filesToDelete.hasNext()) {
                    delFile = filesToDelete.next();
                    delFile.delete();
                }

            }

        }
        hostSystemList = SystemStatusDB.getAllSystemStatus(userId);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return SUCCESS;
}

From source file:com.keybox.manage.action.UploadAndPushAction.java

@Action(value = "/admin/push", results = { @Result(name = "success", location = "/admin/upload_result.jsp") })
public String push() {

    Long userId = AuthUtil.getUserId(servletRequest.getSession());
    Long sessionId = AuthUtil.getSessionId(servletRequest.getSession());
    try {//  www. j a  va 2  s  .c  o m

        //get next pending system
        pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
        if (pendingSystemStatus != null) {
            //get session for system
            SchSession session = null;
            for (Integer instanceId : SecureShellAction.getUserSchSessionMap().get(sessionId).getSchSessionMap()
                    .keySet()) {

                //if host system id matches pending system then upload
                if (pendingSystemStatus.getId().equals(SecureShellAction.getUserSchSessionMap().get(sessionId)
                        .getSchSessionMap().get(instanceId).getHostSystem().getId())) {
                    session = SecureShellAction.getUserSchSessionMap().get(sessionId).getSchSessionMap()
                            .get(instanceId);
                }
            }

            if (session != null) {

                //push upload to system
                currentSystemStatus = SSHUtil.pushUpload(pendingSystemStatus, session.getSession(),
                        UPLOAD_PATH + "/" + uploadFileName, pushDir + "/" + uploadFileName);

                //update system status
                SystemStatusDB.updateSystemStatus(currentSystemStatus, userId);

                pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
            }

        }

        //if push has finished to all servers then delete uploaded file
        if (pendingSystemStatus == null) {
            File delFile = new File(UPLOAD_PATH, uploadFileName);
            FileUtils.deleteQuietly(delFile);

            //delete all expired files in upload path
            File delDir = new File(UPLOAD_PATH);
            if (delDir.isDirectory()) {

                //set expire time to delete all files older than 48 hrs
                Calendar expireTime = Calendar.getInstance();
                expireTime.add(Calendar.HOUR, -48);

                Iterator<File> filesToDelete = FileUtils.iterateFiles(delDir,
                        new AgeFileFilter(expireTime.getTime()), TrueFileFilter.TRUE);
                while (filesToDelete.hasNext()) {
                    delFile = filesToDelete.next();
                    delFile.delete();
                }

            }

        }
        hostSystemList = SystemStatusDB.getAllSystemStatus(userId);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }

    return SUCCESS;
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToLaTeXConverter.java

/**
 * Create a temporary working directory and copy all template files there.
 *
 * @param templateDir/*  w w  w  .  j a v  a 2  s. c o  m*/
 *            the directory containing the original template files
 */
public void prepareDirectories(File templateDir) {

    LATEXDIR = HandleHome.getTrackplus_Home() + File.separator + "Reports" + File.separator + "LaTeX";
    latexTmpDir = LATEXDIR + File.separator + "tmp" + String.valueOf(new Date().getTime());
    errorFile = new File(latexTmpDir + "/errors.txt");
    debugTrace = new StringBuilder();

    File flatexDir = null;
    File flatexTmpDir = null;
    try {
        flatexDir = new File(LATEXDIR);
        flatexTmpDir = new File(latexTmpDir);
        if (!flatexDir.exists() || !flatexDir.isDirectory()) {
            Boolean success = flatexDir.mkdirs();
            if (!success) {
                LOGGER.error("Could not create LaTeX directory at " + LATEXDIR);
            }
        }
        if (!flatexTmpDir.exists() || !flatexTmpDir.isDirectory()) {
            Boolean success = flatexTmpDir.mkdirs();
            if (!success) {
                LOGGER.error("Could not create LaTeX out directory at " + latexTmpDir);
            }
        }
        Date thresholdDate = new Date(new Date().getTime() - 1000 * 60 * 3);

        Iterator<File> filesToDelete = FileUtils.iterateFilesAndDirs(flatexDir,
                new AgeFileFilter(thresholdDate), new AgeFileFilter(thresholdDate));

        while (filesToDelete.hasNext()) {
            File aFile = filesToDelete.next();
            if (aFile.isDirectory() && !aFile.getAbsolutePath().equals(flatexDir.getAbsolutePath())) {
                try {
                    FileUtils.deleteDirectory(aFile);
                } catch (Exception e) {
                    LOGGER.info("Problem deleting " + aFile.getAbsolutePath(), e);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }

    /*
     * Copy the template files including logos, styles, etc. to the
     * temporary working directory
     */
    try {
        FileUtils.copyDirectory(new File(templateDir.getAbsolutePath()), flatexTmpDir);
    } catch (IOException e) {
        LOGGER.error("Could not copy template files from " + templateDir.getAbsolutePath());
    }
}

From source file:org.eclipse.dirigible.repository.local.FileSystemRepository.java

private void cleanOlderFiles(File file) {
    Iterator<File> filesToBeDeleted = FileUtils.iterateFiles(file, new AgeFileFilter(thresholdDate), TRUE);
    while (filesToBeDeleted.hasNext()) {
        File toBeDeleted = filesToBeDeleted.next();
        toBeDeleted.delete();/* w w  w . j a va2s . c  om*/
    }
}

From source file:org.sonar.batch.bootstrap.TempDirectories.java

/**
 * This method is executed by picocontainer during shutdown.
 *///from  w  ww.  java 2s .c  o m
public void stop() {
    directoriesByKey.clear();

    // Deleting temp directory does not work on MS Windows and Sun JVM because URLClassLoader locks JARs and resources.
    // The workaround is that sonar deletes orphans itself.

    // older than AGE_BEFORE_DELETION to be sure that the current dir is deleted on mac and linux.
    rootDir.setLastModified(System.currentTimeMillis() - AGE_BEFORE_DELETION - 60 * 60 * 1000);

    File[] directoriesToDelete = rootDir.getParentFile()
            .listFiles((FileFilter) new AndFileFilter(
                    Arrays.asList(DirectoryFileFilter.DIRECTORY, new PrefixFileFilter(DIR_PREFIX),
                            new AgeFileFilter(System.currentTimeMillis() - AGE_BEFORE_DELETION))));
    for (File dir : directoriesToDelete) {
        LoggerFactory.getLogger(getClass()).debug("Delete temporary directory: " + dir);
        FileUtils.deleteQuietly(dir);
    }
}

From source file:org.sonar.runner.impl.TempCleaning.java

void clean() {
    logger.debug("Start temp cleaning...");
    long cutoff = System.currentTimeMillis() - ONE_DAY_IN_MILLISECONDS;
    Collection<File> files = FileUtils.listFiles(tempDir,
            new AndFileFilter(new PrefixFileFilter("sonar-runner-batch"), new AgeFileFilter(cutoff)), null);

    for (File file : files) {
        FileUtils.deleteQuietly(file);//  w w  w  .j  a v  a 2s .  co m
    }
    logger.debug("Temp cleaning done");
}

From source file:org.sonatype.nexus.tasklog.TaskLogCleanup.java

void cleanup() {
    String taskLogsHome = getTaskLogHome();

    if (taskLogsHome == null) {
        // we are forgiving if the task logs home is not defined. Just log a message with a call to action.
        log.warn(//  w w w . j  a v a 2 s  .  c o m
                "Unable to cleanup task log files. Please check that the 'tasklogfile' appender exists in logback.xml");
        return;
    }

    File logFilesHome = new File(taskLogsHome);

    log.info("Cleaning up log files in {} older than {} days", logFilesHome.getAbsolutePath(), numberOfDays);

    LocalDate now = LocalDate.now().minusDays(numberOfDays);
    Date thresholdDate = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());
    AgeFileFilter ageFileFilter = new AgeFileFilter(thresholdDate);
    Iterator<File> filesToDelete = iterateFiles(logFilesHome, ageFileFilter, ageFileFilter);
    filesToDelete.forEachRemaining(f -> {
        try {
            forceDelete(f);
            log.info("Removed task log file {}", f.toString());
        } catch (IOException e) { // NOSONAR
            log.error("Unable to delete task file {}. Message was {}.", f.toString(), e.getMessage());
        }
    });
}