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.apache.jackrabbit.core.data.FileDataStore.java

/**
 * Returns the record with the given identifier. Note that this method
 * performs no sanity checks on the given identifier. It is up to the
 * caller to ensure that only identifiers of previously created data
 * records are used.// w ww.  jav  a 2s . com
 *
 * @param identifier data identifier
 * @return identified data record
 */
public DataRecord getRecord(DataIdentifier identifier) {
    File file = getFile(identifier);
    synchronized (this) {
        if (minModifiedDate != 0 && file.exists() && file.canWrite()) {
            if (file.lastModified() < minModifiedDate) {
                file.setLastModified(System.currentTimeMillis());
            }
        }
        usesIdentifier(identifier);
    }
    return new FileDataRecord(identifier, file);
}

From source file:entity.files.SYSFilesTools.java

/**
 * <code>getFile(SYSFiles file)</code> holt eine Datei vom FTP Server entsprechend der Angaben aus der EntityBean.
 * Die Methode geht dabei wie folgt vor:
 * <ol>/* www. j  a v  a 2 s .  co  m*/
 * <li>Es wird nachgeprft, ob es einen passenden Eintrag in der DB-Tabelle <i>SYSFiles</i> gibt.</li>
 * <li>Gibt es die Datei schon und hat sie auch die korrekte MD5 Signatur ?
 * <ul>
 * <li>Wenn ja, dann wird einfach ein File auf die Datei zurckgegeben. <b>RETURN</b></li>
 * <li>Wenn nicht, dann geht die Bearbeitung weiter.</li>
 * </ul>
 * <li>Datei wird vom FTP Server geholt.</li>
 * <li>Der Timestamp des letzten Zugriffs wird wieder hergestellt.</li>
 * <li>Wenn die letzten beiden Schritte erfolgreich waren, dann wird ein File als Ergebnis zurckgegeben. null, bei Fehler.</li>
 * </ol>
 *
 * @param sysfile - Datei, die vom FTP Server geholt werden soll.
 * @return File Objekt der geladenen Datei, null bei Fehler.
 */
private static File getFile(SYSFiles sysfile, EventListener eventListener) {
    File target = null;
    try {

        FileTransferClient ftp = getFTPClient();

        String sep = System.getProperties().getProperty("file.separator"); // Fileseparator

        target = new File(OPDE.getOPCache() + sep + sysfile.getFilename());
        // File present in cache directory ?
        if (!target.exists() || !SYSTools.getMD5Checksum(target).equals(sysfile.getMd5())) {
            OPDE.info(SYSTools.xx("misc.msg.download") + ": " + OPDE.getProps().getProperty("FTPServer") + "://"
                    + OPDE.getProps().getProperty("FTPWorkingDirectory") + "/" + sysfile.getFilename());
            FileUtils.deleteQuietly(target);

            ftp.setEventListener(eventListener);
            ftp.downloadFile(OPDE.getOPCache() + sep + sysfile.getFilename(), sysfile.getRemoteFilename());
            target = new File(OPDE.getOPCache() + sep + sysfile.getFilename());
            target.setLastModified(sysfile.getFiledate().getTime());
        }

        ftp.disconnect();
    } catch (FTPException ftpex) {
        OPDE.getDisplayManager().addSubMessage(new DisplayMessage("FTPError: " + ftpex.getMessage(),
                "SYSFilesTools.getFile(SYSFiles, EventListener)"));
        target = null;
    } catch (Exception ex) {
        OPDE.fatal(ex);
    }
    return target;
}

From source file:org.mule.util.FileUtils.java

/**
 * Internal copy file method./*  ww  w  .  j ava  2  s  .c o  m*/
 * 
 * @param srcFile the validated source file, must not be <code>null</code>
 * @param destFile the validated destination file, must not be <code>null</code>
 * @param preserveFileDate whether to preserve the file date
 * @throws IOException if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileChannel input = new FileInputStream(srcFile).getChannel();
    try {
        FileChannel output = new FileOutputStream(destFile).getChannel();
        try {
            output.transferFrom(input, 0, input.size());
        } finally {
            closeQuietly(output);
        }
    } finally {
        closeQuietly(input);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }
}

From source file:org.jboss.tools.central.jobs.AbstractRefreshJob.java

@Override
public IStatus run(IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }/*  w ww. j a v  a2s  .  c o  m*/
    exception = null;
    long urlModified = -1;
    if (!forcedDownload) {
        urlModified = getUrlModified();
        if (exception != null) {
            return Status.CANCEL_STATUS;
        }
    }
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }
    if (forcedDownload || cacheModified == 0 || urlModified != cacheModified) {
        try {
            File tempFile = File.createTempFile("news", ".xml");
            tempFile.deleteOnExit();
            OutputStream destination = new FileOutputStream(tempFile);
            IStatus status = new URLTransportUtility().download(cacheFile.getName(), getUrlString(),
                    destination, TIME_OUT, monitor);
            URL url = getURL();
            if (monitor.isCanceled()) {
                return getValidEntries(monitor);
            }
            if (status.isOK() && url != null) {
                cacheModified = new URLTransportUtility().getLastModified(url);
                FileUtils.copyFile(tempFile, cacheFile);
                tempFile.delete();
                if (monitor.isCanceled()) {
                    return getValidEntries(monitor);
                }
                cacheFile.setLastModified(cacheModified);
                getEntries(cacheFile);
            } else {
                setException(status.getException());
            }
        } catch (Exception e) {
            return getValidEntries(monitor);
        }
    }
    if (monitor.isCanceled()) {
        return getValidEntries(monitor);
    }
    if (!getEntries().isEmpty()) {
        try {
            File validCacheFile = getValidCacheFile();
            if (!validCacheFile.isFile() || cacheFile.lastModified() != validCacheFile.lastModified()) {
                FileUtils.copyFile(cacheFile, getValidCacheFile());
                validCacheFile.setLastModified(cacheFile.lastModified());
            }
        } catch (Exception e) {
            exception = e;
            return getValidEntries(monitor);
        }
    } else {
        return getValidEntries(monitor);
    }
    return Status.OK_STATUS;
}

From source file:org.apache.archiva.policies.ReleasePolicyTest.java

private void assertReleasesPolicy(String 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");
    }/*w w  w . j a  v  a  2 s .  com*/

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

    File targetDir = ChecksumPolicyTest.getTestFile("target/test-policy/");
    File localFile = new File(targetDir, path);

    if (localFile.exists()) {
        localFile.delete();
    }

    if (createLocalFile) {
        localFile.getParentFile().mkdirs();
        FileUtils.writeStringToFile(localFile, "random-junk");
        localFile.setLastModified(localFile.lastModified() - generatedLocalFileUpdateDelta);
    }

    policy.applyPolicy(setting, request, localFile);
}

From source file:org.apache.archiva.policies.SnapshotsPolicyTest.java

private void assertSnapshotPolicy(String 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");
    }// w  w w . j  av  a2 s .co  m

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

    File targetDir = ChecksumPolicyTest.getTestFile("target/test-policy/");
    File localFile = new File(targetDir, path);

    if (localFile.exists()) {
        localFile.delete();
    }

    if (createLocalFile) {
        localFile.getParentFile().mkdirs();
        FileUtils.writeStringToFile(localFile, "random-junk");
        localFile.setLastModified(localFile.lastModified() - generatedLocalFileUpdateDelta);
    }

    policy.applyPolicy(setting, request, localFile);
}

From source file:org.artifactory.util.ZipUtils.java

/**
 * Extracts the given zip entry//from   w w w  .  j  ava  2 s  .c om
 *
 * @param sourceArchive        Archive that is being extracted
 * @param destinationDirectory Extracted file destination
 * @param zipInputStream       Input stream of archive
 * @param entryName            Entry to extract
 * @param entryDate            Last modification date of zip entry
 * @param isEntryDirectory     Indication if the entry is a directory or not
 * @throws IOException
 */
private static void extractFile(File sourceArchive, File destinationDirectory, InputStream zipInputStream,
        String entryName, Date entryDate, boolean isEntryDirectory) throws IOException {

    File resolvedEntryFile = org.codehaus.plexus.util.FileUtils.resolveFile(destinationDirectory, entryName);
    try {
        File parentFile = resolvedEntryFile.getParentFile();

        //If the parent file isn't null, attempt to create it because it might not exist
        if (parentFile != null) {
            parentFile.mkdirs();
        }

        if (isEntryDirectory) {
            //Create directory entry
            resolvedEntryFile.mkdirs();
        } else {
            //Extract file entry
            byte[] buffer = new byte[1024];
            int length;
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(resolvedEntryFile);

                while ((length = zipInputStream.read(buffer)) >= 0) {
                    fileOutputStream.write(buffer, 0, length);
                }
            } finally {
                IOUtils.closeQuietly(fileOutputStream);
            }
        }

        //Preserve last modified date
        resolvedEntryFile.setLastModified(entryDate.getTime());
    } catch (FileNotFoundException ex) {
        throw new RuntimeException("Can't extract file " + sourceArchive.getPath(), ex);
    }
}

From source file:net.solarnetwork.node.backup.FileBackupResourceProvider.java

@Override
public boolean restoreBackupResource(BackupResource resource) {
    if (resourceDirectories != null && resourceDirectories.length > 0) {
        for (String path : resourceDirectories) {
            File rootDir = new File(rootPath, path);
            File backupFile = new File(resource.getBackupPath());
            if (backupFile.getAbsolutePath().startsWith(rootDir.getAbsolutePath())) {
                if (!backupFile.getParentFile().isDirectory() && !backupFile.getParentFile().mkdirs()) {
                    log.warn("Unable to create directory {} to restore file {} into", backupFile.getParent(),
                            resource.getBackupPath());
                }// w ww . j a  v a  2s.  co  m
                try {
                    // save to temp file first, then we'll rename
                    File tempFile = new File(backupFile.getParentFile(), "." + backupFile.getName());
                    log.debug("Installing resource {} => {}", resource.getBackupPath(), tempFile);
                    FileCopyUtils.copy(resource.getInputStream(), new FileOutputStream(tempFile));
                    tempFile.setLastModified(resource.getModificationDate());
                    moveTemporaryResourceFile(tempFile, backupFile);
                } catch (IOException e) {
                    log.error("Unable to restore backup resource {} to {}: {}", resource.getBackupPath(),
                            rootDir.getPath(), e.getMessage());
                }
                return true;
            }
        }
    }
    return false;
}

From source file:org.springframework.integration.sftp.outbound.SftpServerOutboundTests.java

@Test
@SuppressWarnings("unchecked")
public void testInt3172LocalDirectoryExpressionMGETRecursive() throws IOException {
    String dir = "sftpSource/";
    long modified = setModifiedOnSource1();
    File secondRemote = new File(getSourceRemoteDirectory(), "sftpSource2.txt");
    secondRemote.setLastModified(System.currentTimeMillis() - 1_000_000);
    this.inboundMGetRecursive.send(new GenericMessage<Object>(dir + "*"));
    Message<?> result = this.output.receive(1000);
    assertNotNull(result);/*from ww  w  . ja v a 2 s.co  m*/
    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 + "subSftpSource"));

    File secondTarget = new File(getTargetLocalDirectory() + File.separator + "sftpSource", "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>(dir + "*"));
    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>(dir + "*"));
    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:de.schildbach.wallet.data.DynamicFeeLoader.java

private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile,
        final String userAgent) {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(url);//from w w  w . j  av a  2 s .c  o  m
    request.header("User-Agent", userAgent);
    if (targetFile.exists())
        request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified())));

    final OkHttpClient httpClient = Constants.HTTP_CLIENT.clone();
    httpClient.setConnectTimeout(5, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(5, TimeUnit.SECONDS);
    httpClient.setReadTimeout(5, TimeUnit.SECONDS);
    final Call call = httpClient.newCall(request.build());
    try {
        final Response response = call.execute();
        final int status = response.code();
        if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
            log.info("Dynamic fees not modified at {}, took {}", url, watch);
        } else if (status == HttpURLConnection.HTTP_OK) {
            final ResponseBody body = response.body();
            final FileOutputStream os = new FileOutputStream(tempFile);
            Io.copy(body.byteStream(), os);
            os.close();
            final Date lastModified = response.headers().getDate("Last-Modified");
            if (lastModified != null)
                tempFile.setLastModified(lastModified.getTime());
            body.close();
            if (!tempFile.renameTo(targetFile))
                throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile);
            watch.stop();
            log.info("Dynamic fees fetched from {}, took {}", url, watch);
        } else {
            log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url);
        }
    } catch (final Exception x) {
        log.warn("Problem when fetching dynamic fees rates from " + url, x);
    }
}