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

The following examples show how to use java.nio.file.attribute.FileTime#fromMillis() . 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: ITUpdateMetadata.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleSync() throws IOException {
	App app = new App();
	app.sync(options);
	sleep();
	assertThat(googleDriveAdapter.listAll().size(), is(1));
	assertThat(googleDriveAdapter.search(Optional.of("file.bin")).size(), is(1));
	long newMillis = System.currentTimeMillis() + 1000;
	FileTime newTimestamp = FileTime.fromMillis(newMillis);
	Files.setLastModifiedTime(Paths.get(basePathTestData(), TEST_DATA_UP, "file.bin"), newTimestamp);
	app.sync(options);
	assertThat(googleDriveAdapter.search(Optional.of("file.bin")).get(0).getModifiedTime().getValue(), is(newMillis));
}
 
Example 2
Source File: SetLastModifiedTime.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Exercise Files.setLastModifiedTime on the given file
 */
void test(Path path) throws Exception {
    FileTime now = Files.getLastModifiedTime(path);
    FileTime zero = FileTime.fromMillis(0L);

    Path result = Files.setLastModifiedTime(path, zero);
    assertTrue(result == path);
    assertEquals(Files.getLastModifiedTime(path), zero);

    result = Files.setLastModifiedTime(path, now);
    assertTrue(result == path);
    assertEquals(Files.getLastModifiedTime(path), now);
}
 
Example 3
Source File: IfLastModifiedTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoesNotAcceptIfFileAgeLessThanDuration() {
    final IfLastModified filter = IfLastModified.createAgeCondition(Duration.parse("PT33S"));
    final DummyFileAttributes attrs = new DummyFileAttributes();
    final long age = 33 * 1000 - 5;
    attrs.lastModified = FileTime.fromMillis(System.currentTimeMillis() - age);
    assertFalse(filter.accept(null, null, attrs));
}
 
Example 4
Source File: UnixAttributeProvider.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object get(File file, String attribute) {
  switch (attribute) {
    case "uid":
      UserPrincipal user = (UserPrincipal) file.getAttribute("owner", "owner");
      return getUniqueId(user);
    case "gid":
      GroupPrincipal group = (GroupPrincipal) file.getAttribute("posix", "group");
      return getUniqueId(group);
    case "mode":
      Set<PosixFilePermission> permissions =
          (Set<PosixFilePermission>) file.getAttribute("posix", "permissions");
      return toMode(permissions);
    case "ctime":
      return FileTime.fromMillis(file.getCreationTime());
    case "rdev":
      return 0L;
    case "dev":
      return 1L;
    case "ino":
      return file.id();
    case "nlink":
      return file.links();
    default:
      return null;
  }
}
 
Example 5
Source File: ImmortalDappModule.java    From AVM with MIT License 5 votes vote down vote up
/**
 * Create the in-memory JAR containing all the classes in this module.
 */
public byte[] createJar(long blockTimeStamp) throws IOException {
    // set jar file timestamp to block timestamp so the whole network is in agreement over this.
    FileTime timestamp = FileTime.fromMillis(blockTimeStamp);

    // manifest, we explicitly write it so that can can control its timestamps.
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, this.mainClass);

    ZipEntry manifestEntry = new ZipEntry(JarFile.MANIFEST_NAME);
    manifestEntry.setLastModifiedTime(timestamp);
    manifestEntry.setLastAccessTime(timestamp);
    manifestEntry.setCreationTime(timestamp);

    // Create a temporary memory location for this JAR.
    ByteArrayOutputStream tempJarStream = new ByteArrayOutputStream(MAX_JAR_BYTES);

    // create the jar file
    try (JarOutputStream target = new JarOutputStream(tempJarStream)) {
        // first, write the manifest file
        target.putNextEntry(manifestEntry);
        manifest.write(target);
        target.closeEntry();

        // add the classes
        for (String clazz : this.classes.keySet()) {
            JarEntry entry = new JarEntry(clazz.replace('.', '/') + ".class");
            entry.setLastModifiedTime(timestamp);
            entry.setLastAccessTime(timestamp);
            entry.setCreationTime(timestamp);
            target.putNextEntry(entry);
            target.write(this.classes.get(clazz));
            target.closeEntry();
        }
    }
    return tempJarStream.toByteArray();
}
 
Example 6
Source File: ZipFileAttributes.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Override
public FileTime lastModifiedTime() {
    return FileTime.fromMillis(e.mtime);
}
 
Example 7
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 8
Source File: ZipFileAttributes.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public FileTime lastModifiedTime() {
    return FileTime.fromMillis(e.mtime);
}
 
Example 9
Source File: ZipFileAttributes.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public FileTime lastModifiedTime() {
    return FileTime.fromMillis(e.mtime);
}
 
Example 10
Source File: ZipFileAttributes.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public FileTime lastAccessTime() {
    if (e.atime != -1)
        return FileTime.fromMillis(e.atime);
    return null;
}
 
Example 11
Source File: ZipFileAttributes.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Override
public FileTime lastAccessTime() {
    if (e.atime != -1)
        return FileTime.fromMillis(e.atime);
    return null;
}
 
Example 12
Source File: ZipFileAttributes.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public FileTime lastModifiedTime() {
    return FileTime.fromMillis(e.mtime);
}
 
Example 13
Source File: ZipFileAttributes.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public FileTime lastAccessTime() {
    if (e.atime != -1)
        return FileTime.fromMillis(e.atime);
    return null;
}
 
Example 14
Source File: HadoopFileStatusWrapper.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public FileTime lastModifiedTime() {
  return FileTime.fromMillis(status.getModificationTime());
}
 
Example 15
Source File: JarBuilderTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testDoesNotLeakJarFileHandles() throws Exception {
  File toTest = temporaryFolder.newFile();
  File modification = temporaryFolder.newFile();
  try (TestJarEntryContainer container1 = new TestJarEntryContainer("Container1");
      TestJarEntryContainer container2 = new TestJarEntryContainer("Container2")) {
    new JarBuilder()
        .addEntryContainer(container1.addEntry("Before", "Before"))
        .setShouldHashEntries(true)
        .createJarFile(toTest.toPath());
    new JarBuilder()
        .addEntryContainer(container2.addEntry("After", "After"))
        .setShouldHashEntries(true)
        .createJarFile(modification.toPath());
  }

  FileTime hardcodedTime = FileTime.fromMillis(ZipConstants.getFakeTime());
  Files.setLastModifiedTime(toTest.toPath(), hardcodedTime);
  Files.setLastModifiedTime(modification.toPath(), hardcodedTime);

  // Use JarBuilder with toTest
  File outputFile = temporaryFolder.newFile();
  new JarBuilder()
      .setEntriesToJar(ImmutableList.of(toTest.toPath()))
      .setShouldHashEntries(true)
      .setShouldMergeManifests(true)
      .createJarFile(outputFile.toPath());
  // assert the jar was created
  assertTrue(Files.exists(outputFile.toPath()));

  // Now modify toTest make sure we don't get a cached result when we open it for a second time
  Files.move(modification.toPath(), toTest.toPath(), StandardCopyOption.REPLACE_EXISTING);
  Files.setLastModifiedTime(toTest.toPath(), hardcodedTime);

  Map<String, Attributes> entries = new JarFile(toTest).getManifest().getEntries();
  // If we leaked the file handle for toTest from within JarBuilder then we will see
  // stale data here (or a crash) and the manifest
  // will incorrectly return "Before" instead of "After"
  // See item (3) of https://bugs.openjdk.java.net/browse/JDK-8142508 for some info
  assertThat(entries.keySet(), Matchers.contains("After"));
}
 
Example 16
Source File: ZipFileAttributes.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Override
public FileTime creationTime() {
    if (e.ctime != -1)
        return FileTime.fromMillis(e.ctime);
    return null;
}
 
Example 17
Source File: MTGPath.java    From MtgDesktopCompanion with GNU General Public License v3.0 4 votes vote down vote up
public BasicFileAttributes readAttributes() {
	return new BasicFileAttributes() {
		
		@Override
		public long size() {
			return 0;
		}
		
		@Override
		public FileTime lastModifiedTime() {
			return FileTime.fromMillis(new Date().getTime());
		}
		
		@Override
		public FileTime lastAccessTime() {
			return FileTime.fromMillis(new Date().getTime());
		}
		
		@Override
		public boolean isSymbolicLink() {
			return false;
		}
		
		@Override
		public boolean isRegularFile() {
			return isCard();
		}
		
		@Override
		public boolean isOther() {
			return false;
		}
		
		@Override
		public boolean isDirectory() {
			return !isRegularFile();
		}
		
		@Override
		public Object fileKey() {
			return null;
		}
		
		@Override
		public FileTime creationTime() {
			return FileTime.fromMillis(new Date().getTime());
		}
	};
}
 
Example 18
Source File: ZipFileAttributes.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public FileTime lastModifiedTime() {
    return FileTime.fromMillis(e.mtime);
}
 
Example 19
Source File: ZipFileAttributes.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public FileTime lastModifiedTime() {
    return FileTime.fromMillis(e.mtime);
}
 
Example 20
Source File: FileStatusWrapper.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public FileTime lastAccessTime() {
  return FileTime.fromMillis(status.getAccessTime());
}