Java Code Examples for java.nio.file.attribute.FileTime

The following examples show how to use java.nio.file.attribute.FileTime. 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 check out the related API usage on the sidebar.
Example 1
Source Project: n4js   Source File: CommandRebuildTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/** Expectation is that files '.n4js.projectstate' and 'src-gen/Module.js' are changed due to rebuild action. */
@Test
public void testCommandRebuild() throws Exception {
	test("class A { foo(a: A) { } } class Main { main(a: A) { a.foo(null); } }");

	// send command under test
	ExecuteCommandParams cmdCleanParams = new ExecuteCommandParams(N4JSCommandService.N4JS_REBUILD,
			Collections.emptyList());
	CompletableFuture<Object> future = languageServer.executeCommand(cmdCleanParams);
	future.join();

	// wait for previous command to finish
	joinServerRequests();

	// evaluate
	assertNoIssues();
	FileTime prjStateTime = Files.readAttributes(prjStatePath, BasicFileAttributes.class).lastModifiedTime();
	FileTime genFileTime = Files.readAttributes(genFileStatePath, BasicFileAttributes.class).lastModifiedTime();
	assertNotEquals(FILE_TIME_MILLISECONDS, prjStateTime.toMillis());
	assertNotEquals(FILE_TIME_MILLISECONDS, genFileTime.toMillis());
}
 
Example 2
Source Project: buck   Source File: WorkspaceGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void workspaceIsNotRewrittenIfContentsHaveNotChanged() throws IOException {
  {
    generator.addFilePath(Paths.get("./Project.xcodeproj"));
    clock.setCurrentTimeMillis(49152);
    Path workspacePath = generator.writeWorkspace();
    assertThat(
        projectFilesystem.getLastModifiedTime(workspacePath.resolve("contents.xcworkspacedata")),
        equalTo(FileTime.fromMillis(49152L)));
  }

  {
    WorkspaceGenerator generator2 =
        new WorkspaceGenerator(projectFilesystem, "ws", Paths.get("."));
    generator2.addFilePath(Paths.get("./Project.xcodeproj"));
    clock.setCurrentTimeMillis(64738);
    Path workspacePath2 = generator2.writeWorkspace();
    assertThat(
        projectFilesystem.getLastModifiedTime(workspacePath2.resolve("contents.xcworkspacedata")),
        equalTo(FileTime.fromMillis(49152L)));
  }
}
 
Example 3
static void testTimeConversions(long from, long to, long step) {
    ZipEntry ze = new ZipEntry("TestExtraTime.java");
    for (long time = from; time <= to; time += step) {
        ze.setTime(time);
        FileTime lastModifiedTime = ze.getLastModifiedTime();
        if (lastModifiedTime.toMillis() != time) {
            throw new RuntimeException("setTime should make getLastModifiedTime " +
                    "return the specified instant: " + time +
                    " got: " + lastModifiedTime.toMillis());
        }
        if (ze.getTime() != time) {
            throw new RuntimeException("getTime after setTime, expected: " +
                    time + " got: " + ze.getTime());
        }
    }
}
 
Example 4
Source Project: turbine   Source File: ZipTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void attributes() throws Exception {
  Path path = temporaryFolder.newFile("test.jar").toPath();
  Files.delete(path);
  try (FileSystem fs =
      FileSystems.newFileSystem(
          URI.create("jar:" + path.toUri()), ImmutableMap.of("create", "true"))) {
    for (int i = 0; i < 3; i++) {
      String name = "entry" + i;
      byte[] bytes = name.getBytes(UTF_8);
      Path entry = fs.getPath(name);
      Files.write(entry, bytes);
      Files.setLastModifiedTime(entry, FileTime.fromMillis(0));
    }
  }
  assertThat(actual(path)).isEqualTo(expected(path));
}
 
Example 5
Source Project: helidon-build-tools   Source File: FileUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that the given file exists, and update the modified time if it does.
 *
 * @param file The file.
 * @return The file.
 */
public static Path touch(Path file) {
    if (Files.exists(file)) {
        final long currentTime = System.currentTimeMillis();
        final long lastModified = lastModifiedSeconds(file);
        final long lastModifiedPlusOneSecond = lastModified + 1000;
        final long newTime = Math.max(currentTime, lastModifiedPlusOneSecond);
        try {
            Files.setLastModifiedTime(file, FileTime.fromMillis(newTime));
            return file;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    } else {
        return ensureFile(file);
    }
}
 
Example 6
Source Project: jesterj   Source 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 7
static void check(FileTime mtime, FileTime atime, FileTime ctime,
                  ZipEntry ze, byte[] extra) {
    /*
    System.out.printf("    mtime [%tc]: [%tc]/[%tc]%n",
                      mtime.to(TimeUnit.MILLISECONDS),
                      ze.getTime(),
                      ze.getLastModifiedTime().to(TimeUnit.MILLISECONDS));
     */
    if (mtime.to(TimeUnit.SECONDS) !=
        ze.getLastModifiedTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing mtime failed!");
    if (atime != null &&
        atime.to(TimeUnit.SECONDS) !=
        ze.getLastAccessTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing atime failed!");
    if (ctime != null &&
        ctime.to(TimeUnit.SECONDS) !=
        ze.getCreationTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing ctime failed!");
    if (extra != null) {
        // if extra data exists, the current implementation put it at
        // the end of the extra data array (implementation detail)
        byte[] extra1 = ze.getExtra();
        if (extra1 == null || extra1.length < extra.length ||
            !Arrays.equals(Arrays.copyOfRange(extra1,
                                              extra1.length - extra.length,
                                              extra1.length),
                           extra)) {
            throw new RuntimeException("Timestamp: storing extra field failed!");
        }
    }
}
 
Example 8
Source Project: AuthMeReloaded   Source File: GeoIpService.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Downloads the archive to the destination file if it's newer than the locally version.
 *
 * @param lastModified modification timestamp of the already present file
 * @param destination save file
 * @return null if no updates were found, the MD5 hash of the downloaded archive if successful
 * @throws IOException if failed during downloading and writing to destination file
 */
private String downloadDatabaseArchive(Instant lastModified, Path destination) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(ARCHIVE_URL).openConnection();

    String clientId = settings.getProperty(ProtectionSettings.MAXMIND_API_CLIENT_ID);
    String licenseKey = settings.getProperty(ProtectionSettings.MAXMIND_API_LICENSE_KEY);
    if (clientId.isEmpty() || licenseKey.isEmpty()) {
        logger.warning("No MaxMind credentials found in the configuration file!"
            + " GeoIp protections will be disabled.");
        return null;
    }
    String basicAuth = "Basic " + new String(Base64.getEncoder().encode((clientId + ":" + licenseKey).getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);

    if (lastModified != null) {
        // Only download if we actually need a newer version - this field is specified in GMT zone
        ZonedDateTime zonedTime = lastModified.atZone(ZoneId.of("GMT"));
        String timeFormat = DateTimeFormatter.RFC_1123_DATE_TIME.format(zonedTime);
        connection.addRequestProperty("If-Modified-Since", timeFormat);
    }

    if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
        //we already have the newest version
        connection.getInputStream().close();
        return null;
    }

    String hash = connection.getHeaderField("X-Database-MD5");
    String rawModifiedDate = connection.getHeaderField("Last-Modified");
    Instant modifiedDate = Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(rawModifiedDate));
    Files.copy(connection.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING);
    Files.setLastModifiedTime(destination, FileTime.from(modifiedDate));
    return hash;
}
 
Example 9
Source Project: ParallelGit   Source File: BasicFileAttributeViewTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getLastAccessTimeAttributeOfFile_shouldReturnEpoch() throws IOException {
  writeToCache("/file.txt");
  commitToMaster();
  initGitFileSystem();

  GfsFileAttributeView.Basic view = provider.getFileAttributeView(gfs.getPath("/file.txt"), GfsFileAttributeView.Basic.class);
  assertNotNull(view);
  assertEquals(FileTime.fromMillis(0), readAttribute(view, GfsFileAttributeView.Basic.LAST_ACCESS_TIME_NAME));
}
 
Example 10
@Test
void testChangedSinceClassFileNotChecked() {
    FileTime initial = changedTime(TIME_ZERO, LATEST);
    FileTime touched = touchFile(classFile);

    // We should not find the class change since the filter won't allow visiting the target dir
    Optional<FileTime> found = MavenProjectSupplier.changedSince(rootDir, initial, LATEST);
    assertThat(found.isPresent(), is(false));

    // Re-check that it is found without filter
    found = FileUtils.changedSince(rootDir, initial, d -> true, f -> true, LATEST);
    assertThat(found.isPresent(), is(true));
    assertThat(found.get(), is(touched));
}
 
Example 11
Source Project: component-runtime   Source File: Container.java    License: Apache License 2.0 5 votes vote down vote up
private void visitLastModified(final Path f) {
    long lastModified;
    try {
        final FileTime lastModifiedTime = Files.getLastModifiedTime(f);
        lastModified = lastModifiedTime.toMillis();
    } catch (final IOException e) {
        lastModified = f.toFile().lastModified();
    }
    if (lastModified > 0 && new Date(lastModified).compareTo(lastModifiedTimestamp.get()) > 0) {
        lastModifiedTimestamp.set(new Date(lastModified));
    }
}
 
Example 12
Source Project: openjdk-jdk8u-backup   Source File: Basic.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void ts(Instant instant, String expected) {
    String result = FileTime.from(instant).toString();
    if (!result.equals(expected)) {
        System.err.format("FileTime.from(%s).toString() failed\n", instant);
        System.err.format("Expected: %s\n", expected);
        System.err.format("     Got: %s\n", result);
        throw new RuntimeException();
    }
}
 
Example 13
Source Project: jdk8u60   Source File: Basic.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void ts(Instant instant, String expected) {
    String result = FileTime.from(instant).toString();
    if (!result.equals(expected)) {
        System.err.format("FileTime.from(%s).toString() failed\n", instant);
        System.err.format("Expected: %s\n", expected);
        System.err.format("     Got: %s\n", result);
        throw new RuntimeException();
    }
}
 
Example 14
/**
 * 从jar包中查找指定接口的一个实现类 非反射
 *
 * @param interfaceClass
 * @param jarPath
 * @return
 * @throws Exception
 */
public static Class findImplementFromJar(Class interfaceClass, URL jarPath) throws Exception {
    URL url = new URL("jar:" + jarPath.toString() + "!/");
    JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
    JarFile jarFile = jarConnection.getJarFile();
    Enumeration<JarEntry> je = jarFile.entries();
    boolean flag = false;
    while (je.hasMoreElements()) {
        JarEntry e = je.nextElement();
        String n = e.getName();
        FileTime ft = e.getLastModifiedTime();
        if (DateUtils.addDays(new Date(), -100).getTime() - ft.toMillis() > 0) {
            LOGGER.info("jar文件时间超过100天,跳过查找实现类:" + jarFile.getName().substring(jarFile.getName().lastIndexOf("\\")) + ft.toString());
            return null;
        } else {
            if (!flag) {
                flag = true;
                LOGGER.info("在" + jarFile.getName().substring(jarFile.getName().lastIndexOf("\\")) + "中查找实现类");
            }
        }
        if (n.endsWith(".class")) {
            n = n.substring(0, n.length() - 6);
            n = n.replace('/', '.');
            Class currentClass = ClassLoader.getSystemClassLoader().loadClass(n);
            if (interfaceClass.isAssignableFrom(currentClass) && !n.equals(interfaceClass.getName())) {
                return currentClass;
            }
        }
    }
    return null;
}
 
Example 15
Source Project: buck   Source File: DefaultProjectFilesystem.java    License: Apache License 2.0 5 votes vote down vote up
/** Sets the last modified time for the given path. */
@Override
public Path setLastModifiedTime(Path pathRelativeToProjectRoot, FileTime time)
    throws IOException {
  Path path = getPathForRelativePath(pathRelativeToProjectRoot);
  return Files.setLastModifiedTime(path, time);
}
 
Example 16
Source Project: mrgeo   Source File: S3Utils.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException exc) throws IOException
{
  if (indexAttributes != null && dataAttributes != null) {
    partitionSize = indexAttributes.size() + dataAttributes.size();
    callback.foundImage(dir, partitionSize, lastAccessTime);
    indexAttributes = null;
    dataAttributes = null;
    lastAccessTime = FileTime.from(Instant.now());
    partitionSize = 0L;
  }
  return FileVisitResult.CONTINUE;
}
 
Example 17
Source Project: hottub   Source File: Basic.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void ts(long v, TimeUnit unit, String expected) {
    String result = FileTime.from(v, unit).toString();
    if (!result.equals(expected)) {
        System.err.format("FileTime.from(%d, %s).toString() failed\n", v, unit);
        System.err.format("Expected: %s\n", expected);
        System.err.format("     Got: %s\n", result);
        throw new RuntimeException();
    }
}
 
Example 18
Source Project: vespa   Source File: FileDirectoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void requireThatExistingDirWithInvalidContentIsDeleted() throws IOException {
    FileDirectory fileDirectory = new FileDirectory(temporaryFolder.getRoot());

    String subdirName = "subdir";
    File subDirectory = new File(temporaryFolder.getRoot(), subdirName);
    createFileInSubDir(subDirectory, "foo", "some content");
    FileReference fileReference = fileDirectory.addFile(subDirectory);
    File dir = fileDirectory.getFile(fileReference);
    assertTrue(dir.exists());
    File foo = new File(dir, "foo");
    assertTrue(foo.exists());
    FileTime fooCreatedTimestamp = Files.readAttributes(foo.toPath(), BasicFileAttributes.class).creationTime();
    assertFalse(new File(dir, "doesnotexist").exists());
    assertEquals("bebc5a1aee74223d", fileReference.value());

    // Remove a file, directory should be deleted before adding a new file
    try { Thread.sleep(1000);} catch (InterruptedException e) {/*ignore */} // Needed since we have timestamp resolution of 1 second
    Files.delete(Paths.get(fileDirectory.getPath(fileReference)).resolve("subdir").resolve("foo"));
    fileReference = fileDirectory.addFile(subDirectory);
    dir = fileDirectory.getFile(fileReference);
    File foo2 = new File(dir, "foo");
    assertTrue(dir.exists());
    assertTrue(foo2.exists());
    FileTime foo2CreatedTimestamp = Files.readAttributes(foo2.toPath(), BasicFileAttributes.class).creationTime();
    // Check that creation timestamp is newer than the old one to be sure that a new file was written
    assertTrue(foo2CreatedTimestamp.compareTo(fooCreatedTimestamp) > 0);
    assertFalse(new File(dir, "doesnotexist").exists());
    assertEquals("bebc5a1aee74223d", fileReference.value());
}
 
Example 19
Source Project: mycore   Source File: MCRStoredNode.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Renames this node.
 * 
 * @param name
 *            the new file name
 */
public void renameTo(String name) throws IOException {
    Path oldPath = path;
    Path newPath = path.resolveSibling(name);
    Files.move(oldPath, newPath);
    Files.setLastModifiedTime(newPath, FileTime.from(Instant.now()));
    path = newPath;
    writeData(e -> e.setAttribute(NAME_ATT, name));
    getRoot().saveAdditionalData();
}
 
Example 20
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 21
Source Project: buck   Source File: FakeFileAttributes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param fileKey something uniquely representing the file this is for
 * @param isFileElseDir this is for a file, iff this is true. Otherwise it's a dir. Never a
 *     symlink or "other" type.
 * @param size file size. Probably only makes sense for files.
 */
protected FakeFileAttributes(Object fileKey, boolean isFileElseDir, long size) {
  this.fileKeyObj = fileKey;
  this.isFileElseDir = isFileElseDir;
  this.fileSize = size;
  this.timestamp = FileTime.fromMillis(System.currentTimeMillis());
}
 
Example 22
Source Project: jdk8u-jdk   Source File: TestExtraTime.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Throwable{

        File src = new File(System.getProperty("test.src", "."), "TestExtraTime.java");
        if (src.exists()) {
            long time = src.lastModified();
            FileTime mtime = FileTime.from(time, TimeUnit.MILLISECONDS);
            FileTime atime = FileTime.from(time + 300000, TimeUnit.MILLISECONDS);
            FileTime ctime = FileTime.from(time - 300000, TimeUnit.MILLISECONDS);
            TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");

            for (byte[] extra : new byte[][] { null, new byte[] {1, 2, 3}}) {
                test(mtime, null, null, null, extra);
                // ms-dos 1980 epoch problem
                test(FileTime.from(10, TimeUnit.MILLISECONDS), null, null, null, extra);
                // non-default tz
                test(mtime, null, null, tz, extra);

                test(mtime, atime, null, null, extra);
                test(mtime, null, ctime, null, extra);
                test(mtime, atime, ctime, null, extra);

                test(mtime, atime, null, tz, extra);
                test(mtime, null, ctime, tz, extra);
                test(mtime, atime, ctime, tz, extra);
            }
        }

        testNullHandling();
        testTimeConversions();
    }
 
Example 23
Source Project: openjdk-jdk8u   Source File: Basic.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void eq(long v1, TimeUnit u1, long v2, TimeUnit u2) {
    FileTime t1 = FileTime.from(v1, u1);
    FileTime t2 = FileTime.from(v2, u2);
    if (!t1.equals(t2))
        throw new RuntimeException("not equal");
    if (t1.hashCode() != t2.hashCode())
        throw new RuntimeException("hashCodes should be equal");
}
 
Example 24
Source Project: libreveris   Source File: WellKnowns.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private static FileTime getJarTime ()
{
    long millis = JAR_FILE.getEntry("META-INF/MANIFEST.MF")
            .getTime();

    return FileTime.fromMillis(millis);
}
 
Example 25
Source Project: buck   Source File: BuildConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteBuildConfiguration() throws IOException, InterruptedException {
  ImmutableSortedMap<String, String> config =
      ImmutableSortedMap.<String, String>naturalOrder().put("SOME_FLAG", "value").build();
  Path filePath = Paths.get("new-dir/test.xcconfig");

  BuildConfiguration.writeBuildConfiguration(projectFilesystem, filePath, config, false);
  Optional<String> fileContents = projectFilesystem.readFileIfItExists(filePath);
  assertEquals("SOME_FLAG = value\n", fileContents.get());

  // Verify that the same file is not rewritten.
  FileTime modifiedTime = projectFilesystem.getLastModifiedTime(filePath);
  BuildConfiguration.writeBuildConfiguration(projectFilesystem, filePath, config, false);
  FileTime newModifiedTime = projectFilesystem.getLastModifiedTime(filePath);
  assertEquals(modifiedTime, newModifiedTime);

  Thread.sleep(100);

  // Verify that a new file is
  config =
      ImmutableSortedMap.<String, String>naturalOrder()
          .put("SOME_FLAG", "value new y'all")
          .build();
  BuildConfiguration.writeBuildConfiguration(projectFilesystem, filePath, config, false);
  newModifiedTime = projectFilesystem.getLastModifiedTime(filePath);
  assertNotEquals(modifiedTime, newModifiedTime);
}
 
Example 26
Source Project: buck   Source File: FakeProjectFilesystemTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void fileModifiedTimeIsSetOnInitialWrite() throws IOException {
  SettableFakeClock clock = new SettableFakeClock(49152, 0);
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem(clock);
  filesystem.touch(Paths.get("foo"));
  assertEquals(filesystem.getLastModifiedTime(Paths.get("foo")), FileTime.fromMillis(49152));
}
 
Example 27
Source Project: jmonkeybuilder   Source File: ResourceManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@FromAnyThread
public synchronized void assetRequested(@NotNull final AssetKey key) {

    if (key.getCacheType() == null) {
        return;
    }

    final String extension = key.getExtension();
    if (StringUtils.isEmpty(extension)){
        return;
    }

    final ObjectDictionary<String, Reference> table = getAssetCacheTable();
    final Reference reference = table.get(key.getName());
    if (reference == null) {
        return;
    }

    final Path realFile = getRealFile(Paths.get(key.getName()));
    if (realFile == null || !Files.exists(realFile)) {
        return;
    }

    try {

        final long timestamp = reference.getLong();

        final FileTime lastModifiedTime = Files.getLastModifiedTime(realFile);
        if (lastModifiedTime.to(TimeUnit.MILLISECONDS) <= timestamp) {
            return;
        }

        final AssetManager assetManager = EditorUtil.getAssetManager();
        assetManager.deleteFromCache(key);

    } catch (final IOException e) {
        LOGGER.warning(e);
    }
}
 
Example 28
Source Project: carbon-commons   Source File: LoggingUpdaterUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static FileTime readModifiedTime() throws LoggingUpdaterException {

        String carbonConfigDirPath = CarbonUtils.getCarbonConfigDirPath();
        File log4j2File = new File(carbonConfigDirPath + File.separator + "log4j2.properties");
        try {
            BasicFileAttributes log4j2FileAttributes
                    = Files.getFileAttributeView(log4j2File.toPath(), BasicFileAttributeView.class).readAttributes();
            return log4j2FileAttributes.lastModifiedTime();
        } catch (IOException e) {
            throw new LoggingUpdaterException("Error while reading log4j2.properties", e);
        }
    }
 
Example 29
Source Project: jdk8u-dev-jdk   Source File: Basic.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void ts(Instant instant, String expected) {
    String result = FileTime.from(instant).toString();
    if (!result.equals(expected)) {
        System.err.format("FileTime.from(%s).toString() failed\n", instant);
        System.err.format("Expected: %s\n", expected);
        System.err.format("     Got: %s\n", result);
        throw new RuntimeException();
    }
}
 
Example 30
Source Project: AuthMeReloaded   Source File: GeoIpService.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Download (if absent or old) the GeoIpLite data file and then try to load it.
 *
 * @return True if the data is available, false otherwise.
 */
private synchronized boolean isDataAvailable() {
    if (downloading) {
        // we are currently downloading the database
        return false;
    }

    if (databaseReader != null) {
        // everything is initialized
        return true;
    }

    if (Files.exists(dataFile)) {
        try {
            FileTime lastModifiedTime = Files.getLastModifiedTime(dataFile);
            if (Duration.between(lastModifiedTime.toInstant(), Instant.now()).toDays() <= UPDATE_INTERVAL_DAYS) {
                startReading();

                // don't fire the update task - we are up to date
                return true;
            } else {
                logger.debug("GEO IP database is older than " + UPDATE_INTERVAL_DAYS + " Days");
            }
        } catch (IOException ioEx) {
            logger.logException("Failed to load GeoLiteAPI database", ioEx);
            return false;
        }
    }

    //set the downloading flag in order to fix race conditions outside
    downloading = true;

    // File is outdated or doesn't exist - let's try to download the data file!
    // use bukkit's cached threads
    bukkitService.runTaskAsynchronously(this::updateDatabase);
    return false;
}