Example usage for java.io File lastModified

List of usage examples for java.io File lastModified

Introduction

In this page you can find the example usage for java.io File lastModified.

Prototype

public long lastModified() 

Source Link

Document

Returns the time that the file denoted by this abstract pathname was last modified.

Usage

From source file:com.xpn.xwiki.util.Util.java

public static Date getFileLastModificationDate(String path) {
    try {//from  w  ww  .  jav  a 2  s  .  c  o m
        File f = new File(path);

        return (new Date(f.lastModified()));
    } catch (Exception ex) {
        return new Date();
    }
}

From source file:de.ppi.selenium.browser.DefaultWebDriverFactory.java

/**
 * This method can be called to remove specific folders or set how long you
 * want to keep the temp information./*from   w  w w  .jav a2  s  .  co m*/
 *
 * @param folder which temp folder you want to remove
 * @param folderTemplates the templates of these temp folders
 * @param numberOfDaysToKeepTempFolders how long you want to keep the temp
 *            information
 */
private final static void removeFolders(String folder, List<String> folderTemplates,
        int numberOfDaysToKeepTempFolders) {
    long dateToRemoveFiledAfter = (new Date()).getTime()
            - (numberOfDaysToKeepTempFolders * MILLISECONDS_IN_DAY);

    File tempFolder = new File(folder);
    for (File currentFile : tempFolder.listFiles()) {
        if (currentFile.isDirectory()) {
            for (String folderTemplate : folderTemplates) {
                if (currentFile.getName().contains(folderTemplate)
                        && (currentFile.lastModified() < dateToRemoveFiledAfter)) {
                    try {
                        currentFile.delete();
                        FileUtils.deleteDirectory(currentFile);
                        log.debug("Folder '" + currentFile.getName() + "' deleted...");
                    } catch (Exception e) {
                        log.fatal("Error deleting folder '" + currentFile.getName() + "'");
                    }
                }
            }
        }
    }
}

From source file:com.wipro.ats.bdre.filemon.FileScan.java

public static void scanAndAddToQueue() {
    try {/*from   ww w  .  java  2s . co  m*/
        String scanDir = FileMonRunnableMain.getMonitoredDirName();
        LOGGER.debug("Scanning directory: " + scanDir);
        File dir = new File(scanDir);
        if (!dir.exists()) {
            LOGGER.info("Created monitoring dir " + dir + " success=" + dir.mkdirs());
        }
        File arcDir = new File(scanDir + "/" + FileMonRunnableMain.ARCHIVE);
        if (!arcDir.exists()) {
            LOGGER.info("Created monitoring dir " + arcDir + " success=" + arcDir.mkdirs());
        }
        // Getting list of files recursively from directory except '_archive' directory
        Collection<File> listOfFiles = FileUtils.listFiles(dir,
                new RegexFileFilter(FileMonRunnableMain.getFilePattern()),
                new RegexFileFilter("^(?:(?!" + FileMonRunnableMain.ARCHIVE + ").)*$"));
        String fileName = "";
        FileCopyInfo fileCopyInfo = null;
        for (File file : listOfFiles) {
            fileName = file.getName();
            LOGGER.debug("Matched File Pattern by " + fileName);
            fileCopyInfo = new FileCopyInfo();
            fileCopyInfo.setFileName(fileName);
            fileCopyInfo.setSubProcessId(FileMonRunnableMain.getSubProcessId());
            fileCopyInfo.setServerId(Integer.toString(123461));
            fileCopyInfo.setSrcLocation(file.getAbsolutePath());
            fileCopyInfo.setDstLocation(file.getParent().replace(FileMonRunnableMain.getMonitoredDirName(),
                    FileMonRunnableMain.getHdfsUploadDir()));
            fileCopyInfo.setFileHash(DigestUtils.md5Hex(FileUtils.readFileToByteArray(file)));
            fileCopyInfo.setFileSize(file.length());
            fileCopyInfo.setTimeStamp(file.lastModified());
            FileMonitor.addToQueue(fileName, fileCopyInfo);
        }
    } catch (Exception err) {
        LOGGER.error("Error in scan directory ", err);
        throw new BDREException(err);
    }
}

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

/**
 *   .//from   www.  j a  v a2s  .  co m
 * 
 * @param dirPath  .
 * @param fromDate . (yyyy-MM-dd)
 * @param toDate  . (yyyy-MM-dd)
 * @return ??  true.
 * @see File#exists()
 */
public static boolean existsDir(final String dirPath, final String fromDate, final String toDate) {
    return processIO(new IOCallback<Boolean>() {
        public Boolean doInProcessIO() throws NullPointerException, SecurityException {
            File file = new File(dirPath);

            if (existsDir(dirPath)) {
                String lastModifed = DateUtils.date2String(new Date(file.lastModified()));
                if (DateUtils.string2Date(lastModifed).getTime() >= DateUtils.string2Date(fromDate).getTime()
                        && DateUtils.string2Date(lastModifed).getTime() <= DateUtils.string2Date(toDate)
                                .getTime()) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    });
}

From source file:org.transitime.gtfs.GtfsUpdatedModule.java

/**
 * Gets the GTFS file via http from the configured URL urlStr and stores it
 * in the configured directory dirName./*  w w w  .  ja  v  a 2  s  . c om*/
 * <p>
 * If file on web server last modified time is not newer than the local file
 * then the file will not actually be downloaded.
 * <p>
 * If file is downloaded then users and e-mailed.
 */
public static void get() {
    logger.info("Checking to see if GTFS should be downloaded " + "because it was modified. {}",
            url.getValue());

    // Construct the getter
    HttpGetFile httpGetFile = new HttpGetFile(url.getValue(), dirName.getValue());

    // If file hasn't been modified then don't want to download it
    // since it can be large. Therefore determine age of previously 
    // downloaded file and use If-Modified-Since to only actually
    // get the file if it is newer on the web server
    File file = new File(httpGetFile.getFullFileName());
    boolean fileAlreadyExists = file.exists();
    if (fileAlreadyExists) {
        // Get the last modified time of the local file. Add 10 minutes
        // since the web server might be load balanced and the files
        // on the different servers might have slightly different last 
        // modified times. To make sure that don't keep downloading 
        // from the different servers until get the file with most 
        // recent modified time add 10 minutes to the time to indicate
        // that as long as the local file is within 10 minutes of the
        // remote file that it is ok.
        long lastModified = file.lastModified() + 10 * Time.MS_PER_MIN;

        httpGetFile.addRequestHeader("If-Modified-Since", Time.httpDate(lastModified));

        logger.debug("The file {} already exists so using " + "If-Modified-Since header of \"{}\" or {} msec.",
                httpGetFile.getFullFileName(), Time.httpDate(lastModified), lastModified);
    }

    try {
        // Actually get the file from web server
        int httpResponseCode = httpGetFile.getFile();

        // If got a new file (instead of getting a NOT MODIFIED
        // response) then send message to those monitoring so that
        // the GTFS file can be processed.
        if (httpResponseCode == HttpStatus.SC_OK) {
            if (fileAlreadyExists)
                logger.info("Got remote file because version on web server " + "is newer. Url={} dir={}",
                        httpGetFile.getFullFileName(), dirName.getValue());
            else
                logger.info("Got remote file because didn't have a local " + "copy of it. Url={} dir={}",
                        httpGetFile.getFullFileName(), dirName.getValue());

            // Email message
            String subject = "GTFS file was updated for " + AgencyConfig.getAgencyId();
            String message = "For " + AgencyConfig.getAgencyId() + " the GTFS file " + url.getValue()
                    + " was updated so was downloaded to " + httpGetFile.getFullFileName();
            emailSender.send(MonitorBase.recipientsGlobal(), subject, message);

            // Make copy of GTFS zip file in separate directory for archival
            archive(httpGetFile.getFullFileName());
        } else if (httpResponseCode == HttpStatus.SC_NOT_MODIFIED) {
            // If not modified then don't need to do anything
            logger.info(
                    "Remote GTFS file {} not updated (got " + "HTTP NOT_MODIFIED status 304) since the local "
                            + "one  at {} has last modified date of {}",
                    url.getValue(), httpGetFile.getFullFileName(), new Date(file.lastModified()));
        } else {
            // Got unexpected response so log issue
            logger.error("Error retrieving remote GTFS file {} . Http " + "response code={}", url.getValue(),
                    httpResponseCode);
        }
    } catch (IOException e) {
        logger.error("Error retrieving {} . {}", url.getValue(), e.getMessage());
    }
}

From source file:net.opentsdb.tsd.GraphHandler.java

/**
 * Returns whether or not the given cache file can be used or is stale.
 * @param query The query to serve./*w  w w. j a v a 2  s  .  c  om*/
 * @param end_time The end time on the query (32-bit unsigned int, seconds).
 * @param max_age The maximum time (in seconds) we wanna allow clients to
 * cache the result in case of a cache hit.  If the file is exactly that
 * old, it is not considered stale.
 * @param cachedfile The file to check for staleness.
 */
private static boolean staleCacheFile(final HttpQuery query, final long end_time, final long max_age,
        final File cachedfile) {
    final long mtime = cachedfile.lastModified() / 1000;
    if (mtime <= 0) {
        return true; // File doesn't exist, or can't be read.
    }

    final long now = System.currentTimeMillis() / 1000;
    // How old is the cached file, in seconds?
    final long staleness = now - mtime;
    if (staleness < 0) { // Can happen if the mtime is "in the future".
        logWarn(query, "Not using file @ " + cachedfile + " with weird" + " mtime in the future: " + mtime);
        return true; // Play it safe, pretend we can't use this file.
    }

    // Case 1: The end time is an absolute point in the past.
    // We might be able to re-use the cached file.
    if (0 < end_time && end_time < now) {
        // If the file was created prior to the end time, maybe we first
        // executed this query while the result was uncacheable.  We can
        // tell by looking at the mtime on the file.  If the file was created
        // before the query end time, then it contains partial results that
        // shouldn't be served again.
        return mtime < end_time;
    }

    // Case 2: The end time of the query is now or in the future.
    // The cached file contains partial data and can only be re-used if it's
    // not too old.
    if (staleness > max_age) {
        logInfo(query, "Cached file @ " + cachedfile.getPath() + " is " + staleness
                + "s stale, which is more than its limit of " + max_age + "s, and needs to be regenerated.");
        return true;
    }
    return false;
}

From source file:eu.planets_project.services.utils.ZipUtils.java

private static Date getFileDate(File file) {
    Date date = new Date(file.lastModified());
    return date;//from  ww  w. j a v a 2  s.  co m
}

From source file:me.doshou.admin.maintain.editor.web.controller.utils.OnlineEditorUtils.java

public static Map<Object, Object> extractFileInfoMap(File currentFile, String rootPath)
        throws UnsupportedEncodingException {
    Map<Object, Object> info = Maps.newHashMap();
    String name = currentFile.getName();
    info.put("name", name);
    info.put("path",
            URLEncoder.encode(currentFile.getAbsolutePath().replace(rootPath, ""), Constants.ENCODING));
    info.put("canEdit", canEdit(name));
    info.put("hasParent", !currentFile.getPath().equals(rootPath));
    info.put("isParent", hasSubFiles(currentFile));
    info.put("isDirectory", currentFile.isDirectory());
    info.put("root", info.get("path").equals(""));
    info.put("open", info.get("path").equals(""));
    info.put("iconSkin", currentFile.isDirectory() ? CSS_DIRECTORY : CSS_FILE);
    info.put("size", currentFile.length());
    Date modifiedDate = new Date(currentFile.lastModified());
    info.put("lastModified", DateFormatUtils.format(modifiedDate, DATE_PATTERN));
    info.put("lastModifiedForLong", currentFile.lastModified());
    return info;//from  w  w  w.  j  a  v  a  2s. com
}

From source file:com.nary.io.FileUtils.java

/**
 * Replacement for File.exists() method designed to provide an accurate and efficient check that a file really exists. This method is necessary because of an error in the Windows JavaVM in which file names beginning with the same name as a MS-DOS device (e.g. con.cfm, or com1.cfm, etc) will be reported as existing by File.exists(). [ This causes the current thread to hang while attempting to
 * read from the DOS device thus [ preventing further requests to be processed; thus a "denial of service" vulnerability. This alternative method is designed to return quickly for the typical case where the URL is supported with a real file. Note however that empty real files cannot be confirmed without completing all the validation steps required to absolutely confirm the MS-DOS device file
 * condition. This should be a rare case. Note: - getCanonicalPath() provides inconsistent results for non-existing file dependent upon whether a previous call was made with an existant file! (yes, I tested this!) - DOS device names cannot be used as file names on Windows XP nor 2003; i.e. aux.cfm or con.cfm cannot be created. - getCanonicalPath() will sometimes return the pathname with the
 * ".cfm" extension truncated for these "DOS device" files.
 *///www  . ja v a  2  s .c om
public static boolean exists(File _thefile, cfmlURI _uri) {
    if (_thefile.length() != 0) { // all DOS devices have zero length...
        return true; // therefore most valid files will satisfy these tests and return here.
    }

    if (_thefile.lastModified() == 0) { // all valid files have a non-zero value, but DOS devices may also ...
        return false;
    }

    // if we make it here then _thefile.length() == 0, and _thefile.lastModified() != 0,
    // so now we need to make sure it's a valid empty file and not a DOS device name
    try {
        // _thefile.getCanonicalPath() has three possible results:
        // 1. throw an IOException, in which case the file doesn't exist
        // 2. returns a path including the file extension, in which case the file exists
        // 3. returns a path that doesn't have the file extension, in which case the file doesn't exist
        String filename = _thefile.getCanonicalPath();

        // Check for the case that filename has had the ".cfm" extension truncated by comparing against the original URI
        String uri = _uri.getURI();
        if (filename.endsWith(uri.substring(uri.lastIndexOf('.')))) {
            return true;
        }
        return false;
    } catch (IOException e) {
        return false; // Exception guarantees that file does not exist.
    }
}

From source file:MailHandlerDemo.java

/**
 * Used debug problems with the logging.properties. The system property
 * java.security.debug=access,stack can be used to trace access to the
 * LogManager reset./*from   w  ww . j  av  a  2 s .  c  o m*/
 *
 * @param prefix a string to prefix the output.
 * @param err any PrintStream or null for System.out.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void checkConfig(String prefix, PrintStream err) {
    if (prefix == null || prefix.trim().length() == 0) {
        prefix = "DEBUG";
    }

    if (err == null) {
        err = System.out;
    }

    try {
        err.println(prefix + ": java.version=" + System.getProperty("java.version"));
        err.println(prefix + ": LOGGER=" + LOGGER.getLevel());
        err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName());
        err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug"));
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName());
            err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader()));
            err.println(prefix + ": SecurityManager.toString=" + sm);
        } else {
            err.println(prefix + ": SecurityManager.class=null");
            err.println(prefix + ": SecurityManager.toString=null");
            err.println(prefix + ": SecurityManager classLoader=null");
        }

        String policy = System.getProperty("java.security.policy");
        if (policy != null) {
            File f = new File(policy);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        }

        LogManager manager = LogManager.getLogManager();
        String key = "java.util.logging.config.file";
        String cfg = System.getProperty(key);
        if (cfg != null) {
            err.println(prefix + ": " + cfg);
            File f = new File(cfg);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        } else {
            err.println(prefix + ": " + key + " is not set as a system property.");
        }
        err.println(prefix + ": LogManager.class=" + manager.getClass().getName());
        err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader()));
        err.println(prefix + ": LogManager.toString=" + manager);
        err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader()));
        err.println(
                prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader()));
        err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader()));
        err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader()));

        final String p = MailHandler.class.getName();
        key = p.concat(".mail.to");
        String to = manager.getProperty(key);
        err.println(prefix + ": TO=" + to);
        if (to != null) {
            err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true)));
        }

        key = p.concat(".mail.from");
        String from = manager.getProperty(key);
        if (from == null || from.length() == 0) {
            Session session = Session.getInstance(new Properties());
            InternetAddress local = InternetAddress.getLocalAddress(session);
            err.println(prefix + ": FROM=" + local);
        } else {
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false)));
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true)));
        }

        synchronized (manager) {
            final Enumeration<String> e = manager.getLoggerNames();
            while (e.hasMoreElements()) {
                final Logger l = manager.getLogger(e.nextElement());
                if (l != null) {
                    final Handler[] handlers = l.getHandlers();
                    if (handlers.length > 0) {
                        err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName());
                        for (Handler h : handlers) {
                            err.println(prefix + ":\t" + toString(prefix, err, h));
                        }
                    }
                }
            }
        }
    } catch (Throwable error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }
    err.flush();
}