Java Code Examples for java.nio.file.attribute.BasicFileAttributes#lastAccessTime()

The following examples show how to use java.nio.file.attribute.BasicFileAttributes#lastAccessTime() . 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: FileScanner.java    From jesterj with Apache License 2.0 6 votes vote down vote up
/**
 * A default, reusable and overridable means of adding file attributes to a document
 *
 * @param attributes The attributes of the scanned file as returned by
 *                   {@link java.nio.file.Files#getFileAttributeView(Path, Class, LinkOption...)}
 * @param doc        The document representing the scanned file to which attributes should be added.
 */
default void addAttrs(BasicFileAttributes attributes, DocumentImpl doc) {
  if (attributes != null) {
    FileTime modifiedTime = attributes.lastModifiedTime();
    FileTime accessTime = attributes.lastAccessTime();
    FileTime creationTime = attributes.creationTime();
    if (modifiedTime != null) {
      doc.put("modified", String.valueOf(modifiedTime.toMillis()));
    }
    if (accessTime != null) {
      doc.put("accessed", String.valueOf(accessTime.toMillis()));
    }
    if (creationTime != null) {
      doc.put("created", String.valueOf(creationTime.toMillis()));
    }
    doc.put("file_size", String.valueOf(attributes.size()));
  }
}
 
Example 2
Source File: S3Utils.java    From mrgeo with Apache License 2.0 6 votes vote down vote up
@Override
public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs) throws IOException
{
  if (file != null) {
    java.nio.file.Path nameOnly = file.getFileName();
    if (nameOnly != null) {
      String fileName = nameOnly.toString();
      if (fileName.equals("index")) {
        indexAttributes = attrs;
        if (attrs.lastAccessTime().compareTo(lastAccessTime) < 0) {
          lastAccessTime = attrs.lastAccessTime();
        }
      } else if (fileName.equals("data")) {
        dataAttributes = attrs;
        if (attrs.lastAccessTime().compareTo(lastAccessTime) < 0) {
          lastAccessTime = attrs.lastAccessTime();
        }
      }
    }
  }
  return FileVisitResult.CONTINUE;
}
 
Example 3
Source File: DocumentCreator.java    From ganttproject with GNU General Public License v3.0 5 votes vote down vote up
public static Runnable createAutosaveCleanup() {
  long now = CalendarFactory.newCalendar().getTimeInMillis();
  final File tempDir = getTempDir();
  final long cutoff;
  try {
    File optionsFile = GanttOptions.getOptionsFile();
    if (!optionsFile.exists()) {
      return null;
    }
    GPLogger.log("Options file:" + optionsFile.getAbsolutePath());
    BasicFileAttributes attrs = Files.readAttributes(optionsFile.toPath(), BasicFileAttributes.class);
    FileTime accessTime = attrs.lastAccessTime();
    cutoff = Math.min(accessTime.toMillis(), now);
  } catch (IOException e) {
    GPLogger.log(e);
    return null;
  }
  return new Runnable() {
    @Override
    public void run() {
      GPLogger.log("Deleting old auto-save files");
      deleteAutosaves();
    }

    private void deleteAutosaves() {
      // Let's find autosaves created before launch of this GP instance
      File[] previousAutosaves = tempDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
          return file.getName().startsWith("_ganttproject_autosave") && file.lastModified() < cutoff;
        }
      });
      for (File f : previousAutosaves) {
        f.deleteOnExit();
      }
    }
  };
}
 
Example 4
Source File: AbstractJimfsIntegrationTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
FileTimeTester(Path path) throws IOException {
  this.path = path;

  BasicFileAttributes attrs = attrs();
  accessTime = attrs.lastAccessTime();
  modifiedTime = attrs.lastModifiedTime();
}
 
Example 5
Source File: UnixSocketFile.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
    throws InterruptedException, IOException {

    // Use 'which' to verify that 'nc' is available and skip the test
    // if it is not.
    Process proc = Runtime.getRuntime().exec("which nc");
    InputStream stdout = proc.getInputStream();
    int b = stdout.read();
    proc.destroy();
    if (b == -1) {
        System.err.println("Netcat command unavailable; skipping test.");
        return;
    }

    // Create a new sub-directory of the nominal test directory in which
    // 'nc' will create the socket file.
    String testSubDir = System.getProperty("test.dir", ".")
        + File.separator + TEST_SUB_DIR;
    Path socketTestDir = Paths.get(testSubDir);
    Files.createDirectory(socketTestDir);

    // Set the path of the socket file.
    String socketFilePath = testSubDir + File.separator
        + SOCKET_FILE_NAME;

    // Create a process which executes the nc (netcat) utility to create
    // a socket file at the indicated location.
    FileSystem fs = FileSystems.getDefault();
    try (WatchService ws = fs.newWatchService()) {
        // Watch the test sub-directory to receive notification when an
        // entry, i.e., the socket file, is added to the sub-directory.
        WatchKey wk = socketTestDir.register(ws,
                StandardWatchEventKinds.ENTRY_CREATE);

        // Execute the 'nc' command.
        proc = Runtime.getRuntime().exec(CMD_BASE + " " + socketFilePath);

        // Wait until the socket file is created.
        WatchKey key = ws.take();
        if (key != wk) {
            throw new RuntimeException("Unknown entry created - expected: "
                + wk.watchable() + ", actual: " + key.watchable());
        }
        wk.cancel();
    }

    // Verify that the socket file in fact exists.
    Path socketPath = fs.getPath(socketFilePath);
    if (!Files.exists(socketPath)) {
        throw new RuntimeException("Socket file " + socketFilePath
            + " was not created by \"nc\" command.");
    }

    // Retrieve the most recent access and modification times of the
    // socket file; print the values.
    BasicFileAttributeView attributeView = Files.getFileAttributeView(
            socketPath, BasicFileAttributeView.class);
    BasicFileAttributes oldAttributes = attributeView.readAttributes();
    FileTime oldAccessTime = oldAttributes.lastAccessTime();
    FileTime oldModifiedTime = oldAttributes.lastModifiedTime();
    System.out.println("Old times: " + oldAccessTime
        + " " + oldModifiedTime);

    // Calculate the time to which the access and modification times of the
    // socket file will be changed.
    FileTime newFileTime =
        FileTime.fromMillis(oldAccessTime.toMillis() + 1066);

    try {
        // Set the access and modification times of the socket file.
        attributeView.setTimes(newFileTime, newFileTime, null);

        // Retrieve the updated access and modification times of the
        // socket file; print the values.
        FileTime newAccessTime = null;
        FileTime newModifiedTime = null;
        BasicFileAttributes newAttributes = attributeView.readAttributes();
        newAccessTime = newAttributes.lastAccessTime();
        newModifiedTime = newAttributes.lastModifiedTime();
        System.out.println("New times: " + newAccessTime + " "
            + newModifiedTime);

        // Verify that the updated times have the expected values.
        if ((newAccessTime != null && !newAccessTime.equals(newFileTime))
            || (newModifiedTime != null
                && !newModifiedTime.equals(newFileTime))) {
            throw new RuntimeException("Failed to set correct times.");
        }
    } finally {
        // Destry the process running netcat and delete the socket file.
        proc.destroy();
        Files.delete(socketPath);
    }
}
 
Example 6
Source File: MCRFileAttributes.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
public static <T> MCRFileAttributes<T> fromAttributes(BasicFileAttributes attrs, String md5) {
    return new MCRFileAttributes<>(FileType.fromAttribute(attrs), attrs.size(), (T) attrs.fileKey(), md5,
        attrs.creationTime(), attrs.lastModifiedTime(), attrs.lastAccessTime());
}
 
Example 7
Source File: PreserveFiltersTest.java    From ecs-sync with Apache License 2.0 4 votes vote down vote up
@Test
public void testPreserveFileAttributes() throws Exception {
    // can only change ownership if root
    boolean isRoot = "root".equals(System.getProperty("user.name"));
    if (isRoot) log.warn("detected root execution");

    Integer uid = 1111, gid = 2222;
    Set<PosixFilePermission> permissions = new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ,
            PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_WRITE, PosixFilePermission.OTHERS_EXECUTE));
    String mode = "0407"; // matches permissions above

    // write 10 files
    writeTestFiles(sourceDir, 10, 10 * 1024, uid, gid, permissions);

    SyncOptions options = new SyncOptions().withThreadCount(16);

    // sync 10 files to a test target
    FilesystemConfig fsConfig = new FilesystemConfig();
    fsConfig.setPath(sourceDir.getPath());

    TestConfig testConfig = new TestConfig().withReadData(true).withDiscardData(false);

    EcsSync sync = new EcsSync();
    sync.setSyncConfig(new SyncConfig().withOptions(options).withSource(fsConfig).withTarget(testConfig)
            .withFilters(Collections.singletonList(new PreserveFileAttributesConfig())));
    sync.run();

    Assert.assertEquals(0, sync.getStats().getObjectsFailed());
    Assert.assertEquals(10, sync.getStats().getObjectsComplete());

    TestStorage testStorage = (TestStorage) sync.getTarget();

    // NOTE: new ClarityNow! DataMover spec only records to the hundredth of a second
    for (SyncObject object : testStorage.getRootObjects()) {
        File file = new File(sourceDir, object.getRelativePath());
        BasicFileAttributes attributes = Files.getFileAttributeView(file.toPath(), BasicFileAttributeView.class,
                LinkOption.NOFOLLOW_LINKS).readAttributes();
        FileTime mtime = attributes.lastModifiedTime();
        FileTime atime = attributes.lastAccessTime();
        FileTime crtime = attributes.creationTime();
        String mtimeSecs = object.getMetadata().getUserMetadataValue(PreserveFilters.META_MTIME);
        if (mtime == null) Assert.assertNull(mtimeSecs);
        else Assert.assertEquals(mtime.toMillis() / 10, (long) (Double.parseDouble(mtimeSecs) * 100D));
        String atimeSecs = object.getMetadata().getUserMetadataValue(PreserveFilters.META_ATIME);
        if (atime == null) Assert.assertNull(atimeSecs);
        else // atime is affected by reading the file times
            Assert.assertTrue(Math.abs(atime.toMillis() - (long) (Double.parseDouble(atimeSecs) * 1000D)) < 1000);
        String crtimeSecs = object.getMetadata().getUserMetadataValue(PreserveFilters.META_CRTIME);
        if (crtime == null) Assert.assertNull(crtimeSecs);
        else Assert.assertEquals(crtime.toMillis() / 10, (long) (Double.parseDouble(crtimeSecs) * 100D));

        // if possible, check ctime
        FileTime ctime = (FileTime) Files.getAttribute(file.toPath(), "unix:ctime");
        String ctimeSecs = object.getMetadata().getUserMetadataValue(PreserveFilters.META_CTIME);
        if (ctime == null) Assert.assertNull(ctimeSecs);
        else Assert.assertEquals(ctime.toMillis() / 10, (long) (Double.parseDouble(ctimeSecs) * 100D));

        // check permissions
        if (isRoot) {
            Assert.assertEquals(uid.toString(), object.getMetadata().getUserMetadataValue(PreserveFilters.META_OWNER));
            Assert.assertEquals(gid.toString(), object.getMetadata().getUserMetadataValue(PreserveFilters.META_GROUP));
        }
        Assert.assertEquals(mode, object.getMetadata().getUserMetadataValue(PreserveFilters.META_PERMISSIONS));
    }
}
 
Example 8
Source File: PreserveFiltersTest.java    From ecs-sync with Apache License 2.0 4 votes vote down vote up
@Test
public void testRestoreFileAttributes() throws Exception {
    // can only change ownership if root
    boolean isRoot = "root".equals(System.getProperty("user.name"));
    if (isRoot) log.warn("detected root execution");

    // write 10 files
    Integer uid = 1111, gid = 2222;
    Set<PosixFilePermission> permissions = new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ,
            PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_WRITE, PosixFilePermission.OTHERS_EXECUTE));

    // write 10 files
    writeTestFiles(sourceDir, 10, 10 * 1024, uid, gid, permissions);

    SyncOptions options = new SyncOptions().withThreadCount(16).withVerify(true);

    // sync files to a test target
    FilesystemConfig fsConfig = new FilesystemConfig();
    fsConfig.setPath(sourceDir.getPath());

    TestConfig testConfig = new TestConfig().withReadData(true).withDiscardData(false);

    EcsSync sync = new EcsSync();
    sync.setSyncConfig(new SyncConfig().withOptions(options).withSource(fsConfig).withTarget(testConfig)
            .withFilters(Collections.singletonList(new PreserveFileAttributesConfig())));
    sync.run();

    Assert.assertEquals(0, sync.getStats().getObjectsFailed());
    Assert.assertEquals(10, sync.getStats().getObjectsComplete());

    // wait a tick to make sure mtimes are different
    Thread.sleep(1000);

    TestStorage testStorage = (TestStorage) sync.getTarget();

    // sync from test target back to filesystem in a separate dir
    fsConfig.setPath(targetDir.getPath());

    options.setVerify(false); // verification will screw up atime
    sync = new EcsSync();
    sync.setSyncConfig(new SyncConfig().withOptions(options).withTarget(fsConfig)
            .withFilters(Collections.singletonList(new RestoreFileAttributesConfig())));
    sync.setSource(testStorage);
    sync.run();

    Assert.assertEquals(0, sync.getStats().getObjectsFailed());
    Assert.assertEquals(10, sync.getStats().getObjectsComplete());

    // NOTE: new ClarityNow! DataMover spec only records to the hundredth of a second
    for (File sourceFile : sourceDir.listFiles()) {
        File targetFile = new File(targetDir, sourceFile.getName());
        BasicFileAttributes attributes = Files.getFileAttributeView(sourceFile.toPath(),
                BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).readAttributes();
        // java's time parsing is only millisecond-accurate
        FileTime sourceMtime = FileTime.fromMillis(attributes.lastModifiedTime().toMillis());
        FileTime sourceAtime = FileTime.fromMillis(attributes.lastAccessTime().toMillis());
        FileTime sourceCrtime = FileTime.fromMillis(attributes.creationTime().toMillis());
        attributes = Files.getFileAttributeView(targetFile.toPath(),
                BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).readAttributes();
        FileTime targetMtime = attributes.lastModifiedTime();
        FileTime targetAtime = attributes.lastAccessTime();
        FileTime targetCrtime = attributes.creationTime();
        Assert.assertEquals(sourceMtime.toMillis() / 10, targetMtime.toMillis() /10);
        // atime is affected by reading the file times
        Assert.assertTrue(Math.abs(sourceAtime.toMillis() - targetAtime.toMillis()) <= 2000);
        Assert.assertEquals(sourceCrtime.toMillis() / 10, targetCrtime.toMillis() / 10);

        // check permissions
        if (isRoot) Assert.assertEquals(uid, Files.getAttribute(targetFile.toPath(), "unix:uid"));
        if (isRoot) Assert.assertEquals(gid, Files.getAttribute(targetFile.toPath(), "unix:gid"));
        Assert.assertEquals(permissions, Files.getPosixFilePermissions(targetFile.toPath()));
    }
}
 
Example 9
Source File: GetFileLastAccessTime.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void file_last_accessed_time_nio () throws IOException {

	BasicFileAttributes attr = Files.readAttributes(source, BasicFileAttributes.class);

	FileTime lastAccessed = attr.lastAccessTime();
	
	assertEquals(1390446166000l, lastAccessed.toMillis());
}