Example usage for java.io File setLastModified

List of usage examples for java.io File setLastModified

Introduction

In this page you can find the example usage for java.io File setLastModified.

Prototype

public boolean setLastModified(long time) 

Source Link

Document

Sets the last-modified time of the file or directory named by this abstract pathname.

Usage

From source file:org.java.plugin.standard.ShadingPathResolver.java

static void unpack(final InputStream strm, final File destFolder) throws IOException {
    ZipInputStream zipStrm = new ZipInputStream(strm);
    ZipEntry entry = zipStrm.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        File entryFile = new File(destFolder.getCanonicalPath() + "/" + name); //$NON-NLS-1$
        if (name.endsWith("/")) { //$NON-NLS-1$
            if (!entryFile.exists() && !entryFile.mkdirs()) {
                throw new IOException("can't create folder " + entryFile); //$NON-NLS-1$
            }/*from  w  w w  . ja  v a  2s  .c  om*/
        } else {
            File folder = entryFile.getParentFile();
            if (!folder.exists() && !folder.mkdirs()) {
                throw new IOException("can't create folder " + folder); //$NON-NLS-1$
            }
            OutputStream out = new BufferedOutputStream(new FileOutputStream(entryFile, false));
            try {
                IoUtil.copyStream(zipStrm, out, 1024);
            } finally {
                out.close();
            }
        }
        entryFile.setLastModified(entry.getTime());
        entry = zipStrm.getNextEntry();
    }
}

From source file:org.apache.archiva.proxy.AbstractProxyTestCase.java

protected void setManagedNewerThanRemote(File managedFile, File remoteFile, long time) {
    assertTrue("Managed File should exist: ", managedFile.exists());
    assertTrue("Remote File should exist: ", remoteFile.exists());

    managedFile.setLastModified(remoteFile.lastModified() + time);

    assertTrue(managedFile.lastModified() > remoteFile.lastModified());
}

From source file:com.streamsets.pipeline.stage.origin.remote.TestRemoteDownloadSource.java

@Test
public void testPicksUpNewFiles() throws Exception {
    String originPath = currentThread().getContextClassLoader()
            .getResource("remote-download-source/parseNoError").getPath();
    File originDirFile = new File(originPath).listFiles()[0];
    File tempDir = testFolder.newFolder();
    File copied = new File(tempDir, originDirFile.getName());
    Files.copy(originDirFile, copied);
    long lastModified = copied.lastModified();
    setupSSHD(tempDir.toString(), true);
    RemoteDownloadSource origin = new RemoteDownloadSource(
            getBean("sftp://localhost:" + String.valueOf(port) + "/", true, "testuser", "pass", null, null,
                    null, true, DataFormat.JSON, null));
    SourceRunner runner = new SourceRunner.Builder(RemoteDownloadSource.class, origin).addOutputLane("lane")
            .build();//from  ww  w . jav a 2  s  . c  om
    runner.runInit();
    String offset = "-1";
    StageRunner.Output op = runner.runProduce(offset, 1000);
    offset = op.getNewOffset();
    List<Record> expected = getExpectedRecords();
    List<Record> actual = op.getRecords().get("lane");
    Assert.assertEquals(expected.size(), actual.size());
    for (int i = 0; i < 2; i++) {
        Assert.assertEquals(expected.get(i).get(), actual.get(i).get());
    }
    File eventualFile = new File(tempDir, "z" + originDirFile.getName() + "-1");
    Files.copy(originDirFile, eventualFile);
    eventualFile.setLastModified(lastModified);
    op = runner.runProduce(offset, 1000);
    expected = getExpectedRecords();
    actual = op.getRecords().get("lane");
    Assert.assertEquals(expected.size(), actual.size());
    for (int i = 0; i < 2; i++) {
        Assert.assertEquals(expected.get(i).get(), actual.get(i).get());
    }
}

From source file:org.apache.archiva.proxy.AbstractProxyTestCase.java

protected void setManagedOlderThanRemote(File managedFile, File remoteFile, long time) {
    assertTrue("Managed File should exist: ", managedFile.exists());
    assertTrue("Remote File should exist: ", remoteFile.exists());

    managedFile.setLastModified(remoteFile.lastModified() - time);

    assertTrue(managedFile.lastModified() < remoteFile.lastModified());

}

From source file:org.apache.camel.component.file.FileOperations.java

private void keepLastModified(Exchange exchange, File file) {
    if (endpoint.isKeepLastModified()) {
        Long last;/*from   w w w .  jav a2s .c o m*/
        Date date = exchange.getIn().getHeader(Exchange.FILE_LAST_MODIFIED, Date.class);
        if (date != null) {
            last = date.getTime();
        } else {
            // fallback and try a long
            last = exchange.getIn().getHeader(Exchange.FILE_LAST_MODIFIED, Long.class);
        }
        if (last != null) {
            boolean result = file.setLastModified(last);
            if (LOG.isTraceEnabled()) {
                LOG.trace("Keeping last modified timestamp: " + last + " on file: " + file + " with result: "
                        + result);
            }
        }
    }
}

From source file:org.springframework.integration.ftp.outbound.FtpServerOutboundTests.java

@Test
@SuppressWarnings("unchecked")
public void testInt3172LocalDirectoryExpressionMGETRecursive() throws IOException {
    String dir = "ftpSource/";
    long modified = setModifiedOnSource1();
    File secondRemote = new File(getSourceRemoteDirectory(), "ftpSource2.txt");
    secondRemote.setLastModified(System.currentTimeMillis() - 1_000_000);
    this.inboundMGetRecursive.send(new GenericMessage<Object>("*"));
    Message<?> result = this.output.receive(1000);
    assertNotNull(result);//from w ww . ja v a2  s  .com
    List<File> localFiles = (List<File>) result.getPayload();
    assertEquals(3, localFiles.size());

    boolean assertedModified = false;
    for (File file : localFiles) {
        assertThat(file.getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
                containsString(dir));
        if (file.getPath().contains("localTarget1")) {
            assertedModified = assertPreserved(modified, file);
        }
    }
    assertTrue(assertedModified);
    assertThat(localFiles.get(2).getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"),
            containsString(dir + "subFtpSource"));

    File secondTarget = new File(getTargetLocalDirectory() + File.separator + "ftpSource", "localTarget2.txt");
    ByteArrayOutputStream remoteContents = new ByteArrayOutputStream();
    ByteArrayOutputStream localContents = new ByteArrayOutputStream();
    FileUtils.copyFile(secondRemote, remoteContents);
    FileUtils.copyFile(secondTarget, localContents);
    String localAsString = new String(localContents.toByteArray());
    assertEquals(new String(remoteContents.toByteArray()), localAsString);
    long oldLastModified = secondRemote.lastModified();
    FileUtils.copyInputStreamToFile(new ByteArrayInputStream("junk".getBytes()), secondRemote);
    long newLastModified = secondRemote.lastModified();
    secondRemote.setLastModified(oldLastModified);
    this.inboundMGetRecursive.send(new GenericMessage<Object>("*"));
    this.output.receive(0);
    localContents = new ByteArrayOutputStream();
    FileUtils.copyFile(secondTarget, localContents);
    assertEquals(localAsString, new String(localContents.toByteArray()));
    secondRemote.setLastModified(newLastModified);
    this.inboundMGetRecursive.send(new GenericMessage<Object>("*"));
    this.output.receive(0);
    localContents = new ByteArrayOutputStream();
    FileUtils.copyFile(secondTarget, localContents);
    assertEquals("junk", new String(localContents.toByteArray()));
    // restore the remote file contents
    FileUtils.copyInputStreamToFile(new ByteArrayInputStream(localAsString.getBytes()), secondRemote);
}

From source file:org.apache.hadoop.mapred.TestTaskLogsMonitor.java

/**
 * Test the TaskLog.cleanup() where if the number of log files exceed the limit by {@link TaskLogsMonitor}
 * @throws IOException/*  w  ww  . ja  v  a 2s . co m*/
 * @throws InterruptedException
 */
@Test
public void testLogsFilesLimit() throws IOException, InterruptedException {
    JobConf conf = new JobConf();
    conf.setLong("mapred.userlog.cleanup.interval", 10000);
    conf.setInt("mapred.userlog.retain.hours", 24);
    conf.setInt("mapred.userlog.files.limit", 50);
    TaskTracker tracker = new TaskTracker();
    tracker.setConf(conf);
    File f;
    int numFiles = 200;
    for (int i = 0; i < numFiles; i++) {
        String filename = TaskLog.getUserLogDir() + File.separator + "file_" + i;
        System.out.println(filename);
        f = new File(filename);
        f.createNewFile();
        f.setLastModified(System.currentTimeMillis() + i * 60 * 1000);
    }
    tracker.startLogCleanupThread();
    Thread.sleep(900);

    assertEquals("TaskLog.cleanup() may not clean up half of the older logs!", (numFiles + 1) / 2,
            TaskLog.getUserLogDir().listFiles().length);
}

From source file:org.jboss.dashboard.ui.resources.GraphicElement.java

/**
 * Deploy to a given directory. Extract all files in associated zip to given directory plus getBaseDir()
 *
 * @throws java.io.IOException//from ww w. j a v  a  2 s  . c  om
 */
protected void deployFiles() throws Exception {
    //setLastModified(new Date());
    log.info("Deploying files for " + this.getClass().getName() + " " + getId());
    String destinationDir = getDeploymentDirName();
    File destDirFile = new File(destinationDir);
    destDirFile.mkdirs();
    if (!destDirFile.setLastModified(System.currentTimeMillis())) {
        log.error("Failed to set directory last modified, it might not be supported by the filesystem. "
                + "This will cause a noticeable performance degradation. Consider using a better operating system.");
    }
    if (getLastModified() == null || destDirFile.lastModified() <= getLastModified().getTime()) {
        setLastModified(new Date(destDirFile.lastModified() - 1));
    }
    InputStream in = new BufferedInputStream(new FileInputStream(tmpZipFile));
    ZipInputStream zin = new ZipInputStream(in);
    ZipEntry e;
    while ((e = zin.getNextEntry()) != null) {
        String destName = destinationDir + "/" + e.getName();
        if (e.isDirectory()) {
            log.debug("Creating dir " + destName);
            new File(destName).mkdirs();
        } else {
            log.debug("Creating file " + destName);
            unzip(zin, destName, e.getName());
        }
    }
    zin.close();
}

From source file:org.apache.maven.plugin.dependency.fromConfiguration.TestUnpackMojo.java

public void testUnpackOverWriteIfNewer() throws Exception {
    final long now = System.currentTimeMillis();

    setSilent(mojo, false);/*  w w  w  .j a  va  2  s. com*/
    stubFactory.setCreateFiles(true);
    Artifact artifact = stubFactory.getSnapshotArtifact();
    assertTrue(artifact.getFile().setLastModified(now - 20000));

    ArtifactItem item = new ArtifactItem(artifact);

    List<ArtifactItem> list = Collections.singletonList(item);
    mojo.setArtifactItems(list);
    mojo.setOverWriteIfNewer(true);
    mojo.execute();
    File unpackedFile = getUnpackedFile(item);

    // round down to the last second
    long time = now;
    time = time - (time % 1000);
    // go back 10 more seconds for linux
    time -= 10000;
    // set to known value
    assertTrue(unpackedFile.setLastModified(time));
    // set source to be newer was 4s but test is brittle on MacOS if less than 5s
    assertTrue(artifact.getFile().setLastModified(time + 5000));

    // manually set markerfile (must match getMarkerFile in DefaultMarkerFileHandler)
    File marker = new File(mojo.getMarkersDirectory(), artifact.getId().replace(':', '-') + ".marker");
    assertTrue(marker.setLastModified(time));

    displayFile("unpackedFile", unpackedFile);
    displayFile("artifact    ", artifact.getFile());
    displayFile("marker      ", marker);
    System.out.println("mojo.execute()");
    mojo.execute();
    displayFile("unpackedFile", unpackedFile);
    displayFile("artifact    ", artifact.getFile());
    displayFile("marker      ", marker);
    System.out.println("marker.lastModified() = " + marker.lastModified());
    System.out.println("unpackedFile.lastModified() = " + unpackedFile.lastModified());
    assertTrue("unpackedFile '" + unpackedFile + "' lastModified() == " + marker.lastModified()
            + ": should be different", marker.lastModified() != unpackedFile.lastModified());
}

From source file:mendeley2kindle.KindleDAO.java

public void saveFile(MFile file, boolean exportHighlights) throws URISyntaxException, IOException {
    log.log(Level.FINER, "Exporting a document: " + file.getLocalUrl());
    File f = new File(new URI(file.getLocalUrl()));
    FileInputStream fis = new FileInputStream(f);

    File f2 = new File(toKindleLocalPath(file));
    if (f.lastModified() <= f2.lastModified()) {
        log.log(Level.FINE, "No need to save: " + f2);
        return;/*from  w w w  .  j  av a  2 s  .  c om*/
    }

    f2.getParentFile().mkdirs();
    FileOutputStream fos = new FileOutputStream(f2);

    byte[] buf = new byte[4096];
    for (int read = 0; (read = fis.read(buf)) > 0;) {
        fos.write(buf, 0, read);
    }
    fos.close();
    fis.close();
    f2.setLastModified(f.lastModified());
    log.log(Level.FINE, "Exported a document: " + f2);
}