Example usage for org.apache.commons.io.comparator LastModifiedFileComparator LASTMODIFIED_COMPARATOR

List of usage examples for org.apache.commons.io.comparator LastModifiedFileComparator LASTMODIFIED_COMPARATOR

Introduction

In this page you can find the example usage for org.apache.commons.io.comparator LastModifiedFileComparator LASTMODIFIED_COMPARATOR.

Prototype

Comparator LASTMODIFIED_COMPARATOR

To view the source code for org.apache.commons.io.comparator LastModifiedFileComparator LASTMODIFIED_COMPARATOR.

Click Source Link

Document

Last modified comparator instance

Usage

From source file:Main.java

public static void main(String[] args) {
    File dir = new File("c:\\");
    File[] files = dir.listFiles();

    Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
    for (int i = 0; i < files.length; i++) {
        File file = files[i];/*from ww  w  .  j a va  2 s  .co m*/
        System.out.printf("File %s - %2$tm %2$te,%2$tY%n= ", file.getName(), file.lastModified());
    }

    Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        System.out.printf("File %s - %2$tm %2$te,%2$tY%n= ", file.getName(), file.lastModified());
    }
}

From source file:com.uksf.mf.core.utility.LogHandler.java

/**
 * First checks if there are already 10 log files, if so, deletes the oldest, then creates the new log file
 *///from   w ww .  j av a2  s.  c o  m
private void createLogFile() {
    if (LOG_CREATED)
        return;
    LOGS.mkdir();
    File[] logs = LOGS.listFiles((FileFilter) FileFileFilter.FILE);
    assert logs != null;
    if (logs.length > 1)
        Arrays.sort(logs, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
    if (logs.length > 9) {
        if (!logs[0].delete()) {
            System.out.println("'" + logs[0].getAbsolutePath() + logs[0].getName() + "' was not deleted.");
        }
    }
    logFile = new File(LOGS + "\\MF__" + DATEFORMAT.format(DATE) + ".log");
    try {
        if (!logFile.createNewFile()) {
            throw new IOException("Log file not created at '" + logFile.getAbsolutePath() + "'");
        }
    } catch (IOException e) {
        error(e);
    }
    System.out.println(logFile.getAbsolutePath());
    LOG_CREATED = true;
    logSeverity(INFO, "Log Created");
}

From source file:com.iana.dver.pdf.scrapper.DVERScrapperTask.java

public void readAndParseDVER() throws WrongConfigurationException, IOException {
    if (scanDir == null && archiveDir == null && maxFiles == null && xmlDir == null) {
        log.info("Wrong configuration used");
        throw new WrongConfigurationException("Some configuration is missing in job");
    }//w w  w  .  j a v a  2  s . co  m

    // Fetching the files up to 50
    DirectoryScanner scanner = new HeadDirectoryScanner(Integer.parseInt(maxFiles.trim()));
    File dverScanDirectory = new File(scanDir);
    if (dverScanDirectory.isDirectory()) {
        List<File> files = scanner.listFiles(dverScanDirectory);
        // Sorting the list as per created time.
        Collections.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
        // Iterate the files list
        for (File file : files) {
            if (file.isFile()) {
                PDFTextStripperByArea textStripper = readDVER(file);
                generateDverXML(FilenameUtils.getBaseName(file.getName()), textStripper);
            }
        }
    } else {
        throw new WrongConfigurationException("The Path to look for DVER is not a directory");
    }
}

From source file:com.commander4j.thread.InboundMessageCollectionThread.java

private LinkedList<String> getInputFilename(String inputPath) {
    LinkedList<String> Result = new LinkedList<String>();
    File dir;/*from w ww  .  j a va 2  s  . c o  m*/

    dir = new File(inputPath);

    chld = dir.listFiles((FileFilter) FileFileFilter.FILE);

    if (chld == null) {
        logger.debug("Specified directory does not exist or is not a directory. [" + inputPath + "]");
    } else {
        Arrays.sort(chld, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
        for (int i = 0; i < chld.length; i++) {
            fileName = chld[i].getName();
            if (fileName.toLowerCase().endsWith(".xml")) {
                Result.addLast(fileName);
            }
        }
    }

    return Result;
}

From source file:com.castis.xylophone.adsmadapter.filePolling.MapperListPolling.java

public boolean loadFileList() {

    for (int i = 0; i < oneCycleTryCount; i++) {
        long start = System.currentTimeMillis();

        List<File> fileList = getFileListByCondition("mapper", null,
                LastModifiedFileComparator.LASTMODIFIED_COMPARATOR, true);

        if (fileList == null || fileList.isEmpty())
            return true;

        ADSMSchedulerLogDTO schedulerLog = null;
        File selectFile = fileList.get(0);
        if (selectFile == null)
            continue;

        try {//from  w  w  w .  ja va  2  s  .  c  o m
            if (integrityFileSize(selectFile) == false) {
                moveIgnoreFile(selectFile, InputDataType.INVENTORY_DAT, "File size is smaller than limit size");
                continue;
            }

            log.info("MapperListPolling start(" + selectFile.getAbsolutePath() + ")");

            //? 
            ParsedMapperData parsedMapperData = (ParsedMapperData) mapperParsing.parseList(selectFile);

            //DB   
            String siteMessage = FilePolling.PARAM_SITE_PREFIX + ":" + parsedMapperData.getMappingIdDomain();
            String jobName = getJobName(parsedMapperData.getMapperAxisType()).name();
            String param = "fileName:" + selectFile.getName() + "/" + siteMessage + "/" + MAPPER_START_DATE
                    + ":" + parsedMapperData.getMapperStartDateStr();

            int previousSuccessSchedulerLogId = 0;
            // ? ?
            ADSMSchedulerLogDTO previousSuccessLog = tambourineConnector
                    .getLatestADSMSchedulerLogwithMessage(jobName, siteMessage);
            if (previousSuccessLog != null) {
                String lastestSuccessStart = (String) previousSuccessLog.getParamValue(MAPPER_START_DATE);
                Date lastestSuccessStartDate = CiDateUtil.convertDate(lastestSuccessStart, "yyyy-MM-dd");
                //2-2.   ?? ?  dat?
                if (lastestSuccessStartDate != null && lastestSuccessStartDate.getTime() > start) {
                    if (parsedMapperData.getMapperStartDateStr().compareTo(lastestSuccessStart) > 0) {
                        //  ?.
                        moveIgnoreFile(selectFile, InputDataType.INVENTORY_DAT,
                                "License start date after [" + lastestSuccessStart + "] can not be processed.");
                        continue;
                    }
                }
                previousSuccessSchedulerLogId = previousSuccessLog.getId();
            }

            schedulerLog = tambourineConnector.startLog(jobName, param, siteMessage);
            if (schedulerLog == null)
                return false;

            /*?*/
            int mergeListSize = mergeMapperList(parsedMapperData, previousSuccessSchedulerLogId);

            //DB    
            schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.SUCCESS);

            //?  
            moveProcessedFile(selectFile, true);
            ResultFileUtil.writeResultFile(selectFile.getName(),
                    "File processing Success. [size:" + mergeListSize + "]",
                    FileResultCode.RESULT_OK.getValue(), fileResDirectory, InputDataType.INVENTORY_DAT);

            myProcessStatus.addTransactionCount();
        } catch (UnreadableFileException e) {
            log.info(e.getMessage());
            break;
        } catch (WrongFileNameException e) {
            log.warn(e.getMessage());
            moveProcessedFile(selectFile, false);
            ResultFileUtil.writeResultFile(selectFile.getName(), e.getMessage(),
                    FileResultCode.RESULT_FAIL.getValue(), fileResDirectory, InputDataType.INVENTORY_DAT);
            myProcessStatus.addErrorTransactionCount();
            return false;
        } catch (Exception e) {
            String errorLog = "Mapper Info File(" + selectFile.getName() + ")processing fail.";
            TheLogger.getWriter().error(errorLog);
            log.error(errorLog, e);
            if (schedulerLog != null) {
                schedulerLog.setMessage(e.getMessage());
                schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.FAIL);
                StackTraceElement[] stackTraces = e.getStackTrace();
                if (stackTraces.length > 0) {
                    String failProcess = stackTraces[0].getClassName() + " - " + stackTraces[0].getMethodName()
                            + "(" + stackTraces[0].getLineNumber() + ")";
                    schedulerLog.setFailProcess(failProcess);
                }
            }

            moveProcessedFile(selectFile, false);
            ResultFileUtil.writeResultFile(selectFile.getName(), "File processing fail.[" + e + "]",
                    FileResultCode.RESULT_FAIL.getValue(), fileResDirectory, InputDataType.INVENTORY_DAT);
            myProcessStatus.addErrorTransactionCount();
        }

        tambourineConnector.endLog(schedulerLog);

        long end = System.currentTimeMillis();
        log.info("MapperListPolling end - T(" + (end - start) + ")");
    }

    return true;
}

From source file:info.servertools.core.util.FileUtils.java

/**
 * Retrieve the oldest file in a directory
 *
 * @param directory/*from   w w  w  .j a  va 2 s .  c  o m*/
 *         the directory to check
 *
 * @return the oldest file
 */
public static File getOldestFile(File directory) {

    File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE);

    Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);

    return files.length > 0 ? files[0] : null;
}

From source file:$.LogParser.java

public File[] getLogFiles(final DateTime date) throws FileNotFoundException {
        File logFolder = new File(logFolderPath);
        if (!logFolder.exists() || !logFolder.canRead()) {
            throw new FileNotFoundException("there is no readable log folder - " + logFolderPath);
        }/*  w  w w. j  av  a 2  s  .c  o  m*/

        final String logDateFormatted = FILE_DATE_FORMAT.print(date);
        final long dateMillis = date.getMillis();

        File[] files = logFolder.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                String name = file.getName();
                return name.endsWith(FILE_EXTENSION) // it's a log file
                        && name.contains(logDateFormatted) // it contains the date in the name
                        && file.lastModified() >= dateMillis; // and it's not older than the search date
            }
        });

        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);

        if (files.length == 0) {
            Log.debug("No log files ending with {}, containing {}, modified after {}, at {}", FILE_EXTENSION,
                    logDateFormatted, date, logFolderPath);
        } else {
            Log.debug("Found log files for {}: {}", date, files);
        }

        return files;
    }

From source file:com.castis.xylophone.adsmadapter.filePolling.InventoryDataListPolling.java

public boolean loadFileList(String targetDir, String filter) {

    for (int i = 0; i < oneCycleTryCount; i++) {
        long start = System.currentTimeMillis();

        fileDirectory = targetDir;/*from   w w  w. j a va2 s  .  c o m*/

        //? ?  
        List<File> fileList = getFileListByCondition(filter, null,
                LastModifiedFileComparator.LASTMODIFIED_COMPARATOR, true);
        if (fileList != null && !fileList.isEmpty()) {
            try {
                process(fileList.get(0), start);
            } catch (UnreadableFileException e) {
                break;
            }
        } else
            break;

    }

    return true;
}

From source file:net.sf.jvifm.control.ListFileCommand.java

@SuppressWarnings("unchecked")
public void execute() throws Exception {

    if (pwd == null)
        return;//from  ww  w.  j  a  v a2 s  . c  o m
    if (pwd.length() == 2 && pwd.endsWith(":")) {
        pwd = pwd + File.separator;
    }
    File currentDir = new File(pwd);

    String[] filters = cmdLine.getArgs();
    OrFileFilter orFileFilter = new OrFileFilter();

    if (filters == null || filters.length < 1) {
        orFileFilter.addFileFilter(new WildcardFileFilter("*"));
    } else {
        for (int i = 0; i < filters.length; i++) {
            orFileFilter.addFileFilter(new WildcardFileFilter(filters[i]));
        }
    }

    if (cmdLine.hasOption("R")) {
        // FileFinder finder = new FileFinder();
        // subFiles = finder.find(currentDir, orFileFilter);
    } else {
        subFiles = currentDir.listFiles((FilenameFilter) orFileFilter);
    }

    if (cmdLine.hasOption("r")) {
        if (cmdLine.hasOption("t")) {
            Arrays.sort(subFiles, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
        } else if (cmdLine.hasOption("S")) {
            Arrays.sort(subFiles, SizeFileComparator.SIZE_REVERSE);
        } else if (cmdLine.hasOption("X")) {
            Arrays.sort(subFiles, ExtensionFileComparator.EXTENSION_REVERSE);
        } else {
            Arrays.sort(subFiles, FileComprator.getFileComprator("name", true));
        }
    } else {
        if (cmdLine.hasOption("t")) {
            Arrays.sort(subFiles, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
        } else if (cmdLine.hasOption("S")) {
            Arrays.sort(subFiles, SizeFileComparator.SIZE_COMPARATOR);
        } else if (cmdLine.hasOption("X")) {
            Arrays.sort(subFiles, ExtensionFileComparator.EXTENSION_COMPARATOR);
        } else {
            Arrays.sort(subFiles, FileComprator.getFileComprator("name", false));
        }
    }

    listSubFileInPanel(subFiles);

}

From source file:$.MessageLogParser.java

/**
     * Gets lines from the log file which corresponds with specified correlation ID.
     */*from  w ww.j a  v  a2s . co m*/
     * @param correlationId the correlation ID
     * @param logDate which date to search log files for
     * @return log lines
     * @throws IOException when error occurred during file reading
     */
    List<String> getLogLines(String correlationId, Date logDate) throws IOException {
        File logFolder = new File(logFolderPath);
        if (!logFolder.exists() || !logFolder.canRead()) {
            throw new FileNotFoundException("there is no readable log folder - " + logFolderPath);
        }

        final String logDateFormatted = fileFormat.format(logDate);

        // filter log files for current date
        IOFileFilter nameFilter = new IOFileFilter() {
            @Override
            public boolean accept(File file) {
                return logNameFilter.accept(file) && (StringUtils.contains(file.getName(), logDateFormatted)
                        || file.getName().endsWith(BASE_FILE_EXTENSION));
            }

            @Override
            public boolean accept(File dir, String name) {
                return StringUtils.contains(name, logDateFormatted) || name.endsWith(BASE_FILE_EXTENSION);

            }
        };

        List<File> logFiles = new ArrayList<File>(FileUtils.listFiles(logFolder, nameFilter, null));
        Collections.sort(logFiles, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);

        // go through all log files
        List<String> logLines = new ArrayList<String>();
        for (File logFile : logFiles) {
            logLines.addAll(getLogLines(logFile, correlationId));
        }

        return logLines;
    }