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

The following examples show how to use java.nio.file.attribute.BasicFileAttributes#creationTime() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: jesterj   File: FileScanner.java    License: 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
protected FileTime determineTime(Path path) {
    FileTime result = FileTime.fromMillis(0);
    try {
        BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
        FileTime creationTime = attributes.creationTime();
        if (creationTime.equals(result)) {
            // file system doesn't support creation time and didn't give modification time automatically
            result = attributes.lastModifiedTime();
        } else {
            result = creationTime;
        }
    } catch (IOException e) {
        // ignore
    }
    return result;
}
 
Example 3
FileTime getDriverCreationTime(String driver) {
    for (File file : mojo.installationDirectory.listFiles()) {
        if (file.getName().equals(driver)) {
            BasicFileAttributes attr = null;
            try {
                attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            } catch (IOException e) {
                fail("Did not find driver creation time for driver " + driver + " since driver file or folder is not installed"
                     + System.lineSeparator() + Utils.debugInfo(mojo));
            }
            return attr.creationTime();
        }
    }
    fail("Did not find driver creation time for driver " + driver + " since driver file or folder is not installed"
         + System.lineSeparator() + Utils.debugInfo(mojo));
    return null;
}
 
Example 4
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 Project: camel-spring-boot   File: BOMResolver.java    License: Apache License 2.0 5 votes vote down vote up
private boolean canUseCache() throws IOException {
    if (CACHE_FILE.exists()) {
        BasicFileAttributes attr = Files.readAttributes(CACHE_FILE.toPath(), BasicFileAttributes.class);
        FileTime fileTime = attr != null ? attr.creationTime() : null;
        Long time = fileTime != null ? fileTime.toMillis() : null;
        // Update the cache every day
        return time != null && time.compareTo(System.currentTimeMillis() - 1000 * 60 * 60 * 24) > 0;
    }

    return false;
}
 
Example 6
private long getCreationTime(File file) {
    try {
        BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
        FileTime fileTime = attr.creationTime();
        return fileTime.toMillis();
    } catch (IOException e) {
        LOGGER.error("", e);
        // handle exception
        return 0l;
    }
}
 
Example 7
Source Project: tutorials   File: CreationDateResolver.java    License: MIT License 5 votes vote down vote up
public Instant resolveCreationTimeWithBasicAttributes(Path path) {
    try {
        final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
        final FileTime fileTime = attr.creationTime();

        return fileTime.toInstant();
    } catch (IOException ex) {
        throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
    }
}
 
Example 8
@Test
public void testView() throws IOException {
  BasicFileAttributeView view = provider.view(fileLookup(), NO_INHERITED_VIEWS);

  assertThat(view).isNotNull();
  assertThat(view.name()).isEqualTo("basic");

  BasicFileAttributes attrs = view.readAttributes();
  assertThat(attrs.fileKey()).isEqualTo(0);

  FileTime time = attrs.creationTime();
  assertThat(attrs.lastAccessTime()).isEqualTo(time);
  assertThat(attrs.lastModifiedTime()).isEqualTo(time);

  view.setTimes(null, null, null);

  attrs = view.readAttributes();
  assertThat(attrs.creationTime()).isEqualTo(time);
  assertThat(attrs.lastAccessTime()).isEqualTo(time);
  assertThat(attrs.lastModifiedTime()).isEqualTo(time);

  view.setTimes(FileTime.fromMillis(0L), null, null);

  attrs = view.readAttributes();
  assertThat(attrs.creationTime()).isEqualTo(time);
  assertThat(attrs.lastAccessTime()).isEqualTo(time);
  assertThat(attrs.lastModifiedTime()).isEqualTo(FileTime.fromMillis(0L));
}
 
Example 9
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 10
Source Project: ecs-sync   File: PreserveFiltersTest.java    License: 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 11
Source Project: ecs-sync   File: PreserveFiltersTest.java    License: 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 12
Source Project: cloudstack   File: DiagnosticsHelper.java    License: Apache License 2.0 4 votes vote down vote up
public static Long getFileCreationTime(File file) throws IOException {
    Path p = Paths.get(file.getAbsolutePath());
    BasicFileAttributes view = Files.getFileAttributeView(p, BasicFileAttributeView.class).readAttributes();
    FileTime fileTime = view.creationTime();
    return fileTime.toMillis();
}
 
Example 13
private final synchronized void loadMetadataIfNecessary()
{
    if (cachedMetadata == null)
    {
        cachedMetadata   = metadataLoader.loadMetadata(metadataReference);
        contentIsInPlace = false;

        if (contentReference != null)
        {
            try
            {
                final Path                path       = contentReference.toPath();
                final BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);

                // If not set in the metadata file, set the creation timestamp to what's on disk
                if (!cachedMetadata.getProperties().containsKey(ContentModel.PROP_CREATED.toString()) &&
                    !cachedMetadata.getProperties().containsKey(ContentModel.PROP_CREATED.toPrefixString(namespaceService)) &&
                    attributes.creationTime() != null)
                {
                    final Date created = new Date(attributes.creationTime().toMillis());
                    cachedMetadata.addProperty(ContentModel.PROP_CREATED.toString(), created);
                }

                // If not set in the metadata file, set the modification timestamp to what's on disk
                if (!cachedMetadata.getProperties().containsKey(ContentModel.PROP_MODIFIED.toString()) &&
                    !cachedMetadata.getProperties().containsKey(ContentModel.PROP_MODIFIED.toPrefixString(namespaceService)) &&
                    attributes.lastModifiedTime() != null)
                {
                    final Date modified = new Date(attributes.lastModifiedTime().toMillis());
                    cachedMetadata.addProperty(ContentModel.PROP_MODIFIED.toString(), modified);
                }

                // If an in-place import is possible, attempt to construct a content URL
                if (!contentReference.isDirectory() && isInContentStore(configuredContentStore, contentReference))
                {
                    final ContentData contentData = buildContentProperty(mimeTypeService, configuredContentStore, contentReference);

                    if (contentData != null)
                    {
                        // We have valid in-place content
                        contentIsInPlace = true;
                        cachedMetadata.addProperty(ContentModel.PROP_CONTENT.toString(), contentData);
                    }
                    else
                    {
                        if (warn(FilesystemBulkImportItem.log)) warn (FilesystemBulkImportItem.log, "Unable to in-place import '" + getFileName(contentReference) + "'. Will stream it instead.");
                    }
                }
            }
            catch (final IOException ioe)
            {
                // Not much we can do in this case - log it and keep on truckin'
                if (warn(FilesystemBulkImportItem.log)) warn(FilesystemBulkImportItem.log, "Unable to read file attributes for " + contentReference.getAbsolutePath() + ". Creation and modification timestamps will be system generated.", ioe);
            }
        }
    }
}
 
Example 14
/**
 * Read further documentation to determine if your file system supports creation time.
 * 
 * @throws IOException
 */
@Test
public void file_creation_time () throws IOException {

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

	FileTime fileCreated = attr.creationTime();
	
	assertEquals(1389290887000l, fileCreated.toMillis());
}