Java Code Examples for java.nio.file.Files#getLastModifiedTime()

The following examples show how to use java.nio.file.Files#getLastModifiedTime() . 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: p4ic4idea   File: SymbolicLinkHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the last modified time for a symbolic link.
 *
 * Note: symbolic links are not followed (NOFOLLOW_LINKS LinkOption)
 *
 * @param link the path to the symbolic link
 * @return last modified time of the symbolic link
 */
public static long getLastModifiedTime(String link) {
  if (nonNull(link)) {
    try {
      Path linkPath = Paths.get(link);
      if (nonNull(linkPath)) {
        FileTime fileTimeObject = Files.getLastModifiedTime(linkPath, LinkOption.NOFOLLOW_LINKS);
        if (nonNull(fileTimeObject)) {
          return fileTimeObject.toMillis();
        }
      }
    // p4ic4idea: Do not catch throwable unless you're really careful
    //} catch (Throwable thr) {
    } catch (Exception thr) {
      Log.error("Unexpected exception invoking method: %s", thr.getLocalizedMessage());
      Log.exception(thr);
    }
  }
  return 0L;
}
 
Example 2
public boolean isDirty() {
	try {
		if (!Files.exists(file)) {
			// This case occurs when user delete the XML Schema / DTD file
			return true;
		}
		FileTime currentLastModified = Files.getLastModifiedTime(file);
		if (!currentLastModified.equals(lastModified)) {
			lastModified = currentLastModified;
			return true;
		}
	} catch (IOException e) {
		LOGGER.log(Level.SEVERE, "Get last modified time failed", e);
		return true;
	}
	return false;
}
 
Example 3
Source Project: Pydev   File: ScopedPreferences.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Map<String, Object> getYamlFileContents(final File yamlFile) throws Exception {
    if (!yamlFile.exists()) {
        return null;
    }
    //Using this API to get a higher precision!
    FileTime ret = Files.getLastModifiedTime(yamlFile.toPath());
    long lastModified = ret.to(TimeUnit.NANOSECONDS);

    return getCachedYamlFileContents(yamlFile, lastModified,
            new ICallback0<Object>() {

                @Override
                public Object call() {
                    try {
                        String fileContents = FileUtils.getFileContents(yamlFile);
                        Map<String, Object> initial = getYamlFileContentsImpl(fileContents);
                        return initial;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });

}
 
Example 4
Source Project: crate   File: SslContextProviderService.java    License: Apache License 2.0 6 votes vote down vote up
public boolean didChange() throws IOException {
    FileTime lastModifiedTime = Files.getLastModifiedTime(path);
    boolean changed = false;
    if (!lastModifiedTime.equals(this.lastModifiedTime)) {
        this.lastModifiedTime = lastModifiedTime;
        changed = true;
    }
    try (var in = new BufferedChecksumStreamInput(new InputStreamStreamInput(Files.newInputStream(path)), path.toString())) {
        long checksum = in.getChecksum();
        if (checksum != this.checksum) {
            this.checksum = checksum;
            changed = true;
        }
    }
    return changed;
}
 
Example 5
Source Project: marathonv5   File: Copy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
    // fix up modification time of directory when done
    if (exc == null) {
        Path newdir = target.resolve(source.relativize(dir));
        try {
            FileTime time = Files.getLastModifiedTime(dir);
            Files.setLastModifiedTime(newdir, time);
        } catch (IOException x) {
            System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);
        }
        try {
            if (operation == Operation.CUT) {
                Files.delete(dir);
            }
        } catch (IOException e) {
            System.err.format("Unable to delete directory: %s: %s%n", newdir, e);
        }
    }
    return CONTINUE;
}
 
Example 6
Source Project: tus-java-server   File: DiskLockingService.java    License: MIT License 6 votes vote down vote up
@Override
public void cleanupStaleLocks() throws IOException {
    try (DirectoryStream<Path> locksStream = Files.newDirectoryStream(getStoragePath())) {
        for (Path path : locksStream) {

            FileTime lastModifiedTime = Files.getLastModifiedTime(path);
            if (lastModifiedTime.toMillis() < System.currentTimeMillis() - 10000L) {
                UploadId id = new UploadId(path.getFileName().toString());

                if (!isLocked(id)) {
                    Files.deleteIfExists(path);
                }
            }

        }
    }
}
 
Example 7
private boolean isTooOld(Path p, long max) {
  FileTime ft;
  try {
    ft = Files.getLastModifiedTime(p);
  } catch (IOException e) {
    log.error("Cannot get LastModifiedTime", e);
    return false;
  }
  return ft.toMillis() < max;
}
 
Example 8
Source Project: Java-Coding-Problems   File: CopyFileVisitor.java    License: MIT License 5 votes vote down vote up
@Override
public FileVisitResult postVisitDirectory(Object dir, IOException ioe) throws IOException {
    
    Path newDir = copyTo.resolve(copyFrom.relativize((Path) dir));
    try {
        FileTime time = Files.getLastModifiedTime((Path) dir);
        Files.setLastModifiedTime(newDir, time);
    } catch (IOException e) {
        System.err.println("Unable to preserve the time attribute to: " + newDir + " [" + e + "]");
    }

    return FileVisitResult.CONTINUE;
}
 
Example 9
Source Project: helidon-build-tools   File: FileUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the last modified time of the given file.
 *
 * @param file The file.
 * @return The last modified time.
 */
public static FileTime lastModifiedTime(Path file) {
    try {
        return Files.getLastModifiedTime(file);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 10
private void setFileMetaData(RuleProvider ruleProvider)
{
    if (ruleProvider.getOrigin() == null)
        return;

    try
    {
        String filePathString = ruleProvider.getOrigin();

        if (filePathString.startsWith("file:"))
            filePathString = filePathString.substring(5);

        Path filePath = Paths.get(filePathString);
        if (!Files.isRegularFile(filePath))
            return;

        FileTime lastModifiedTime = Files.getLastModifiedTime(Paths.get(filePathString));
        GregorianCalendar lastModifiedCalendar = new GregorianCalendar();
        lastModifiedCalendar.setTimeInMillis(lastModifiedTime.toMillis());
        ruleProvider.setDateModified(lastModifiedCalendar);

        // TODO: Can we still find the rules path in order to get the relative path?
        // filePath = Paths.get(ruleProvider.getRulesPath().getPath()).relativize(Paths.get(filePathString));
        ruleProvider.setOrigin(filePath.toString());
    }
    catch (Exception e)
    {
        // not a file path... ignore
    }
}
 
Example 11
Source Project: j2cl   File: FileCache.java    License: Apache License 2.0 5 votes vote down vote up
private T get() {
  // Note that the method is not syncronized and it is ok to calculate cached object twice in
  // case of unlike event of a race condition.
  try {
    FileTime newLastModified = Files.getLastModifiedTime(path);
    if (!newLastModified.equals(lastModified)) {
      cached = fn.apply(path);
      lastModified = newLastModified;
    }
    return cached;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 12
Source Project: Pydev   File: FileStub.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public long getModificationStamp() {
    try {
        FileTime ret = Files.getLastModifiedTime(this.file.toPath());
        return ret.to(TimeUnit.NANOSECONDS);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 13
Source Project: pulsar   File: FileModifiedTimeUpdater.java    License: Apache License 2.0 5 votes vote down vote up
private FileTime updateLastModifiedTime() {
    if (fileName != null) {
        Path p = Paths.get(fileName);
        try {
            return Files.getLastModifiedTime(p);
        } catch (IOException e) {
            LOG.error("Unable to fetch lastModified time for file {}: ", fileName, e);
        }
    }
    return null;
}
 
Example 14
Source Project: io   File: DcFixedWindowRollingPolicy.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * アーカイブされているログが最大保持世代数のときに最古の アーカイブログを削除する.
 * @param parent アーカイブログが格納されているディレクトリの親ディレクトリを示すオブジェクト
 */
private void removeOldestArchiveLog(File parent) {
    // アーカイブファイル数が保持世代(12世代)を超える場合は、最古のファイルを削除する
    File[] files = parent.listFiles();
    File oldest = null;
    FileTime oldestTime = null;
    if (files.length >= maxIndex - minIndex + 1) {
        for (File archive : files) {
            if (null == oldest) {
                oldest = archive;
            } else {
                try {
                    FileTime archiveTime = Files.getLastModifiedTime(archive.toPath());
                    oldestTime = Files.getLastModifiedTime(oldest.toPath());
                    if (archiveTime.toMillis() < oldestTime.toMillis()) {
                        oldest = archive;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (null != oldest && oldest.exists()) {
            logger.info("olddest archive file will be deleted.");
            logger.info("oldestFile Name: " + oldest.getPath() + ", timestamp: " + oldestTime.toMillis());
            logger.info("number of existing files:" + files.length + ", max number of files: "
                    + (maxIndex - minIndex + 1));
            if (oldest.delete()) {
                logger.warn("Failed to oldest archive file: " + oldest.getPath());
            }
        }
    }
}
 
Example 15
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) {
  // fix up modification time of directory when done
  if (exc == null) {
    final Path newdir = target.resolve(source.relativize(dir));
    try {
      final FileTime time = Files.getLastModifiedTime(dir);
      Files.setLastModifiedTime(newdir, time);
    } catch (final IOException ioException) {
      System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, ioException);
    }
  }
  return CONTINUE;
}
 
Example 16
Source Project: knox   File: HadoopXmlResourceMonitor.java    License: Apache License 2.0 5 votes vote down vote up
private void monitorClouderaManagerDescriptor(Path clouderaManagerDescriptorFile, String topologyName) {
  try {
    if (Files.isReadable(clouderaManagerDescriptorFile)) {
      final FileTime lastModifiedTime = Files.getLastModifiedTime(clouderaManagerDescriptorFile);
      if (topologyName != null || lastReloadTime == null || lastReloadTime.compareTo(lastModifiedTime) < 0) {
        lastReloadTime = lastModifiedTime;
        processClouderaManagerDescriptor(clouderaManagerDescriptorFile.toString(), topologyName);
      }
    } else {
      LOG.failedToMonitorHadoopXmlResource(clouderaManagerDescriptorFile.toString(), "File is not readable!", null);
    }
  } catch (IOException e) {
    LOG.failedToMonitorHadoopXmlResource(clouderaManagerDescriptorFile.toString(), e.getMessage(), e);
  }
}
 
Example 17
@Test
public void testFileChangeThatDoesNotModifyAbiAvoidsRebuild() throws IOException {
  setUpProjectWorkspaceForScenario("rulekey_changed_while_abi_stable");

  // Run `buck build`.
  BuildTarget bizTarget = BuildTargetFactory.newInstance("//:biz");
  BuildTarget utilTarget = BuildTargetFactory.newInstance("//:util");
  ProcessResult buildResult =
      workspace.runBuckCommand("build", bizTarget.getFullyQualifiedName());
  buildResult.assertSuccess("Successful build should exit with 0.");

  Path utilOutputPath =
      BuildTargetPaths.getGenPath(
          workspace.getProjectFileSystem(),
          utilTarget,
          "lib__%s__output/" + utilTarget.getShortName() + ".jar");
  long utilJarSize = Files.size(workspace.getPath(utilOutputPath));
  Path bizOutputPath =
      BuildTargetPaths.getGenPath(
          workspace.getProjectFileSystem(),
          bizTarget,
          "lib__%s__output/" + bizTarget.getShortName() + ".jar");
  FileTime bizJarLastModified = Files.getLastModifiedTime(workspace.getPath(bizOutputPath));

  // TODO(mbolin): Run uber-biz.jar and verify it prints "Hello World!\n".

  // Edit Util.java in a way that does not affect its ABI.
  workspace.replaceFileContents("Util.java", "Hello World", "Hola Mundo");

  // Run `buck build` again.
  ProcessResult buildResult2 = workspace.runBuckCommand("build", "//:biz");
  buildResult2.assertSuccess("Successful build should exit with 0.");

  workspace.getBuildLog().assertTargetBuiltLocally(utilTarget);
  workspace.getBuildLog().assertTargetHadMatchingInputRuleKey(bizTarget);

  assertThat(
      "util.jar should have been rewritten, so its file size should have changed.",
      utilJarSize,
      not(equalTo(Files.size(workspace.getPath(utilOutputPath)))));
  assertEquals(
      "biz.jar should not have been rewritten, so its last-modified time should be the same.",
      bizJarLastModified,
      Files.getLastModifiedTime(workspace.getPath(bizOutputPath)));

  // TODO(mbolin): Run uber-biz.jar and verify it prints "Hola Mundo!\n".

  // TODO(mbolin): This last scenario that is being tested would be better as a unit test.
  // Run `buck build` one last time. This ensures that a dependency java_library() rule (:util)
  // that is built via BuildRuleSuccess.Type.MATCHING_INPUT_BASED_RULE_KEY does not
  // explode when its dependent rule (:biz) invokes the dependency's getAbiKey() method as part of
  // its own getAbiKeyForDeps().
  ProcessResult buildResult3 = workspace.runBuckCommand("build", "//:biz");
  buildResult3.assertSuccess("Successful build should exit with 0.");
}
 
Example 18
/**
 * 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 19
@Test
public void testAddArtifact() throws IOException, URISyntaxException, LayoutException
{
    ManagedRepository repo = createManagedRepoWithContent( "delete-repository" );
    ManagedRepositoryContent myRepoContent = repo.getContent( );
    BaseRepositoryContentLayout layout = myRepoContent.getLayout( BaseRepositoryContentLayout.class );
    Path repoRoot = repo.getRoot().getFilePath( );

    Path tmpFile = Files.createTempFile( "archiva-mvn-repotest", "jar" );
    try( OutputStream outputStream = Files.newOutputStream( tmpFile ))
    {
        for ( int i = 0; i < 255; i++ )
        {
            outputStream.write( "test.test.test\n".getBytes( Charset.forName( "UTF-8" ) ) );
        }
    }

    Path file = repoRoot.resolve( "org/apache/maven/samplejar/2.0/samplejar-2.0.jar" );
    FileTime lmt = Files.getLastModifiedTime( file );
    ArchivaItemSelector selector = ArchivaItemSelector.builder( )
        .withNamespace( "org.apache.maven" )
        .withProjectId( "samplejar" )
        .withVersion( "2.0" )
        .withArtifactId( "samplejar" )
        .withArtifactVersion( "2.0" )
        .withExtension( "jar" )
        .build( );
    Artifact artifact = layout.getArtifact( selector );
    layout.addArtifact( tmpFile, artifact );
    FileTime lmtAfter = Files.getLastModifiedTime( file );
    assertNotEquals( lmtAfter, lmt );
    Reader ln = Files.newBufferedReader( file, Charset.forName( "UTF-8" ) );
    char[] content = new char[50];
    ln.read( content );
    assertTrue( new String( content ).startsWith( "test.test.test" ) );

    tmpFile = Files.createTempFile( "archiva-mvn-repotest", "jar" );
    try( OutputStream outputStream = Files.newOutputStream( tmpFile ))
    {
        for ( int i = 0; i < 255; i++ )
        {
            outputStream.write( "test.test.test\n".getBytes( Charset.forName( "UTF-8" ) ) );
        }
    }
    file = repoRoot.resolve( "org/apache/maven/samplejar/2.0/samplejar-2.0.test" );
    assertFalse( Files.exists( file ) );
    assertTrue( Files.exists( tmpFile ) );
    selector = ArchivaItemSelector.builder( )
        .withNamespace( "org.apache.maven" )
        .withProjectId( "samplejar" )
        .withVersion( "2.0" )
        .withArtifactId( "samplejar" )
        .withArtifactVersion( "2.0" )
        .withExtension( "test" )
        .build( );
    artifact = layout.getArtifact( selector );
    layout.addArtifact( tmpFile, artifact );
    ln = Files.newBufferedReader( file, Charset.forName( "UTF-8" ) );
    ln.read( content );
    assertTrue( new String( content ).startsWith( "test.test.test" ) );
}
 
Example 20
Source Project: jsr203-hadoop   File: TestFiles.java    License: Apache License 2.0 3 votes vote down vote up
@Test
public void testGetLastModifiedTime() throws IOException {
  Path rootPath = Paths.get(clusterUri);

  FileTime ft = Files.getLastModifiedTime(rootPath);

  assertNotNull(ft);

}