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:org.paxml.core.PaxmlResource.java

public long getLastModified() {
    Resource res = getSpringResource();
    if (!res.exists()) {
        return -1;
    }//from   w ww .  j a v a  2  s.  c  o m
    final File file;
    try {
        file = res.getFile();
    } catch (IOException e) {
        return 0;
    }
    return file.lastModified();

}

From source file:org.orderofthebee.addons.support.tools.share.LogFileGet.java

/**
 *
 * {@inheritDoc}//from   w w  w .j  av a 2 s.com
 */
@Override
public void execute(final WebScriptRequest req, final WebScriptResponse res) throws IOException {
    final String servicePath = req.getServicePath();
    final String matchPath = req.getServiceMatch().getPath();
    final String filePath = servicePath.substring(servicePath.indexOf(matchPath) + matchPath.length());

    final Map<String, Object> model = new HashMap<>();
    final Status status = new Status();
    final Cache cache = new Cache(this.getDescription().getRequiredCache());
    model.put("status", status);
    model.put("cache", cache);

    final String attachParam = req.getParameter("a");
    final boolean attach = attachParam != null && Boolean.parseBoolean(attachParam);

    final File file = this.validateFilePath(filePath);

    // chances are log file is text/plain but might also be a compressed file (i.e. via logrotate)
    final String mimetype = "application/octet-stream";
    this.streamContent(req, res, file, file.lastModified(), attach, file.getName(), model, mimetype);
}

From source file:com.qwazr.utils.json.DirectoryJsonManager.java

protected void load() throws IOException, ServerException {
    try {/*from ww w. j a v a 2 s. co  m*/
        File[] files = directory.listFiles(JsonFileFilter.INSTANCE);
        if (files == null)
            return;
        for (File file : files) {
            String name = file.getName();
            name = name.substring(0, name.length() - 5);
            loadItem(name, file, file.lastModified());
        }
    } finally {
        buildCache();
    }
}

From source file:net.yacy.yacy.java

/**
* Starts up the whole application. Sets up all datastructures and starts
* the main threads.//from w  w w . j a  v a2 s  . c om
*
* @param homePath Root-path where all information is to be found.
* @param startupFree free memory at startup time, to be used later for statistics
*/
private static void startup(final File dataHome, final File appHome, final long startupMemFree,
        final long startupMemTotal, final boolean gui) {
    String tmpdir = null;
    try {
        // start up
        System.out.println(copyright);
        System.out.println(hline);

        // ensure that there is a DATA directory, if not, create one and if that fails warn and die
        mkdirsIfNeseccary(dataHome);
        mkdirsIfNeseccary(appHome);
        File f = new File(dataHome, "DATA/");
        mkdirsIfNeseccary(f);
        if (!(f.exists())) {
            System.err.println("Error creating DATA-directory in " + dataHome.toString()
                    + " . Please check your write-permission for this folder. YaCy will now terminate.");
            System.exit(-1);
        }

        // set jvm tmpdir to a subdir for easy cleanup (as extensive use file.deleteonexit waists memory during long runs, as todelete files names are collected and never cleaned up during runtime)
        // keep this as earlier as possible, as any other class can use the "java.io.tmpdir" property, even the log manager, when the log file pattern uses "%t" as an alias for the tmp directory 
        try {
            tmpdir = java.nio.file.Files.createTempDirectory("yacy-tmp-").toString(); // creates sub dir in jvm's temp (see System.property "java.io.tempdir")
            System.setProperty("java.io.tmpdir", tmpdir);
        } catch (IOException ex) {
        }

        // setting up logging
        f = new File(dataHome, "DATA/LOG/");
        mkdirsIfNeseccary(f);
        f = new File(dataHome, "DATA/LOG/yacy.logging");
        final File f0 = new File(appHome, "defaults/yacy.logging");
        if (!f.exists() || f0.lastModified() > f.lastModified())
            try {
                Files.copy(f0, f);
            } catch (final IOException e) {
                System.out.println("could not copy yacy.logging");
            }
        try {
            ConcurrentLog.configureLogging(dataHome, new File(dataHome, "DATA/LOG/yacy.logging"));
        } catch (final IOException e) {
            System.out.println("could not find logging properties in homePath=" + dataHome);
            ConcurrentLog.logException(e);
        }
        ConcurrentLog.config("STARTUP", "YaCy version: " + yacyBuildProperties.getVersion() + "/"
                + yacyBuildProperties.getSVNRevision());
        ConcurrentLog.config("STARTUP",
                "Java version: " + System.getProperty("java.version", "no-java-version"));
        ConcurrentLog.config("STARTUP", "Operation system: " + System.getProperty("os.name", "unknown"));
        ConcurrentLog.config("STARTUP", "Application root-path: " + appHome);
        ConcurrentLog.config("STARTUP", "Data root-path: " + dataHome);
        ConcurrentLog.config("STARTUP", "Time zone: UTC" + GenericFormatter.UTCDiffString() + "; UTC+0000 is "
                + System.currentTimeMillis());
        ConcurrentLog.config("STARTUP", "Maximum file system path length: " + OS.maxPathLength);

        f = new File(dataHome, "DATA/yacy.running");
        final String conf = "DATA/SETTINGS/yacy.conf".replace("/", File.separator);
        if (!f.createNewFile())
            ConcurrentLog.severe("STARTUP", "WARNING: the file " + f + " can not be created!");
        try {
            new FileOutputStream(f).write(Integer.toString(OS.getPID()).getBytes());
        } catch (final Exception e) {
        } // write PID
        f.deleteOnExit();
        FileChannel channel = null;
        FileLock lock = null;
        try {
            channel = new RandomAccessFile(f, "rw").getChannel();
            lock = channel.tryLock(); // lock yacy.running
        } catch (final Exception e) {
        }

        try {
            sb = new Switchboard(dataHome, appHome, "defaults/yacy.init".replace("/", File.separator), conf);
        } catch (final RuntimeException e) {
            ConcurrentLog.severe("STARTUP", "YaCy cannot start: " + e.getMessage(), e);
            System.exit(-1);
        }
        //sbSync.V(); // signal that the sb reference was set

        // switch the memory strategy
        MemoryControl.setStandardStrategy(sb.getConfigBool("memory.standardStrategy", true));

        // save information about available memory at startup time
        sb.setConfig("memoryFreeAfterStartup", startupMemFree);
        sb.setConfig("memoryTotalAfterStartup", startupMemTotal);

        // start gui if wanted
        if (gui)
            YaCyApp.start("localhost", sb.getLocalPort());

        // hardcoded, forced, temporary value-migration
        sb.setConfig("htTemplatePath", "htroot/env/templates");

        double oldVer;
        try {
            String tmpversion = sb.getConfig(Seed.VERSION, "");
            if (tmpversion.isEmpty()) { // before 1.83009737 only the svnRevision nr was in config (like 9737)
                tmpversion = yacyBuildProperties.getVersion();
                int oldRev = Integer.parseInt(sb.getConfig("svnRevision", "0"));
                if (oldRev > 1) {
                    oldVer = Double.parseDouble(tmpversion) + oldRev / 100000000.0;
                } else {
                    oldVer = Double.parseDouble(yacyBuildProperties.getLongVersion()); // failsafe (assume current version = no migration)
                }
            } else {
                oldVer = Double.parseDouble(tmpversion);
            }
        } catch (final NumberFormatException e) {
            oldVer = 0.0d;
        }
        final double newRev = Double.parseDouble(yacyBuildProperties.getLongVersion());
        sb.setConfig(Seed.VERSION, yacyBuildProperties.getLongVersion());
        sb.setConfig("applicationRoot", appHome.toString());
        sb.setConfig("dataRoot", dataHome.toString());

        // create some directories
        final File htRootPath = new File(appHome,
                sb.getConfig(SwitchboardConstants.HTROOT_PATH, SwitchboardConstants.HTROOT_PATH_DEFAULT));
        mkdirIfNeseccary(htRootPath);
        htDocsPath = sb.getDataPath(SwitchboardConstants.HTDOCS_PATH, SwitchboardConstants.HTDOCS_PATH_DEFAULT);
        mkdirIfNeseccary(htDocsPath);
        //final File htTemplatePath = new File(homePath, sb.getConfig("htTemplatePath","htdocs"));

        // copy the donate iframe (better to copy this once here instead of doing this in an actual iframe in the search result)
        importDonationIFrame(sb, htDocsPath);

        // create default notifier picture
        File notifierFile = new File(htDocsPath, "notifier.gif");
        if (!notifierFile.exists())
            try {
                Files.copy(new File(htRootPath, "env/grafics/empty.gif"), notifierFile);
            } catch (final IOException e) {
            }

        final File htdocsReadme = new File(htDocsPath, "readme.txt");
        if (!(htdocsReadme.exists()))
            try {
                FileUtils.copy(("This is your root directory for individual Web Content\r\n" + "\r\n"
                        + "Please place your html files into the www subdirectory.\r\n"
                        + "The URL of that path is either\r\n" + "http://www.<your-peer-name>.yacy    or\r\n"
                        + "http://<your-ip>:<your-port>/www\r\n" + "\r\n"
                        + "Other subdirectories may be created; they map to corresponding sub-domains.\r\n"
                        + "This directory shares it's content with the applications htroot path, so you\r\n"
                        + "may access your yacy search page with\r\n" + "http://<your-peer-name>.yacy/\r\n"
                        + "\r\n").getBytes(), htdocsReadme);
            } catch (final IOException e) {
                System.out.println("Error creating htdocs readme: " + e.getMessage());
            }

        shareDefaultPath = new File(htDocsPath, "share");
        mkdirIfNeseccary(shareDefaultPath);
        shareDumpDefaultPath = new File(shareDefaultPath, "dump");
        mkdirIfNeseccary(shareDumpDefaultPath);

        migration.migrate(sb, oldVer, newRev);

        // delete old release files
        final int deleteOldDownloadsAfterDays = (int) sb.getConfigLong("update.deleteOld", 30);
        yacyRelease.deleteOldDownloads(sb.releasePath, deleteOldDownloadsAfterDays);

        // set user-agent
        HTTPClient.setDefaultUserAgent(ClientIdentification.yacyInternetCrawlerAgent.userAgent);

        // start main threads
        final int port = sb.getLocalPort();
        try {
            // start http server
            YaCyHttpServer httpServer;
            httpServer = new Jetty9HttpServerImpl(port);
            httpServer.startupServer();
            sb.setHttpServer(httpServer);
            // TODO: this has no effect on Jetty (but needed to reflect configured value and limit is still used)
            ConnectionInfo.setServerMaxcount(sb.getConfigInt("connectionsMax", ConnectionInfo.getMaxcount()));

            ConcurrentLog.info("STARTUP", httpServer.getVersion());

            // open the browser window
            final boolean browserPopUpTrigger = sb
                    .getConfig(SwitchboardConstants.BROWSER_POP_UP_TRIGGER, "true").equals("true");
            if (browserPopUpTrigger)
                try {
                    final String browserPopUpPage = sb.getConfig(SwitchboardConstants.BROWSER_POP_UP_PAGE,
                            "ConfigBasic.html");
                    //boolean properPW = (sb.getConfig(SwitchboardConstants.ADMIN_ACCOUNT, "").isEmpty()) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0);
                    //if (!properPW) browserPopUpPage = "ConfigBasic.html";
                    /* YaCy main startup process must not hang because browser opening is long or fails. 
                     * Let's open try opening the browser in a separate thread */
                    new Thread("Browser opening") {
                        @Override
                        public void run() {
                            Browser.openBrowser(("http://localhost:" + port) + "/" + browserPopUpPage);
                        }
                    }.start();
                    // Browser.openBrowser((server.withSSL()?"https":"http") + "://localhost:" + serverCore.getPortNr(port) + "/" + browserPopUpPage);
                } catch (final Throwable e) {
                    // cannot open browser. This may be normal in headless environments
                    //Log.logException(e);
                }

            // enable browser popup, http server is ready now
            sb.tray.setReady();

            //regenerate Locales from Translationlist, if needed
            final File locale_source = sb.getAppPath("locale.source", "locales");
            final String lang = sb.getConfig("locale.language", "");
            // on lang=browser all active translation should be checked (because any could be requested by client)
            List<String> langlist;
            if (lang.endsWith("browser"))
                langlist = Translator.activeTranslations(); // get all translated languages
            else {
                langlist = new ArrayList<String>();
                langlist.add(lang);
            }
            for (String tmplang : langlist) {
                if (!tmplang.equals("") && !tmplang.equals("default") && !tmplang.equals("browser")) { //locale is used
                    String currentRev = null;
                    BufferedReader br = null;
                    try {
                        br = new BufferedReader(new InputStreamReader(new FileInputStream(
                                new File(sb.getDataPath("locale.translated_html", "DATA/LOCALE/htroot"),
                                        tmplang + "/version"))));
                        currentRev = br.readLine(); // may return null
                    } catch (final IOException e) {
                        //Error
                    } finally {
                        try {
                            br.close();
                        } catch (IOException ioe) {
                            ConcurrentLog.warn("STARTUP", "Could not close " + tmplang + " version file");
                        }
                    }

                    if (currentRev == null || !currentRev.equals(sb.getConfig(Seed.VERSION, ""))) {
                        try { //is this another version?!
                            final File sourceDir = new File(sb.getConfig(SwitchboardConstants.HTROOT_PATH,
                                    SwitchboardConstants.HTROOT_PATH_DEFAULT));
                            final File destDir = new File(
                                    sb.getDataPath("locale.translated_html", "DATA/LOCALE/htroot"), tmplang);
                            if (new TranslatorXliff().translateFilesRecursive(sourceDir, destDir,
                                    new File(locale_source, tmplang + ".lng"), "html,template,inc", "locale")) { //translate it
                                //write the new Versionnumber
                                final BufferedWriter bw = new BufferedWriter(
                                        new PrintWriter(new FileWriter(new File(destDir, "version"))));
                                bw.write(sb.getConfig(Seed.VERSION, "Error getting Version"));
                                bw.close();
                            }
                        } catch (final IOException e) {
                        }
                    }
                }
            }
            // initialize number formatter with this locale
            if (!lang.equals("browser")) // "default" is handled by .setLocale()
                Formatter.setLocale(lang);

            // registering shutdown hook
            ConcurrentLog.config("STARTUP", "Registering Shutdown Hook");
            final Runtime run = Runtime.getRuntime();
            run.addShutdownHook(new shutdownHookThread(sb, shutdownSemaphore));

            // save information about available memory after all initializations
            //try {
            sb.setConfig("memoryFreeAfterInitBGC", MemoryControl.free());
            sb.setConfig("memoryTotalAfterInitBGC", MemoryControl.total());
            System.gc();
            sb.setConfig("memoryFreeAfterInitAGC", MemoryControl.free());
            sb.setConfig("memoryTotalAfterInitAGC", MemoryControl.total());
            //} catch (final ConcurrentModificationException e) {}

            // wait for server shutdown
            try {
                sb.waitForShutdown();
            } catch (final Exception e) {
                ConcurrentLog.severe("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(), e);
            }
            // shut down
            Array.terminate();
            ConcurrentLog.config("SHUTDOWN", "caught termination signal");
            httpServer.stop();

            ConcurrentLog.config("SHUTDOWN", "server has terminated");
            sb.close();
        } catch (final Exception e) {
            ConcurrentLog.severe("STARTUP", "Unexpected Error: " + e.getClass().getName(), e);
            //System.exit(1);
        }
        if (lock != null)
            lock.release();
        if (channel != null)
            channel.close();
    } catch (final Exception ee) {
        ConcurrentLog.severe("STARTUP", "FATAL ERROR: " + ee.getMessage(), ee);
    } finally {
    }

    if (tmpdir != null)
        FileUtils.deletedelete(new File(tmpdir)); // clean up temp dir (set at startup as subdir of system.propery "java.io.tmpdir")

    ConcurrentLog.config("SHUTDOWN", "goodbye. (this is the last line)");
    ConcurrentLog.shutdown();
    shutdownSemaphore.release(1000);
    try {
        System.exit(0);
    } catch (final Exception e) {
    } // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790)
}

From source file:com.qwazr.utils.json.DirectoryJsonManager.java

private T getNoLock(File file, String name, AtomicBoolean mustBeEvaluated) throws IOException {
    Pair<Long, T> item = instancesCache.get(name);
    long lastModified = file.lastModified();
    if (file.exists()) {
        if (item != null && item.getLeft() == lastModified)
            return item.getRight();
        if (mustBeEvaluated == null) {
            item = loadItem(name, file, lastModified);
            buildCache();/*from   ww w .ja v a  2s  .  c  o  m*/
            return item.getRight();
        }
    } else {
        if (item == null)
            return null;
        if (mustBeEvaluated == null) {
            instancesMap.remove(name);
            buildCache();
            return null;
        }
    }
    mustBeEvaluated.set(true);
    return null;
}

From source file:com.thinkbiganalytics.nifi.provenance.repo.ConfigurationProperties.java

public boolean isModified() {
    File file = getConfigFile(getConfigLocation());
    return (lastModified != null && file.exists() && file.lastModified() != lastModified);
}

From source file:no.dusken.aranea.admin.control.EditExternalPageController.java

/**
 * get 15 last feedentries from the given url.
 *
 * @param feedurl - url to a rss-feed/*  w ww  .  ja v a 2  s.com*/
 * @return list with feedentries
 */
private SyndFeed getFeedEntries(String feedurl) {
    File feedFile = new File(cacheDirectory + "/" + feedurl);

    // check if the file is too old, and download if that is the case
    if (!feedFile.exists() || System.currentTimeMillis() - feedFile.lastModified() > 100000) {
        try {
            FileUtils.copyURLToFile(new URL(feedurl), new File(cacheDirectory + "/" + feedurl));
        } catch (IOException e) {
            // log, continue using the old file and hope the best
            log.error("Could not download rss", e);
        }
    }
    SyndFeed feed = null;
    try {
        SyndFeedInput input = new SyndFeedInput();
        feed = input.build(new XmlReader(feedFile));
        feed.setEncoding("UTF-8");
    } catch (FeedException e) {
        log.error("Could not parse feed", e);
    } catch (IOException e) {
        log.error("Could not read rss file", e);
    }
    if (feed != null) {
        return feed;
    } else {
        return null;
    }
}

From source file:org.paxml.tag.AbstractPaxmlEntity.java

@Override
public boolean isModified() {
    Resource res = getResource().getSpringResource();
    if (!res.exists()) {
        return true;
    }//from   ww w.  java 2s  . c  o m
    final File file;
    try {
        file = res.getFile();

    } catch (IOException e) {
        // if file is not obtainable, it is not modifiable.
        return false;
    }
    return !file.exists() || file.lastModified() != timestamp;
}

From source file:MainClass.java

public Object[][] getFileStats(File dir) {
    String files[] = dir.list();//  w  ww .j  a v  a  2  s  .c om
    Object[][] results = new Object[files.length][titles.length];

    for (int i = 0; i < files.length; i++) {
        File tmp = new File(files[i]);
        results[i][0] = new Boolean(tmp.isDirectory());
        results[i][1] = tmp.getName();
        results[i][2] = new Boolean(tmp.canRead());
        results[i][3] = new Boolean(tmp.canWrite());
        results[i][4] = new Long(tmp.length());
        results[i][5] = new Date(tmp.lastModified());
    }
    return results;
}

From source file:net.firejack.platform.core.store.registry.FileStore.java

@Override
public FileInfo getInfo(String... path) {
    try {/*from  w w w .  jav  a2 s .c  om*/
        FileUtils.checkPath(base, path);
    } catch (IOException e) {
        return null;
    }
    File file = FileUtils.create(base, path);
    if (!file.exists()) {
        return null;
    }
    return new FileInfo(file.getName(), file.lastModified());
}