Example usage for org.apache.commons.io FileUtils isFileNewer

List of usage examples for org.apache.commons.io FileUtils isFileNewer

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils isFileNewer.

Prototype

public static boolean isFileNewer(File file, long timeMillis) 

Source Link

Document

Tests if the specified File is newer than the specified time reference.

Usage

From source file:edu.cornell.med.icb.goby.modes.FastaToCompactMode.java

private void processOneFile(final int loopIndex, final int length, final String inputFilename,
        final Properties keyValueProps) throws IOException {
    String outputFilename;//from www. j  a  v a  2  s .  c o  m
    if (loopIndex == 0 && inputFilenames.length == 1 && StringUtils.isNotBlank(reqOutputFilename)) {
        outputFilename = reqOutputFilename;
    } else {
        outputFilename = stripFastxExtensions(inputFilename) + ".compact-reads";
        if (processPairs) {
            // remove _1 from the destination compact filename but only if the output filename
            // was generated automatically.
            outputFilename = pairOutputFilename(outputFilename);
        }
    }

    final File output = new File(outputFilename);
    final File readsFile = new File(inputFilename);
    if (!output.exists() || FileUtils.isFileNewer(readsFile, output) || output.length() == 0 || force) {
        System.out.println("Creating file " + outputFilename);
        convert(loopIndex, length, inputFilename, outputFilename, keyValueProps);
    } else {
        System.out.printf("Skipping file that already exists %s%n", outputFilename);
    }
}

From source file:net.sf.zekr.common.config.ApplicationConfig.java

@SuppressWarnings("unchecked")
private void extractViewProps() {
    ThemeData td;//from www  . ja  v  a  2s.c  o  m
    Reader reader;
    String def = props.getString("theme.default");
    logger.info("Loading theme .properties files.");

    String[] paths = { ApplicationPath.THEME_DIR, Naming.getThemeDir() };
    for (int pathIndex = 0; pathIndex < paths.length; pathIndex++) {
        File targetThemeDir = new File(paths[pathIndex]);
        if (!targetThemeDir.exists()) {
            continue;
        }

        logger.info("Loading theme files info from \"" + paths[pathIndex]);
        File[] targetThemes = targetThemeDir.listFiles();

        File origThemeDir = new File(paths[pathIndex]);
        File[] origThemes = origThemeDir.listFiles();
        for (int i = 0; i < origThemes.length; i++) {
            String targetThemeDesc = Naming.getThemePropsDir() + "/" + origThemes[i].getName() + ".properties";
            File origThemeDesc = new File(origThemes[i] + "/" + ApplicationPath.THEME_DESC);
            File targetThemeFile = new File(targetThemeDesc);

            if (!origThemeDesc.exists()) {
                logger.warn("\"" + origThemes[i] + "\" is not a standard theme! Will ignore it.");
                continue;
            }

            try {
                if (!targetThemeFile.exists() || FileUtils.isFileNewer(origThemeDesc, targetThemeFile)) {
                    logger.info("Copy theme " + origThemes[i].getName() + " to " + Naming.getThemePropsDir());
                    FileUtils.copyFile(origThemeDesc, targetThemeFile);
                }
                FileInputStream fis = new FileInputStream(targetThemeFile);
                reader = new InputStreamReader(fis, "UTF-8");
                PropertiesConfiguration pc = new PropertiesConfiguration();
                pc.load(reader);
                reader.close();
                fis.close();

                td = new ThemeData();
                td.props = new LinkedHashMap<String, String>(); // order is important for options table!
                for (Iterator<String> iter = pc.getKeys(); iter.hasNext();) {
                    String key = iter.next();
                    td.props.put(key, CollectionUtils.toString(pc.getList(key), ", "));
                }
                td.author = pc.getString("author");
                td.name = pc.getString("name");
                td.version = pc.getString("version");
                td.id = origThemes[i].getName();
                td.fileName = targetThemeFile.getName();
                td.baseDir = paths[pathIndex];
                td.props.remove("author");
                td.props.remove("name");
                td.props.remove("version");

                // extractTransProps must be called before it!
                if (getTranslation().getDefault() != null) {
                    td.process(getTranslation().getDefault().locale.getLanguage());
                } else {
                    td.process("en");
                }

                theme.add(td);

                if (td.id.equals(def)) {
                    theme.setCurrent(td);
                }
            } catch (Exception e) {
                logger.warn("Can not load theme \"" + targetThemes[i].getName()
                        + "\", because of the following exception:");
                logger.log(e);
            }
        }
    }
    if (theme.getCurrent() == null) {
        logger.doFatal(new ZekrBaseException("Could not find default theme: " + def));
    }
}

From source file:org.apache.maven.plugins.jacorb.JacorbPlugin.java

public void execute() throws MojoExecutionException {
    File timestampFile = new File(getTstamp());
    File schemaFile = new File(getSchema());
    if ((!timestampFile.exists())
            || (timestampFile.exists() && !FileUtils.isFileNewer(timestampFile, schemaFile))) {
        try {/* www .j a  v  a 2s  .co  m*/
            File tstampDir = new File(getTstampDirectory());
            FileUtils.forceMkdir(tstampDir);
            FileUtils.touch(timestampFile);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage());
        }
        ArrayList a = new ArrayList();
        if (!schemaHasNoValue()) {
            a.add("-i" + getSchema());
        }
        a.add("-f");
        if (!packagingHasNoValue()) {
            a.add("-package" + getPackaging());
        }
        if (!typesHasNoValue()) {
            a.add("-types" + getTypes());
        }
        if (marshal) {
            a.add("-nomarshall");
        }
        if (!destHasNoValue()) {
            a.add("-dest" + getDest());
        }
        //  SourceGenerator sourceGenerator = new SourceGenerator();
        String args[] = new String[a.size()];
        for (int i = 0; i < a.size(); i++) {
            args[i] = (String) a.get(i);
        }
        //  sourceGenerator.main( args );
    } else {
        getLog().info("Schema is up to date. Did not generate source files. Delete " + getTstamp()
                + " if you want to force source generation.");
    }
}

From source file:org.artifactory.backup.BackupServiceImpl.java

@Override
public void cleanupOldBackups(Date now, String backupKey) {
    BackupDescriptor descriptor = getBackup(backupKey);
    if (descriptor == null) {
        return;//from   w  w  w . j  a  v  a 2 s  .c  om
    }
    int retentionPeriodHours = descriptor.getRetentionPeriodHours();
    //No action if retention is 0 (or less)
    if (retentionPeriodHours <= 0) {
        return;
    }
    File backupDir = getBackupDir(descriptor);
    File[] children = backupDir.listFiles();
    if (children == null || CollectionUtils.isNullOrEmpty(children)) {
        log.debug("No old backup files to remove.");
        return;
    }

    //Calculate last valid time
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(now);
    calendar.add(Calendar.HOUR, -retentionPeriodHours);
    Date validFrom = calendar.getTime();
    log.debug("Removing backups older than {}.", validFrom);
    //Delete anything not newer than the last valid time
    for (File child : children) {
        if (!FileUtils.isFileNewer(child, validFrom)) {
            try {
                log.debug("Removing old backup file '{}'.", child.getPath());
                FileUtils.forceDelete(child);
            } catch (IOException e) {
                log.warn("Failed to remove old backup file or folder '" + child.getPath() + "'.", e);
            }
        } else {
            log.debug("Skipping new backup file '{}'.", child.getPath());
        }
    }
}

From source file:org.codehaus.mojo.latex.LaTeXMojo.java

private boolean requiresBuilding(File dir, File pdfFile) throws IOException {
    Collection texFiles = FileUtils.listFiles(dir, new String[] { "tex", "bib" }, true);
    getLog().info(texFiles.toString());/*w ww.ja  v  a2s  .c o m*/
    if (pdfFile.exists()) {
        boolean upToDate = true;
        Iterator it = texFiles.iterator();
        while (it.hasNext() && upToDate) {
            File file = (File) it.next();
            if (FileUtils.isFileNewer(file, pdfFile)) {
                if (getLog().isInfoEnabled()) {
                    getLog().info("Changes detected on " + file.getAbsolutePath());
                }
                return true;
            }
            if (getLog().isInfoEnabled()) {
                getLog().info("No change detected on " + file.getAbsolutePath());
            }
        }
        if (getLog().isInfoEnabled()) {
            getLog().info("Skipping: no LaTeX changes detected in " + dir.getCanonicalPath());
        }
        return false;
    } else {
        return true;
    }
}

From source file:org.eclipse.smarthome.model.core.internal.folder.FolderObserver.java

private void checkFolder(String foldername) {
    File folder = getFolder(foldername);
    if (!folder.exists()) {
        return;// ww w. j a v a 2s.co  m
    }
    String[] extensions = folderFileExtMap.get(foldername);

    // check current files and add or refresh them accordingly
    Set<String> currentFileNames = new HashSet<String>();
    for (File file : folder.listFiles()) {
        if (file.isDirectory())
            continue;
        if (!file.getName().contains("."))
            continue;
        if (file.getName().startsWith("."))
            continue;

        // if there is an extension filter defined, continue if the file has a different extension
        String fileExt = getExtension(file.getName());
        if (extensions != null && extensions.length > 0 && !ArrayUtils.contains(extensions, fileExt))
            continue;

        currentFileNames.add(file.getName());
        Long timeLastCheck = lastCheckedMap.get(file.getName());
        if (timeLastCheck == null)
            timeLastCheck = 0L;
        if (FileUtils.isFileNewer(file, timeLastCheck)) {
            if (modelRepo != null) {
                try {
                    if (modelRepo.addOrRefreshModel(file.getName(), FileUtils.openInputStream(file))) {
                        lastCheckedMap.put(file.getName(), new Date().getTime());
                    }
                } catch (IOException e) {
                    logger.warn("Cannot open file '" + file.getAbsolutePath() + "' for reading.", e);
                }
            }
        }
    }

    // check for files that have been deleted meanwhile
    if (lastFileNames.get(foldername) != null) {
        ;
        for (String fileName : lastFileNames.get(foldername)) {
            if (!currentFileNames.contains(fileName)) {
                logger.info("File '{}' has been deleted", fileName);
                if (modelRepo != null) {
                    modelRepo.removeModel(fileName);
                }
            }
        }
    }
    lastFileNames.put(foldername, currentFileNames);
}

From source file:org.gdms.maven.sql.AbstractGenerateSql.java

protected void doExecute(File sqlScriptsDirectory, File outputDirectory)
        throws MojoExecutionException, MojoFailureException {
    MavenLogAppender.startPluginLog(this);

    try {//from ww w  . j av  a  2 s  . com
        final String inputPath = sqlScriptsDirectory.getAbsolutePath();

        getLog().info(String.format("Processing folder %s", inputPath));
        if (!sqlScriptsDirectory.exists()) {
            // nothing to do, no valid input directory
            getLog().warn("Directory does not exist! Nothing to do.");
            return;
        }

        Collection<File> fil = FileUtils.listFiles(sqlScriptsDirectory, new String[] { "sql" }, true);

        int size = fil.size();
        if (size == 0) {
            // nothing to do, no files...
            getLog().warn("Found 0 sql files! Nothing to do.");
        } else {
            // be sure the output dir exists
            if (!outputDirectory.exists()) {
                outputDirectory.mkdirs();
            }

            List<File> changedFiles = new ArrayList<File>();

            for (File ff : fil) {
                File tff = getTargetFile(inputPath, outputDirectory, ff);
                if (!tff.exists() || FileUtils.isFileNewer(ff, tff)) {
                    changedFiles.add(ff);
                }
            }

            if (changedFiles.isEmpty()) {
                getLog().info("Nothing to compile - all compiled scripts are up to date");
            } else if (changedFiles.size() != size) {
                getLog().info(String.format("Compiling %d changed sql files out of %d to %s",
                        changedFiles.size(), size, outputDirectory.getAbsolutePath()));
            } else {
                getLog().info(
                        String.format("Compiling %d sql files to %s", size, outputDirectory.getAbsolutePath()));
            }

            Properties props = DataSourceFactory.getDefaultProperties();

            if (engineProperties != null) {
                props = new Properties(props);
                for (String k : engineProperties.stringPropertyNames()) {
                    props.setProperty(k, engineProperties.getProperty(k));
                }
            }

            if (getLog().isDebugEnabled()) {
                // display properties
                Log log = getLog();
                log.debug("Engine invocation properties:");
                if (engineProperties == null) {
                    log.debug("No custom properties. Using Default:");
                } else {
                    log.debug("Custom properties:");
                    printProperties(engineProperties);
                    log.debug("Merged with default properties:");
                }
                printProperties(props);
            }

            int errors = 0;

            for (File ff : changedFiles) {
                if (getLog().isDebugEnabled()) {
                    getLog().debug("Parsing script " + ff.getAbsolutePath());
                }
                SQLScript s;
                try {
                    s = Engine.parseScript(ff, props);
                } catch (Exception e) {
                    if (errors == 0) {
                        getLog().info("---------------------------------------");
                        getLog().error("COMPILATION ERROR :");
                        getLog().info("---------------------------------------");
                    }
                    errors++;
                    getLog().error(e.getLocalizedMessage());
                    getLog().info(String.format("location:  %s", ff.getAbsolutePath()));
                    if (e instanceof ParseException) {
                        ParseException p = (ParseException) e;
                        getLog().info(p.getLocation().prettyPrint());
                    }
                    getLog().debug(e);
                    getLog().info("---------------------------------------");
                    continue;
                }
                File targetFile = getTargetFile(inputPath, outputDirectory, ff);

                // create parent directory. Might not exist
                targetFile.getParentFile().mkdirs();

                // delete existing compiled script
                if (targetFile.exists()) {
                    targetFile.delete();
                }

                try {
                    s.save(new FileOutputStream(targetFile));
                } catch (IOException ex) {
                    // this is not good, let's abort
                    throw new MojoExecutionException(
                            String.format("Error while saving to '%s'", targetFile.getAbsolutePath()), ex);
                }
            }

            if (errors != 0) {
                getLog().info(String.format("%d errors", errors));
                String errorStr;
                if (errors == 1) {
                    errorStr = "There was 1 SQL build error!";
                } else {
                    errorStr = String.format("There were %d SQL build errors!", errors);
                }
                throw new MojoFailureException(errorStr + " See above for more details.");
            }
        }
    } finally {
        MavenLogAppender.endPluginLog(this);
    }
}

From source file:org.mitre.mpf.mvc.util.tailer.MpfLogTailer.java

/**
 * Follows changes in the file, calling the MpfLogTailerListener's handle method for each new line.
 *
 * @param maxLines The maximum number of lines to read
 * @return The number of lines read//from  w w  w  .j  a  va  2 s .co  m
 */
public int readLines(int maxLines) {
    int numLines = 0;

    try {
        // Open the file
        if (reader == null) {
            try {
                reader = new RandomAccessFile(file, RAF_MODE);
            } catch (FileNotFoundException e) {
                listener.fileNotFound();
            }

            if (reader != null) {
                if (lastChecked == -1) {
                    lastChecked = System.currentTimeMillis();
                }
                if (position == -1) {
                    position = end ? file.length() : 0;
                }
                reader.seek(position);
            }
        }

        // Get new content

        boolean newer = FileUtils.isFileNewer(file, lastChecked); // IO-279, must be done first

        // Check the file length to see if it was rotated
        long length = file.length();

        if (length < position) {

            // File was rotated
            listener.fileRotated();

            // Reopen the reader after rotation
            try {
                // Ensure that the old file is closed iff we re-open it successfully
                RandomAccessFile save = reader;
                reader = new RandomAccessFile(file, RAF_MODE);
                position = 0;
                // close old file explicitly rather than relying on GC picking up previous RAF
                IOUtils.closeQuietly(save);
            } catch (FileNotFoundException e) {
                // in this case we continue to use the previous reader and position values
                listener.fileNotFound();
            }

            return readLines(maxLines); // start over with rotated file

        } else {

            // File was not rotated

            // See if the file needs to be read again
            if (length > position) {

                // The file has more content than it did last time
                numLines = readLines(reader, maxLines);
                lastChecked = System.currentTimeMillis();

            } else if (newer) {

                /*
                 * This can happen if the file is truncated or overwritten with the exact same length of
                 * information. In cases like this, the file position needs to be reset
                 */
                position = 0;
                reader.seek(position); // cannot be null here

                // Now we can read new lines
                numLines = readLines(reader, maxLines);
                lastChecked = System.currentTimeMillis();
            }
        }
        if (reOpen) {
            IOUtils.closeQuietly(reader);
        }
        if (reOpen) {
            reader = new RandomAccessFile(file, RAF_MODE);
            reader.seek(position);
        }

    } catch (Exception e) {
        listener.handle(e);
    }

    return numLines;
}

From source file:org.openhab.model.core.internal.folder.FolderObserver.java

private void checkFolder(String foldername) {
    File folder = getFolder(foldername);
    if (!folder.exists()) {
        return;//from w w w.  j a  v  a  2s  .  co m
    }
    String[] extensions = folderFileExtMap.get(foldername);

    // check current files and add or refresh them accordingly
    Set<String> currentFileNames = new HashSet<String>();
    for (File file : folder.listFiles()) {
        if (file.isDirectory())
            continue;
        if (!file.getName().contains("."))
            continue;
        if (file.getName().startsWith("."))
            continue;

        // if there is an extension filter defined, continue if the file has a different extension
        String fileExt = getExtension(file.getName());
        if (extensions != null && extensions.length > 0 && !ArrayUtils.contains(extensions, fileExt))
            continue;

        currentFileNames.add(file.getName());
        Long timeLastCheck = lastCheckedMap.get(file.getName());
        if (timeLastCheck == null)
            timeLastCheck = 0L;
        if (FileUtils.isFileNewer(file, timeLastCheck)) {
            if (modelRepo != null) {
                try {
                    if (modelRepo.addOrRefreshModel(file.getName(), FileUtils.openInputStream(file))) {
                        lastCheckedMap.put(file.getName(), new Date().getTime());
                    }
                } catch (IOException e) {
                    logger.warn("Cannot open file '" + file.getAbsolutePath() + "' for reading.", e);
                }
            }
        }
    }

    // check for files that have been deleted meanwhile
    if (lastFileNames.get(foldername) != null) {
        for (String fileName : lastFileNames.get(foldername)) {
            if (!currentFileNames.contains(fileName)) {
                logger.info("File '{}' has been deleted", fileName);
                if (modelRepo != null) {
                    modelRepo.removeModel(fileName);
                    lastCheckedMap.remove(fileName);
                }
            }
        }
    }
    lastFileNames.put(foldername, currentFileNames);
}

From source file:org.openmrs.module.clinicalsummary.io.DownloadSummariesTask.java

private void processStream(ZipOutputStream zipOutputStream, String basePath, File currentFile, Date cutOffDate)
        throws Exception {
    byte data[] = new byte[TaskConstants.BUFFER_SIZE];
    if (currentFile.isDirectory()) {
        FileFilter fileFilter = new WildcardFileFilter(
                StringUtils.join(Arrays.asList("*", Evaluator.FILE_TYPE_XML), "."));
        File[] files = currentFile.listFiles(fileFilter);
        for (File file : files) {
            processStream(zipOutputStream, basePath, file, cutOffDate);
        }/*  www . j  a  v  a  2  s .c  o m*/
    } else {
        if (cutOffDate == null || FileUtils.isFileNewer(currentFile, cutOffDate)) {
            processedFilename = currentFile.getName();
            // add the zip entry
            String zipEntryName = StringUtils.remove(currentFile.getAbsolutePath(), basePath);
            ZipEntry entry = new ZipEntry(zipEntryName);
            zipOutputStream.putNextEntry(entry);
            // write the entry
            int count;
            InputStream inStream = new BufferedInputStream(new FileInputStream(currentFile));
            while ((count = inStream.read(data, 0, TaskConstants.BUFFER_SIZE)) != -1) {
                zipOutputStream.write(data, 0, count);
            }
            inStream.close();
        }
    }
}