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:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

protected File prepareSkinDir(String name, Date date, boolean overWrite) throws SkinException, IOException {
    File mySkinDir = getSkinDir(name);
    if (mySkinDir.exists()) {
        if (!mySkinDir.isDirectory()) {
            throw new SkinException("Unexepected file found '" + mySkinDir + "'");
        }//from  www .j  a  v  a2 s  .c om
        if (!overWrite) {
            throw new CannotOverwriteException("Cannot overwite existing skin '" + mySkinDir + "'");
        } else {
            validateSkinDir(mySkinDir);
            boolean myDeleted = FileSystemUtils.purge(mySkinDir);
            if (!myDeleted) {
                throw new SkinException("Cannot remove existing skin '" + mySkinDir + "'");
            }
        }
    }

    if (!mySkinDir.exists()) {
        boolean myMakeDir = mySkinDir.mkdirs();
        if (!myMakeDir) {
            throw new SkinException("Cannot create skin directory '" + mySkinDir + "'");
        }
    }
    mySkinDir.setLastModified(date.getTime());
    return mySkinDir;
}

From source file:de.tilman.synctool.SyncTool.java

/**
 * Determines what to do with two files at the same place in the file tree
 * on the source and the destination. This method also updates the database
 * for the source file.//w w w  .j a v  a  2  s. co  m
 */
private Operation getOperation(File srcFile, File destFile, boolean history) throws SQLException, IOException {

    if (destFile != null && destFile.exists()) {

        if (!history) {
            insertFileSql.setString(1, srcFile.getCanonicalPath());
            if (!dryRun)
                insertFileSql.execute();
        }

        if (srcFile.isDirectory()) {
            dirsCompared++;
            if (!dryRun && !ignoreDirAttribs) {
                if (srcFile.lastModified() != destFile.lastModified()
                //                     || srcFile.canExecute() != destFile.canExecute()
                //                     || srcFile.canRead() != destFile.canRead()
                //                     || srcFile.canWrite() != destFile.canWrite()
                ) {
                    log.info("Setting attributes for " + destFile);
                    destFile.setLastModified(srcFile.lastModified());
                    //                  destFile.setExecutable(srcFile.canExecute());
                    //                  destFile.setReadable(srcFile.canRead());
                    //                  destFile.setWritable(srcFile.canWrite());
                }
            }
            return Operation.NONE;
        }

        filesCompared++;

        if (consideredEqual(srcFile, destFile))
            return Operation.NONE;

        if (srcFile.lastModified() > destFile.lastModified())
            return Operation.COPY; // copy source file

        return Operation.COPYDESTINATION; // copy destination file
    }

    // if the file exists in the history, it has been deleted on the
    // target side and should also be deleted on the source side
    if (history) {
        deleteFileSql.setString(1, srcFile.getCanonicalPath());
        if (!dryRun)
            deleteFileSql.execute();
        return Operation.DELETE;
    }

    // if the file is not present in the synchronization history, it
    // has been added on the source side and should be copied
    insertFileSql.setString(1, srcFile.getCanonicalPath());
    if (!dryRun)
        insertFileSql.execute();
    return Operation.COPY; // copy source file

}

From source file:phex.util.FileUtils.java

/**
 * Copys the source file to the destination file. Old contents of the
 * destination file will be overwritten.
 * This is a optimized version of the org.apache.commons.io.FileUtils.copy
 * source, with larger file buffer for a faster copy process.
 *
 * @throws IOException in case an IO operation fails
 *//*from  ww  w .  ja v  a2s  . c o m*/
public static void copyFile(File source, File destination, long copyLength) throws IOException {
    // check source exists
    if (!source.exists()) {
        String message = "File " + source + " does not exist";
        throw new FileNotFoundException(message);
    }

    //does destinations directory exist ?
    if (destination.getParentFile() != null && !destination.getParentFile().exists()) {
        forceMkdir(destination.getParentFile());
    }

    //make sure we can write to destination
    if (destination.exists() && !destination.canWrite()) {
        String message = "Unable to open file " + destination + " for writing.";
        throw new IOException(message);
    }

    //makes sure it is not the same file
    if (source.getCanonicalPath().equals(destination.getCanonicalPath())) {
        String message = "Unable to write file " + source + " on itself.";
        throw new IOException(message);
    }

    if (copyLength == 0) {
        truncateFile(destination, 0);
    }

    FileInputStream input = null;
    FileOutputStream output = null;
    try {
        input = new FileInputStream(source);
        output = new FileOutputStream(destination);
        long lengthLeft = copyLength;
        byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, lengthLeft + 1)];
        int read;
        while (lengthLeft > 0) {
            read = input.read(buffer);
            if (read == -1) {
                break;
            }
            lengthLeft -= read;
            output.write(buffer, 0, read);
        }
        output.flush();
        output.getFD().sync();
    } finally {
        IOUtil.closeQuietly(input);
        IOUtil.closeQuietly(output);
    }

    //file copy should preserve file date
    destination.setLastModified(source.lastModified());
}

From source file:com.synopsys.integration.blackduck.codelocation.signaturescanner.command.ScannerZipInstaller.java

private void downloadIfModified(File scannerExpansionDirectory, File versionFile, String downloadUrl)
        throws IOException, IntegrationException, ArchiveException {
    long lastTimeDownloaded = versionFile.lastModified();
    logger.debug(String.format("last time downloaded: %d", lastTimeDownloaded));

    Request downloadRequest = new Request.Builder(downloadUrl).build();
    Optional<Response> optionalResponse = intHttpClient.executeGetRequestIfModifiedSince(downloadRequest,
            lastTimeDownloaded);/*from  w  w  w.j  a  v a 2 s  . co  m*/
    if (optionalResponse.isPresent()) {
        Response response = optionalResponse.get();
        try {
            logger.info("Downloading the Black Duck Signature Scanner.");
            try (InputStream responseStream = response.getContent()) {
                logger.info(String.format(
                        "If your Black Duck server has changed, the contents of %s may change which could involve deleting files - please do not place items in the expansion directory as this directory is assumed to be under blackduck-common control.",
                        scannerExpansionDirectory.getAbsolutePath()));
                cleanupZipExpander.expand(responseStream, scannerExpansionDirectory);
            }
            long lastModifiedOnServer = response.getLastModified();
            versionFile.setLastModified(lastModifiedOnServer);

            ScanPaths scanPaths = scanPathsUtility
                    .determineSignatureScannerPaths(scannerExpansionDirectory.getParentFile());
            File javaExecutable = new File(scanPaths.getPathToJavaExecutable());
            File oneJar = new File(scanPaths.getPathToOneJar());
            File scanExecutable = new File(scanPaths.getPathToScanExecutable());
            javaExecutable.setExecutable(true);
            oneJar.setExecutable(true);
            scanExecutable.setExecutable(true);

            logger.info(String.format("Black Duck Signature Scanner downloaded successfully."));
        } finally {
            response.close();
        }
    } else {
        logger.debug(
                "The Black Duck Signature Scanner has not been modified since it was last downloaded - skipping download.");
    }
}

From source file:org.apache.archiva.converter.artifact.LegacyToDefaultConverterTest.java

@Test
public void testUnmodifiedArtifact() throws Exception, InterruptedException {
    // test the unmodified artifact is untouched

    Artifact artifact = createArtifact("test", "unmodified-artifact", "1.0.0");
    Artifact pomArtifact = createPomArtifact(artifact);

    File sourceFile = new File(sourceRepository.getBasedir(), sourceRepository.pathOf(artifact));
    File sourcePomFile = new File(sourceRepository.getBasedir(), sourceRepository.pathOf(pomArtifact));
    File targetFile = new File(targetRepository.getBasedir(), targetRepository.pathOf(artifact));
    File targetPomFile = new File(targetRepository.getBasedir(), targetRepository.pathOf(pomArtifact));

    assertTrue("Check target file exists", targetFile.exists());
    assertTrue("Check target POM exists", targetPomFile.exists());

    sourceFile.setLastModified(System.currentTimeMillis());
    sourcePomFile.setLastModified(System.currentTimeMillis());

    long origTime = targetFile.lastModified();
    long origPomTime = targetPomFile.lastModified();

    // Need to guarantee last modified is not equal
    Thread.sleep(SLEEP_MILLIS);//w w  w.j av a  2 s  .  c o  m

    artifactConverter.convert(artifact, targetRepository);
    checkSuccess(artifactConverter);

    compareFiles(sourceFile, targetFile);
    compareFiles(sourcePomFile, targetPomFile);

    assertEquals("Check artifact unmodified", origTime, targetFile.lastModified());
    assertEquals("Check POM unmodified", origPomTime, targetPomFile.lastModified());
}

From source file:org.apache.archiva.converter.artifact.LegacyToDefaultConverterTest.java

@Test
public void testModifedArtifactFails() throws Exception {
    // test that it fails when the source artifact has changed and is different to the existing artifact in the
    // target repository

    Artifact artifact = createArtifact("test", "modified-artifact", "1.0.0");
    Artifact pomArtifact = createPomArtifact(artifact);

    File sourceFile = new File(sourceRepository.getBasedir(), sourceRepository.pathOf(artifact));
    File sourcePomFile = new File(sourceRepository.getBasedir(), sourceRepository.pathOf(pomArtifact));
    File targetFile = new File(targetRepository.getBasedir(), targetRepository.pathOf(artifact));
    File targetPomFile = new File(targetRepository.getBasedir(), targetRepository.pathOf(pomArtifact));

    assertTrue("Check target file exists", targetFile.exists());
    assertTrue("Check target POM exists", targetPomFile.exists());

    sourceFile.setLastModified(System.currentTimeMillis());
    sourcePomFile.setLastModified(System.currentTimeMillis());

    long origTime = targetFile.lastModified();
    long origPomTime = targetPomFile.lastModified();

    // Need to guarantee last modified is not equal
    Thread.sleep(SLEEP_MILLIS);/*from  www .  j  a  va  2s  . co  m*/

    artifactConverter.convert(artifact, targetRepository);
    checkWarnings(artifactConverter, 2);

    assertHasWarningReason(artifactConverter, Messages.getString("failure.target.already.exists"));

    assertEquals("Check unmodified", origTime, targetFile.lastModified());
    assertEquals("Check unmodified", origPomTime, targetPomFile.lastModified());

    ArtifactRepositoryMetadata metadata = new ArtifactRepositoryMetadata(artifact);
    File metadataFile = new File(targetRepository.getBasedir(),
            targetRepository.pathOfRemoteRepositoryMetadata(metadata));
    assertFalse("Check metadata not created", metadataFile.exists());
}

From source file:org.apache.archiva.converter.artifact.LegacyToDefaultConverterTest.java

@Test
public void testDryRunFailure() throws Exception {
    // test dry run does nothing on a run that will fail, and returns failure

    artifactConverter = applicationContext.getBean("artifactConverter#dryrun-repository-converter",
            ArtifactConverter.class);

    Artifact artifact = createArtifact("test", "modified-artifact", "1.0.0");
    Artifact pomArtifact = createPomArtifact(artifact);

    File sourceFile = new File(sourceRepository.getBasedir(), sourceRepository.pathOf(artifact));
    File sourcePomFile = new File(sourceRepository.getBasedir(), sourceRepository.pathOf(pomArtifact));
    File targetFile = new File(targetRepository.getBasedir(), targetRepository.pathOf(artifact));
    File targetPomFile = new File(targetRepository.getBasedir(), targetRepository.pathOf(pomArtifact));

    assertTrue("Check target file exists", targetFile.exists());
    assertTrue("Check target POM exists", targetPomFile.exists());

    sourceFile.setLastModified(System.currentTimeMillis());
    sourcePomFile.setLastModified(System.currentTimeMillis());

    long origTime = targetFile.lastModified();
    long origPomTime = targetPomFile.lastModified();

    // Need to guarantee last modified is not equal
    Thread.sleep(SLEEP_MILLIS);/*from   ww  w .j a v a  2s  .co  m*/

    // clear warning before test related to MRM-1638
    artifactConverter.clearWarnings();
    artifactConverter.convert(artifact, targetRepository);
    checkWarnings(artifactConverter, 2);

    assertHasWarningReason(artifactConverter, Messages.getString("failure.target.already.exists"));

    assertEquals("Check unmodified", origTime, targetFile.lastModified());
    assertEquals("Check unmodified", origPomTime, targetPomFile.lastModified());

    ArtifactRepositoryMetadata metadata = new ArtifactRepositoryMetadata(artifact);
    File metadataFile = new File(targetRepository.getBasedir(),
            targetRepository.pathOfRemoteRepositoryMetadata(metadata));
    assertFalse("Check metadata not created", metadataFile.exists());
}

From source file:org.geoserver.security.xml.XMLUserGroupServiceTest.java

@Test
public void testDynamicReload() throws Exception {
    File xmlFile = File.createTempFile("users", ".xml");
    FileUtils.copyURLToFile(getClass().getResource("usersTemplate.xml"), xmlFile);
    GeoServerUserGroupService service1 = createUserGroupService("reload1", xmlFile.getCanonicalPath());
    GeoServerUserGroupService service2 = createUserGroupService("reload2", xmlFile.getCanonicalPath());

    GeoServerUserGroupStore store1 = createStore(service1);

    GeoServerUserGroup group = store1.createGroupObject("group", true);

    checkEmpty(service1);//  ww  w  .j a  v  a2 s. c  om
    checkEmpty(service2);

    // prepare for syncing

    UserGroupLoadedListener listener = new UserGroupLoadedListener() {

        @Override
        public void usersAndGroupsChanged(UserGroupLoadedEvent event) {
            synchronized (this) {
                this.notifyAll();
            }
        }
    };

    service2.registerUserGroupLoadedListener(listener);

    // modifiy store1
    store1.addGroup(group);
    store1.store();
    assertTrue(service1.getUserGroups().size() == 1);
    assertTrue(service1.getGroupCount() == 1);

    // increment lastmodified adding a second manually, the test is too fast
    xmlFile.setLastModified(xmlFile.lastModified() + 2000);

    // wait for the listener to unlock when 
    // service 2 triggers a load event
    synchronized (listener) {
        listener.wait();
    }

    // here comes the magic !!!
    assertTrue(service2.getUserGroups().size() == 1);
    assertTrue(service2.getGroupCount() == 1);
}

From source file:org.torproject.collector.bridgedescs.TarballBuilder.java

/** Writes the previously configured tarball with all contained files to the
 * given file, or fail if the file extension is not known. */
void build(File directory) throws IOException {
    File tarballFile = new File(directory, this.tarballFileName);
    TarArchiveOutputStream taos = null;// www.  ja  v  a2s .  c o m
    if (this.tarballFileName.endsWith(".tar.gz")) {
        taos = new TarArchiveOutputStream(
                new GzipCompressorOutputStream(new BufferedOutputStream(new FileOutputStream(tarballFile))));
    } else if (this.tarballFileName.endsWith(".tar.bz2")) {
        taos = new TarArchiveOutputStream(
                new BZip2CompressorOutputStream(new BufferedOutputStream(new FileOutputStream(tarballFile))));
    } else if (this.tarballFileName.endsWith(".tar")) {
        taos = new TarArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(tarballFile)));
    } else {
        fail("Unknown file extension: " + this.tarballFileName);
    }
    for (Map.Entry<String, TarballFile> file : this.tarballFiles.entrySet()) {
        TarArchiveEntry tae = new TarArchiveEntry(file.getKey());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        for (DescriptorBuilder descriptorBuilder : file.getValue().descriptorBuilders) {
            descriptorBuilder.build(baos);
        }
        tae.setSize(baos.size());
        tae.setModTime(file.getValue().modifiedMillis);
        taos.putArchiveEntry(tae);
        taos.write(baos.toByteArray());
        taos.closeArchiveEntry();
    }
    taos.close();
    tarballFile.setLastModified(this.modifiedMillis);
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static void touch(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    try {/*from w ww .ja va 2 s  .  c o m*/
        if (ArgList.length == 1 && !isNull(ArgList[0]) && !isUndefined(ArgList[0])) {
            File file = new File((String) ArgList[0]);
            boolean success = file.createNewFile();
            if (!success) {
                file.setLastModified(System.currentTimeMillis());
            }
        } else {
            throw new RuntimeException("The function call touch requires 1 valid argument.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}