Java Code Examples for java.nio.file.attribute.FileTime#compareTo()

The following examples show how to use java.nio.file.attribute.FileTime#compareTo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HollowFilesystemAnnouncementWatcher.java    From hollow with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        HollowFilesystemAnnouncementWatcher watcher = ref.get();
        if (watcher != null) {
            if (!Files.isReadable(watcher.announcePath)) return;

            FileTime lastModifiedTime = getLastModifiedTime(watcher.announcePath);
            if (lastModifiedTime.compareTo(previousFileTime) > 0) {
                previousFileTime = lastModifiedTime;

                long currentVersion = watcher.readLatestVersion();
                if (watcher.latestVersion != currentVersion) {
                    watcher.latestVersion = currentVersion;
                    for (HollowConsumer consumer : watcher.subscribedConsumers)
                        consumer.triggerAsyncRefresh();
                }
            }
        }
    } catch (Exception ex) {
        log.log(Level.WARNING, "Exception reading the current announced version", ex);
    } catch (Throwable th) {
        log.log(Level.SEVERE, "Exception reading the current announced version", th);
        throw th;
    }
}
 
Example 2
Source File: AdvancedServiceDiscoveryConfigurationMonitor.java    From knox with Apache License 2.0 6 votes vote down vote up
private void monitorAdvancedServiceConfiguration(Path resourcePath) {
  try {
    if (Files.exists(resourcePath) && Files.isReadable(resourcePath)) {
      FileTime lastModifiedTime = Files.getLastModifiedTime(resourcePath);
      FileTime lastReloadTime = lastReloadTimes.get(resourcePath);
      if (lastReloadTime == null || lastReloadTime.compareTo(lastModifiedTime) < 0) {
        lastReloadTimes.put(resourcePath, lastModifiedTime);
        try (InputStream advanceconfigurationFileInputStream = Files.newInputStream(resourcePath)) {
          Properties properties = new Properties();
          properties.load(advanceconfigurationFileInputStream);
          notifyListeners(resourcePath.toString(), properties);
        }
      }
    }
  } catch (IOException e) {
    LOG.failedToMonitorClouderaManagerAdvancedConfiguration(e.getMessage(), e);
  }
}
 
Example 3
Source File: PFontHandler.java    From PolyGlot with MIT License 6 votes vote down vote up
/**
 * Compares "freshness" of files. First compares last modified. If the same
 * (and running on Windows), also compares creation date. Returns true if 
 * file a is fresher than file b.
 * @param a
 * @param b
 * @return 
 * * @throws java.io.IOException
 */
private static boolean compareFreshness(File a, File b) throws IOException {
    boolean ret = false;
    long aModified = a.lastModified();
    long bModified = b.lastModified();
    
    if (aModified == bModified && PGTUtil.IS_WINDOWS) {
        FileTime aCreated = Files.readAttributes(a.toPath(), BasicFileAttributes.class).creationTime();
        FileTime bCreated = Files.readAttributes(b.toPath(), BasicFileAttributes.class).creationTime();
        
        if (aCreated.compareTo(bCreated) > 0) {
            ret = true;
        }
    } else if (aModified > bModified) {
        ret = true;
    }
    
    return ret;
}
 
Example 4
Source File: RollingFileManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static long initialFileTime(File file) {
    Path path = file.toPath();
    if (Files.exists(path)) {
        try {
            BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
            FileTime fileTime = attrs.creationTime();
            if (fileTime.compareTo(EPOCH) > 0) {
                return fileTime.toMillis();
            }
            LOGGER.info("Unable to obtain file creation time for " + file.getAbsolutePath());
        } catch (Exception ex) {
            LOGGER.info("Unable to calculate file creation time for " + file.getAbsolutePath() + ": " + ex.getMessage());
        }
    }
    return file.lastModified();
}
 
Example 5
Source File: LocalFileFilter.java    From LiquidDonkey with MIT License 5 votes vote down vote up
int testLastModified(Path local, ICloud.MBSFile remote) throws IOException {
    FileTime localTimestamp = Files.getLastModifiedTime(local);
    FileTime remoteTimestamp = FileTime.from(remote.getAttributes().getLastModified(), TimeUnit.SECONDS);
    int comparision = localTimestamp.compareTo(remoteTimestamp);

    logger.debug("-- testLastModified() < comparision: {} local: {} remote: {} file: {}",
            comparision, localTimestamp, remoteTimestamp, remote.getRelativePath());
    return comparision;
}
 
Example 6
Source File: PathItem.java    From LiveDirsFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public boolean updateModificationTime(FileTime lastModified) {
    if(lastModified.compareTo(this.lastModified) > 0) {
        this.lastModified = lastModified;
        return true;
    } else {
        return false;
    }
}
 
Example 7
Source File: MOptionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testOneModule(Path base) throws Exception {
    Path src = base.resolve("src");
    Path m1 = src.resolve("m1x");
    Path build = base.resolve("build");
    Files.createDirectories(build);

    tb.writeJavaFiles(m1,
            "module m1x {}",
            "package test; public class Test {}");

    new JavacTask(tb)
            .options("-m", "m1x", "--module-source-path", src.toString(), "-d", build.toString())
            .run(Task.Expect.SUCCESS)
            .writeAll();

    Path moduleInfoClass = build.resolve("m1x/module-info.class");
    Path testTestClass = build.resolve("m1x/test/Test.class");

    FileTime moduleInfoTimeStamp = Files.getLastModifiedTime(moduleInfoClass);
    FileTime testTestTimeStamp = Files.getLastModifiedTime(testTestClass);

    Path moduleInfo = m1.resolve("module-info.java");
    if (moduleInfoTimeStamp.compareTo(Files.getLastModifiedTime(moduleInfo)) < 0) {
        throw new AssertionError("Classfiles too old!");
    }

    Path testTest = m1.resolve("test/Test.java");
    if (testTestTimeStamp.compareTo(Files.getLastModifiedTime(testTest)) < 0) {
        throw new AssertionError("Classfiles too old!");
    }

    Thread.sleep(2000); //timestamps

    new JavacTask(tb)
            .options("-m", "m1x", "--module-source-path", src.toString(), "-d", build.toString())
            .run(Task.Expect.SUCCESS)
            .writeAll();

    if (!moduleInfoTimeStamp.equals(Files.getLastModifiedTime(moduleInfoClass))) {
        throw new AssertionError("Classfile update!");
    }

    if (!testTestTimeStamp.equals(Files.getLastModifiedTime(testTestClass))) {
        throw new AssertionError("Classfile update!");
    }

    Thread.sleep(2000); //timestamps

    Files.setLastModifiedTime(testTest, FileTime.fromMillis(System.currentTimeMillis()));

    new JavacTask(tb)
            .options("-m", "m1x", "--module-source-path", src.toString(), "-d", build.toString())
            .run(Task.Expect.SUCCESS)
            .writeAll();

    if (!moduleInfoTimeStamp.equals(Files.getLastModifiedTime(moduleInfoClass))) {
        throw new AssertionError("Classfile update!");
    }

    if (Files.getLastModifiedTime(testTestClass).compareTo(Files.getLastModifiedTime(testTest)) < 0) {
        throw new AssertionError("Classfiles too old!");
    }
}
 
Example 8
Source File: Plugin.java    From audiveris with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Try to retrieve an up-to-date export file
 *
 * @param book the related book
 * @return path to suitable export, or null
 */
private Path retrieveExport (Book book)
{
    try {
        // Make sure we have the export file
        final Path exportPathSansExt = BookManager.getDefaultExportPathSansExt(book);

        if (exportPathSansExt == null) {
            logger.warn("Could not get export path");

            return null;
        }

        final Path exportPath = Paths.get(exportPathSansExt + BookManager.getExportExtension());

        if (Files.exists(exportPath)) {
            FileTime exportTime = Files.getLastModifiedTime(exportPath);

            if (!book.isModified()) {
                Path bookPath = book.getBookPath();

                if ((bookPath != null) && Files.exists(bookPath)) {
                    FileTime bookTime = Files.getLastModifiedTime(bookPath);

                    if (exportTime.compareTo(bookTime) > 0) {
                        return exportPath; // We can use this export file
                    }
                }
            }
        }

        book.export();

        if (Files.exists(exportPath)) {
            return exportPath;
        }

        logger.warn("Cannot find file {}", exportPath);
    } catch (IOException ex) {
        logger.warn("Error getting export file " + ex, ex);
    }

    return null;
}
 
Example 9
Source File: JarExpander.java    From libreveris with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Process one entry.
 *
 * @param source the source entry to check and install
 * @return 1 if actually copied, 0 otherwise
 */
private int process (String source)
{
    ///logger.debug("Processing source {}", source);
    final String sourcePath = sourceFolder.isEmpty() ? source
            : source.substring(sourceFolder.length() + 1);
    final Path target = Paths.get(targetFolder.toString(), sourcePath);

    try {
        if (source.endsWith("/")) {
            // This is a directory
            if (Files.exists(target)) {
                if (!Files.isDirectory(target)) {
                    logger.warn("Existing non directory {}", target);
                } else {
                    logger.trace("Directory {} exists", target);
                }
                return 0;
            } else {
                Files.createDirectories(target);
                logger.trace("Created dir {}", target);
                return 1;
            }
        } else {
            ZipEntry entry = jar.getEntry(source);

            // Target exists?
            if (Files.exists(target)) {
                // Compare date
                FileTime sourceTime = FileTime.fromMillis(entry.getTime());
                FileTime targetTime = Files.getLastModifiedTime(target);
                if (targetTime.compareTo(sourceTime) >= 0) {
                    logger.trace("Target {} is up to date", target);
                    return 0;
                }
            }

            // Do copy
            ///logger.info("About to copy {} to {}", source, target);
            try (InputStream is = jar.getInputStream(entry)) {
                Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING);
                logger.trace("Target {} copied", target);
                return 1;
            }
        }
    } catch (IOException ex) {
        logger.warn("IOException on " + target, ex);
        return 0;
    }
}
 
Example 10
Source File: MyTab.java    From AsciidocFX with Apache License 2.0 4 votes vote down vote up
private synchronized void save() {

        FileTime latestModifiedTime = IOHelper.getLastModifiedTime(getPath());

        if (Objects.nonNull(latestModifiedTime) && Objects.nonNull(getLastModifiedTime())) {
            if (latestModifiedTime.compareTo(getLastModifiedTime()) > 0) {

                this.select();
                ButtonType buttonType = AlertHelper.conflictAlert(getPath()).orElse(ButtonType.CANCEL);

                if (buttonType == ButtonType.CANCEL) {
                    return;
                }

                if (buttonType == AlertHelper.LOAD_FILE_SYSTEM_CHANGES) {
                    load();
                }
            } else {
                if (!isNew() && !isChanged()) {
                    return;
                }
            }
        }

        if (Objects.isNull(getPath())) {
            final FileChooser fileChooser = directoryService.newFileChooser(String.format("Save file"));
            fileChooser.getExtensionFilters().addAll(ExtensionFilters.ASCIIDOC);
            fileChooser.getExtensionFilters().addAll(ExtensionFilters.MARKDOWN);
            fileChooser.getExtensionFilters().addAll(ExtensionFilters.ALL);
            File file = fileChooser.showSaveDialog(null);

            if (Objects.isNull(file))
                return;

            setPath(file.toPath());
            setTabText(file.toPath().getFileName().toString());
        }

        String editorValue = editorPane.getEditorValue();

        IOHelper.createDirectories(getPath().getParent());

        Optional<Exception> exception =
                IOHelper.writeToFile(getPath(), editorValue, TRUNCATE_EXISTING, CREATE, SYNC);

        if (exception.isPresent()) {
            return;
        }

        setLastModifiedTime(IOHelper.getLastModifiedTime(getPath()));

        setChangedProperty(false);

        ObservableList<Item> recentFiles = storedConfigBean.getRecentFiles();
        recentFiles.remove(new Item(getPath()));
        recentFiles.add(0, new Item(getPath()));

        directoryService.setInitialDirectory(Optional.ofNullable(getPath().toFile()));
    }
 
Example 11
Source File: FileUtils.java    From helidon-build-tools with Apache License 2.0 2 votes vote down vote up
/**
 * Tests whether or not the given change time is newer than a base time.
 *
 * @param changeTime The time.
 * @param baseTime The base time. May be {@code null}.
 * @return {@code true} if base time is {@code null} or change time is newer.
 */
public static boolean newerThan(FileTime changeTime, FileTime baseTime) {
    return baseTime == null || changeTime.compareTo(baseTime) > 0;
}
 
Example 12
Source File: FileUtils.java    From helidon-build-tools with Apache License 2.0 2 votes vote down vote up
/**
 * Tests whether or not the given change time is older than a base time.
 *
 * @param changeTime The time.
 * @param baseTime The base time. May be {@code null}.
 * @return {@code true} if base time is {@code null} or change time is older.
 */
public static boolean olderThan(FileTime changeTime, FileTime baseTime) {
    return baseTime == null || changeTime.compareTo(baseTime) < 0;
}