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

The following examples show how to use java.nio.file.Files#setLastModifiedTime() . 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: ConfigurationTest.java    From SerialKiller with Apache License 2.0 6 votes vote down vote up
@Test
public void testReload() throws Exception {
    Path tempFile = Files.createTempFile("sk-", ".conf");
    Files.copy(new File("src/test/resources/blacklist-all-refresh-10-ms.conf").toPath(), tempFile, REPLACE_EXISTING);

    Configuration configuration = new Configuration(tempFile.toAbsolutePath().toString());

    assertFalse(configuration.isProfiling());
    assertEquals(".*", configuration.blacklist().iterator().next().pattern());
    assertEquals("java\\.lang\\..*", configuration.whitelist().iterator().next().pattern());

    Files.copy(new File("src/test/resources/whitelist-all.conf").toPath(), tempFile, REPLACE_EXISTING);
    Thread.sleep(1000L); // Wait to ensure the file is fully copied
    Files.setLastModifiedTime(tempFile, FileTime.fromMillis(System.currentTimeMillis())); // Commons configuration watches file modified time
    Thread.sleep(1000L); // Wait to ensure a reload happens

    configuration.reloadIfNeeded(); // Trigger reload

    assertFalse(configuration.blacklist().iterator().hasNext());
    assertEquals(".*", configuration.whitelist().iterator().next().pattern());
}
 
Example 2
Source File: FileServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testFileSystemGet_modifiedFile(String baseUri) throws Exception {
    final Path barFile = tmpDir.resolve("modifiedFile.html");
    final String expectedContentA = "<html/>";
    final String expectedContentB = "<html><body/></html>";
    writeFile(barFile, expectedContentA);
    final long barFileLastModified = Files.getLastModifiedTime(barFile).toMillis();

    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpUriRequest req = new HttpGet(baseUri + "/fs/modifiedFile.html");
        try (CloseableHttpResponse res = hc.execute(req)) {
            assert200Ok(res, "text/html", expectedContentA);
        }

        // Modify the file cached by the service. Update last modification time explicitly
        // so that it differs from the old value.
        writeFile(barFile, expectedContentB);
        Files.setLastModifiedTime(barFile, FileTime.fromMillis(barFileLastModified + 5000));

        try (CloseableHttpResponse res = hc.execute(req)) {
            assert200Ok(res, "text/html", expectedContentB);
        }
    }
}
 
Example 3
Source File: Environment.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the path is writable.
 * Acts just like {@link Files#isWritable(Path)}, except won't
 * falsely return false for paths on SUBST'd drive letters
 * See https://bugs.openjdk.java.net/browse/JDK-8034057
 * Note this will set the file modification time (to its already-set value)
 * to test access.
 */
@SuppressForbidden(reason = "works around https://bugs.openjdk.java.net/browse/JDK-8034057")
public static boolean isWritable(Path path) throws IOException {
    boolean v = Files.isWritable(path);
    if (v || Constants.WINDOWS == false) {
        return v;
    }

    // isWritable returned false on windows, the hack begins!!!!!!
    // resetting the modification time is the least destructive/simplest
    // way to check for both files and directories, and fails early just
    // in getting the current value if file doesn't exist, etc
    try {
        Files.setLastModifiedTime(path, Files.getLastModifiedTime(path));
        return true;
    } catch (Throwable e) {
        return false;
    }
}
 
Example 4
Source File: SystemTest.java    From yajsync with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testCopyFileTwiceNotMultipleBlockSize() throws IOException
{
    Path src = _tempDir.newFile().toPath();
    Path dst = Paths.get(src.toString() + ".copy");
    int fileSize = 557;
    int numDirs = 0;
    int numFiles = 1;
    byte[] content = FileUtil.generateBytes(0x18, fileSize);
    FileUtil.writeToFiles(content, src);
    Files.setLastModifiedTime(src, FileTime.fromMillis(0));
    ReturnStatus status = fileCopy(src, dst);
    assertTrue(status.rc == 0);
    assertTrue(FileUtil.isContentIdentical(src, dst));
    assertTrue(status.stats.numFiles() == numDirs + numFiles);
    assertTrue(status.stats.numTransferredFiles() == numFiles);
    assertTrue(status.stats.totalLiteralSize() == fileSize);
    assertTrue(status.stats.totalMatchedSize() == 0);
    ReturnStatus status2 = fileCopy(src, dst);
    assertTrue(status2.rc == 0);
    assertTrue(FileUtil.isContentIdentical(src, dst));
    assertTrue(status2.stats.numFiles() == numDirs + numFiles);
    assertTrue(status2.stats.numTransferredFiles() == numFiles);
    assertTrue(status2.stats.totalLiteralSize() == 0);
    assertTrue(status2.stats.totalMatchedSize() == fileSize);
}
 
Example 5
Source File: FileServiceFileStorageTest.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteFilesModifiedBefore() throws Exception {
    long currentMillis = System.currentTimeMillis();
    final long oldFilesTtl = 1000 * 60 * 10; // 10min
    final long pastMoment = currentMillis - 1000 * 60 * 15; // before 15min

    FileEntry fileEntryToRemain1 = addFile(TEST_FILE_LOCATION);
    FileEntry fileEntryToRemain2 = addFile(SECOND_FILE_TEST_LOCATION);
    FileEntry fileEntryToDelete1 = addFile(TEST_FILE_LOCATION);
    FileEntry fileEntryToDelete2 = addFile(SECOND_FILE_TEST_LOCATION);

    Files.setLastModifiedTime(getFileLocation(fileEntryToDelete1), FileTime.fromMillis(pastMoment));
    Files.setLastModifiedTime(getFileLocation(fileEntryToDelete2), FileTime.fromMillis(pastMoment));

    Path oldNonDeployerFile = Files.createFile(Paths.get(temporaryStorageLocation.toString(), "random"));
    Files.setLastModifiedTime(oldNonDeployerFile, FileTime.fromMillis(pastMoment));

    int deletedFiles = fileStorage.deleteFilesModifiedBefore(new Date(currentMillis - oldFilesTtl));

    assertEquals(3, deletedFiles);
    assertFalse(Files.exists(oldNonDeployerFile));
    assertFileExists(true, fileEntryToRemain1);
    assertFileExists(true, fileEntryToRemain2);
    assertFileExists(false, fileEntryToDelete1);
    assertFileExists(false, fileEntryToDelete2);
}
 
Example 6
Source File: Copy.java    From marathonv5 with 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 7
Source File: SerialKillerTest.java    From SerialKiller with Apache License 2.0 6 votes vote down vote up
@Test
public void testReload() throws Exception {
    Path tempFile = Files.createTempFile("sk-", ".conf");
    Files.copy(new File("src/test/resources/blacklist-all-refresh-10-ms.conf").toPath(), tempFile, REPLACE_EXISTING);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    try (ObjectOutputStream stream = new ObjectOutputStream(bytes)) {
        stream.writeObject(42);
    }

    try (ObjectInputStream stream = new SerialKiller(new ByteArrayInputStream(bytes.toByteArray()), tempFile.toAbsolutePath().toString())) {

        Files.copy(new File("src/test/resources/whitelist-all.conf").toPath(), tempFile, REPLACE_EXISTING);
        Thread.sleep(1000L); // Wait to ensure the file is fully copied
        Files.setLastModifiedTime(tempFile, FileTime.fromMillis(System.currentTimeMillis())); // Commons configuration watches file modified time
        Thread.sleep(1000L); // Wait to ensure a reload happens

        assertEquals(42, stream.readObject());
    }
}
 
Example 8
Source File: QuarkusDevModeTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public void sleepForFileChanges(Path path) {
    try {
        //we want to make sure the last modified time is larger than both the current time
        //and the current last modified time. Some file systems only resolve file
        //time to the nearest second, so this is necessary for dev mode to pick up the changes
        long timeToBeat = Math.max(System.currentTimeMillis(), Files.getLastModifiedTime(path).toMillis());
        for (;;) {
            Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));
            long fm = Files.getLastModifiedTime(path).toMillis();
            Thread.sleep(10);
            if (fm > timeToBeat) {
                return;
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: MCRUtils.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Extracts files in a tar archive. Currently works only on uncompressed tar files.
 *
 * @param source
 *            the uncompressed tar to extract
 * @param expandToDirectory
 *            the directory to extract the tar file to
 * @throws IOException
 *             if the source file does not exists
 */
public static void untar(Path source, Path expandToDirectory) throws IOException {
    try (TarArchiveInputStream tain = new TarArchiveInputStream(Files.newInputStream(source))) {
        TarArchiveEntry tarEntry;
        FileSystem targetFS = expandToDirectory.getFileSystem();
        HashMap<Path, FileTime> directoryTimes = new HashMap<>();
        while ((tarEntry = tain.getNextTarEntry()) != null) {
            Path target = MCRPathUtils.getPath(targetFS, tarEntry.getName());
            Path absoluteTarget = expandToDirectory.resolve(target).normalize().toAbsolutePath();
            if (tarEntry.isDirectory()) {
                Files.createDirectories(expandToDirectory.resolve(absoluteTarget));
                directoryTimes.put(absoluteTarget, FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
            } else {
                if (Files.notExists(absoluteTarget.getParent())) {
                    Files.createDirectories(absoluteTarget.getParent());
                }
                Files.copy(tain, absoluteTarget, StandardCopyOption.REPLACE_EXISTING);
                Files.setLastModifiedTime(absoluteTarget,
                    FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
            }
        }
        //restore directory dates
        Files.walkFileTree(expandToDirectory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Path absolutePath = dir.normalize().toAbsolutePath();
                Files.setLastModifiedTime(absolutePath, directoryTimes.get(absolutePath));
                return super.postVisitDirectory(dir, exc);
            }
        });
    }
}
 
Example 10
Source File: TreeCopier.java    From Processing.R with GNU General Public License v3.0 5 votes vote down vote up
@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 11
Source File: MCRAutoDeploy.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private void deployWebResources(final ServletContext servletContext, final MCRComponent comp) {
    final Path webRoot = Optional.ofNullable(servletContext.getRealPath("/")).map(Paths::get).orElse(null);
    if (webRoot != null) {
        int resourceDirPathComponents = RESOURCE_DIR.split("/").length;
        try (InputStream fin = Files.newInputStream(comp.getJarFile().toPath());
            ZipInputStream zin = new ZipInputStream(fin)) {
            LOGGER.info("Deploy web resources from {} to {}...", comp.getName(), webRoot);
            for (ZipEntry zipEntry = zin.getNextEntry(); zipEntry != null; zipEntry = zin.getNextEntry()) {
                if (zipEntry.getName().startsWith(RESOURCE_DIR)) {
                    Path relativePath = toNativePath(zipEntry);
                    if (relativePath.getNameCount() > resourceDirPathComponents) {
                        //strip RESOURCE_DIR:
                        relativePath = relativePath.subpath(resourceDirPathComponents, relativePath.getNameCount());
                        Path target = webRoot.resolve(relativePath);
                        if (zipEntry.isDirectory()) {
                            Files.createDirectories(target);
                        } else if (isUnzipRequired(zipEntry, target)) {
                            LOGGER.debug("...deploy {}", zipEntry.getName());
                            Files.copy(zin, target, StandardCopyOption.REPLACE_EXISTING);
                            Files.setLastModifiedTime(target, zipEntry.getLastModifiedTime());
                        }
                    }
                }
            }
            LOGGER.info("...done.");
        } catch (final IOException e) {
            LOGGER.error("Could not deploy web resources of " + comp.getJarFile() + "!", e);
        }
    }
}
 
Example 12
Source File: FileUtils.java    From zip4j with Apache License 2.0 5 votes vote down vote up
public static void setFileLastModifiedTime(Path file, long lastModifiedTime) {
  if (lastModifiedTime <= 0 || !Files.exists(file)) {
    return;
  }

  try {
    Files.setLastModifiedTime(file, FileTime.fromMillis(Zip4jUtil.dosToJavaTme(lastModifiedTime)));
  } catch (Exception e) {
    // Ignore
  }
}
 
Example 13
Source File: CleanupOldDeploysJobTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private void createTestDirectories(int count) throws IOException {
  long now = System.currentTimeMillis();
  // most recent directory will be "1", oldest is "<count>"
  for (int i = count; i > 0; --i) {
    File newFolder = tempFolder.newFolder(Integer.toString(i));
    Files.setLastModifiedTime(
        newFolder.toPath(), FileTime.fromMillis(now - i * 1000L)); // to ensure correct ordering
  }
}
 
Example 14
Source File: ConfigDispatcherOSGiTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void globalPIDIsOverriddenByLocalPIDInDifferentFileIfTheFileWithTheLocalOneIsModifiedLast()
        throws Exception {
    String configDirectory = configBaseDirectory + SEP + "global_and_local_pid_different_files_conf";
    String servicesDirectory = "global_and_local_pid_overridden_global_services";
    String defaultConfigFilePath = configDirectory + SEP + "global.and.local.pid.default.file.cfg";
    String lastModifiedFileName = "a.overriding.local.pid.service.file.cfg";

    /*
     * Both files(with local and global pid) contain this property, but with different value.
     * The value for this property in the last processed file must override the previous
     * values for the same property in the configuration.
     */
    String conflictProperty = "global.and.local.property";

    initialize(defaultConfigFilePath);

    cd.processConfigFile(new File(getAbsoluteConfigDirectory(configDirectory, servicesDirectory)));

    // Modify this file, so that we are sure it is the last modified file in servicesDirectory.
    File fileToModify = new File(configDirectory + SEP + servicesDirectory + SEP + lastModifiedFileName);
    Files.setLastModifiedTime(fileToModify.toPath(), FileTime.from(Instant.now()));
    cd.processConfigFile(fileToModify);

    String value = getLastModifiedValueForPoperty(getAbsoluteConfigDirectory(configDirectory, servicesDirectory),
            conflictProperty);

    /*
     * Assert that the local pid from the last modified file
     * has overridden the global pid from previously processed file.
     */
    verifyValueOfConfigurationProperty("overridden.global.pid", conflictProperty, value);
}
 
Example 15
Source File: FileModifiedTimeUpdaterTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "files")
public void testFileModified(String fileName) throws IOException, InterruptedException {
    Path path = Paths.get(fileName);
    createFile(path);
    FileModifiedTimeUpdater fileModifiedTimeUpdater = new FileModifiedTimeUpdater(fileName);
    Thread.sleep(2000);
    Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));
    FileTime fileTime = fileModifiedTimeUpdater.getLastModifiedTime();
    Assert.assertTrue(fileModifiedTimeUpdater.checkAndRefresh());
    Assert.assertNotEquals(fileTime, fileModifiedTimeUpdater.getLastModifiedTime());
}
 
Example 16
Source File: SnapshotsPolicyTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
private void assertSnapshotPolicy( PolicyOption setting, String path, boolean createLocalFile )
    throws Exception
{
    PreDownloadPolicy policy = lookupPolicy();
    Properties request = new Properties();
    request.setProperty( "filetype", path.endsWith( "/maven-metadata.xml" ) ? "metadata" : "artifact" );

    if ( path.contains( "1.0-SNAPSHOT" ) )
    {
        request.setProperty( "version", "1.0-SNAPSHOT" );
    }

    if ( path.contains( "2.0" ) )
    {
        request.setProperty( "version", "2.0" );
    }

    StorageAsset targetDir = ChecksumPolicyTest.getTestFile( "target/test-policy/" );
    StorageAsset localFile = targetDir.resolve( path );

    Files.deleteIfExists( localFile.getFilePath() );

    if ( createLocalFile )
    {
        Files.createDirectories( localFile.getParent().getFilePath() );
        org.apache.archiva.common.utils.FileUtils.writeStringToFile( localFile.getFilePath(), FILE_ENCODING, "random-junk" );
        Files.setLastModifiedTime( localFile.getFilePath(),
            FileTime.fromMillis( Files.getLastModifiedTime( localFile.getFilePath() ).toMillis() - generatedLocalFileUpdateDelta ));
    }

    policy.applyPolicy( setting, request, localFile );
}
 
Example 17
Source File: DefaultProjectFilesystemTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testSortedDirectoryContents() throws IOException {
  tmp.newFolder("foo");
  Path a = tmp.newFile("foo/a.txt");
  Files.setLastModifiedTime(a, FileTime.fromMillis(1000));
  Path b = tmp.newFile("foo/b.txt");
  Files.setLastModifiedTime(b, FileTime.fromMillis(2000));
  Path c = tmp.newFile("foo/c.txt");
  Files.setLastModifiedTime(c, FileTime.fromMillis(3000));
  tmp.newFile("foo/non-matching");

  assertEquals(
      ImmutableSet.of(c, b, a),
      filesystem.getMtimeSortedMatchingDirectoryContents(Paths.get("foo"), "*.txt"));
}
 
Example 18
Source File: ArchiveRepositoryTest.java    From Nicobar with Apache License 2.0 4 votes vote down vote up
/**
 * Test insert, update, delete
 */
@Test
public void testRoundTrip() throws Exception {
    ArchiveRepository repository = createRepository();
    JarScriptArchive jarScriptArchive = new JarScriptArchive.Builder(testArchiveJarFile).build();
    ModuleId testModuleId = TEST_MODULE_SPEC_JAR.getModuleId();
    repository.insertArchive(jarScriptArchive);
    Map<ModuleId, Long> archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes();
    long expectedUpdateTime = Files.getLastModifiedTime(testArchiveJarFile).toMillis();
    assertEquals(archiveUpdateTimes, Collections.singletonMap(testModuleId, expectedUpdateTime));

    // assert getScriptArchives
    Set<ScriptArchive> scriptArchives = repository.getScriptArchives(archiveUpdateTimes.keySet());
    assertEquals(scriptArchives.size(), 1, scriptArchives.toString());
    ScriptArchive scriptArchive = scriptArchives.iterator().next();
    assertEquals(scriptArchive.getModuleSpec().getModuleId(), testModuleId);
    assertEquals(scriptArchive.getCreateTime(), expectedUpdateTime);

    // assert getArchiveSummaries
    List<ArchiveSummary> archiveSummaries = repository.getDefaultView().getArchiveSummaries();
    assertEquals(archiveSummaries.size(), 1);
    ArchiveSummary archiveSummary = archiveSummaries.get(0);
    assertEquals(archiveSummary.getModuleId(), testModuleId);
    assertEquals(archiveSummary.getLastUpdateTime(), expectedUpdateTime);

    // assert getRepositorySummary
    RepositorySummary repositorySummary = repository.getDefaultView().getRepositorySummary();
    assertNotNull(repositorySummary);
    assertEquals(repositorySummary.getArchiveCount(), 1);
    assertEquals(repositorySummary.getLastUpdated(), expectedUpdateTime);

    // advance the timestamp by 10 seconds and update
    expectedUpdateTime = expectedUpdateTime + 10000;
    Files.setLastModifiedTime(testArchiveJarFile, FileTime.fromMillis(expectedUpdateTime));
    jarScriptArchive = new JarScriptArchive.Builder(testArchiveJarFile).build();
    repository.insertArchive(jarScriptArchive);
    archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes();
    assertEquals(archiveUpdateTimes, Collections.singletonMap(testModuleId, expectedUpdateTime));

    // assert getScriptArchives
    scriptArchives = repository.getScriptArchives(archiveUpdateTimes.keySet());
    assertEquals(scriptArchives.size(), 1, scriptArchives.toString());
    scriptArchive = scriptArchives.iterator().next();
    assertEquals(scriptArchive.getModuleSpec().getModuleId(), testModuleId);
    assertEquals(scriptArchive.getCreateTime(), expectedUpdateTime);

    // assert getArchiveSummaries
    archiveSummaries = repository.getDefaultView().getArchiveSummaries();
    assertEquals(archiveSummaries.size(), 1);
    archiveSummary = archiveSummaries.get(0);
    assertEquals(archiveSummary.getModuleId(), testModuleId);
    assertEquals(archiveSummary.getLastUpdateTime(), expectedUpdateTime);

    // assert getRepositorySummary
    repositorySummary = repository.getDefaultView().getRepositorySummary();
    assertNotNull(repositorySummary);
    assertEquals(repositorySummary.getArchiveCount(), 1);
    assertEquals(repositorySummary.getLastUpdated(), expectedUpdateTime);

    // delete module
    repository.deleteArchive(testModuleId);
    archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes();
    assertTrue(archiveUpdateTimes.isEmpty(), archiveUpdateTimes.toString());
}
 
Example 19
Source File: ArchivaRepositoryScanningTaskExecutorPhase2Test.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Test
    public void testExecutorScanOnlyNewArtifactsMidScan()
        throws Exception
    {
        RepositoryTask repoTask = new RepositoryTask();

        repoTask.setRepositoryId( TEST_REPO_ID );
        repoTask.setScanAll( false );

        createAndSaveTestStats();

        Path newArtifactGroup = repoDir.resolve( "org/apache/archiva" );
        assertFalse( "newArtifactGroup should not exist.", Files.exists(newArtifactGroup) );

        FileUtils.copyDirectory( Paths.get( "target/test-classes/test-repo/org/apache/archiva" ).toFile(),
                                          newArtifactGroup.toFile() );

        // update last modified date, placing in middle of last scan
        Files.setLastModifiedTime( newArtifactGroup.resolve("archiva-index-methods-jar-test/1.0/pom.xml" ), FileTime.fromMillis(
            Calendar.getInstance().getTimeInMillis() - 50000 ));
        Files.setLastModifiedTime( newArtifactGroup.resolve(
                  "archiva-index-methods-jar-test/1.0/archiva-index-methods-jar-test-1.0.jar" ), FileTime.fromMillis(
                      Calendar.getInstance().getTimeInMillis() - 50000 ));

        assertTrue( Files.exists(newArtifactGroup) );

        // scan using the really long previous duration
        taskExecutor.executeTask( repoTask );

        // check no artifacts processed
        Collection<String> unprocessedResultList = testConsumer.getConsumed();
        assertNotNull( unprocessedResultList );
        assertEquals( "Incorrect number of unprocessed artifacts detected. One new artifact should have been found.", 1,
                      unprocessedResultList.size() );

        // check correctness of new stats
        RepositoryStatistics newStats =
            repositoryStatisticsManager.getLastStatistics( TEST_REPO_ID );
        assertEquals( 2, newStats.getNewFileCount() );
        assertEquals( 33, newStats.getTotalFileCount() );
        // FIXME: can't test these as they weren't stored in the database, move to tests for RepositoryStatisticsManager implementation
//        assertEquals( 8, newStats.getTotalArtifactCount() );
//        assertEquals( 3, newStats.getTotalGroupCount() );
//        assertEquals( 5, newStats.getTotalProjectCount() );
//        assertEquals( 19301, newStats.getTotalArtifactFileSize() );
    }
 
Example 20
Source File: TestDirectorySpooler.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testArchiveWithoutStartingFile() throws Exception {
  assertTrue(spoolDir.mkdirs());
  assertTrue(archiveDir.mkdirs());

  File logFile1 = new File(spoolDir, "x1.log").getAbsoluteFile();
  new FileWriter(logFile1).close();

  File logFile2 = new File(spoolDir, "x2.log").getAbsoluteFile();
  new FileWriter(logFile2).close();

  File logFile3 = new File(spoolDir, "x3.log").getAbsoluteFile();
  new FileWriter(logFile3).close();

  long currentMills = System.currentTimeMillis();

  //Set the last modified time to be different seconds for each file
  Files.setLastModifiedTime(
      Paths.get(logFile1.getAbsolutePath()),
      FileTime.from(currentMills - 3000, TimeUnit.MILLISECONDS)
  );
  Files.setLastModifiedTime(
      Paths.get(logFile2.getAbsolutePath()),
      FileTime.from(currentMills - 2000, TimeUnit.MILLISECONDS)
  );
  Files.setLastModifiedTime(
      Paths.get(logFile3.getAbsolutePath()),
      FileTime.from(currentMills - 1000, TimeUnit.MILLISECONDS)
  );

  //Directory has the most recent timestamp, because with every new file directory's modified time changes.
  Files.setLastModifiedTime(
      Paths.get(spoolDir.getAbsolutePath()),
      FileTime.from(currentMills, TimeUnit.MILLISECONDS)
  );

  DirectorySpooler.Builder builder = initializeAndGetBuilder()
      .setMaxSpoolFiles(5)
      .setUseLastModifiedTimestamp(true)
      .setFilePattern("*")
      .setPostProcessing(DirectorySpooler.FilePostProcessing.ARCHIVE)
      .setArchiveDir(archiveDir.getAbsolutePath());
  DirectorySpooler spooler = builder.build();

  Assert.assertEquals(3, spoolDir.list().length);
  Assert.assertEquals(0, archiveDir.list().length);
  assertTrue(logFile1.exists());
  assertTrue(logFile2.exists());
  assertTrue(logFile3.exists());

  //No starting file
  spooler.init("");
  //Nothing should be archived.
  Assert.assertEquals(3, spoolDir.list().length);
  Assert.assertEquals(0, archiveDir.list().length);
  assertTrue(logFile1.exists());
  assertTrue(logFile2.exists());
  assertTrue(logFile3.exists());

  spooler.destroy();
}