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.maven.plugins.TestLocalRepositoryMojo.java

/**
 * Create an empty artifact with creation date modification (for delay testing purpose)
 * @param file/*from w w w .ja v a 2s. c  o m*/
 * @param creationDateSinceToday
 * @throws IOException
 */
private void createArtifact(File file, int creationDateSinceToday) throws IOException {

    FileUtils.openOutputStream(file, false).close();

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, creationDateSinceToday);
    file.setLastModified(calendar.getTimeInMillis());
}

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

/**
 * The attempt here should result in file being transferred.
 * <p/>//  w w w  .  java2  s  .  co m
 * The file exists locally, is over 6 years old, and the policy is DAILY.
 *
 * @throws Exception
 */
@Test
public void testGetDefaultLayoutRemoteUpdate() throws Exception {
    String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
    setupTestableManagedRepository(path);

    File expectedFile = new File(managedDefaultDir, path);
    ArtifactReference artifact = managedDefaultRepository.toArtifactReference(path);

    assertTrue(expectedFile.exists());
    expectedFile.setLastModified(getPastDate().getTime());

    // Configure Connector (usually done within archiva.xml configuration)
    saveConnector(ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.DAILY,
            SnapshotsPolicy.DAILY, CachedFailuresPolicy.NO, false);

    // Attempt the proxy fetch.
    File downloadedFile = proxyHandler.fetchFromProxies(managedDefaultRepository, artifact);

    File proxiedFile = new File(REPOPATH_PROXIED1, path);
    assertFileEquals(expectedFile, downloadedFile, proxiedFile);
    assertNoTempFiles(expectedFile);
}

From source file:it.greenvulcano.util.zip.ZipHelper.java

/**
 * Performs the uncompression of a <code>zip</code> file, whose name and
 * parent directory are passed as arguments, on the local filesystem. The
 * content of the <code>zip</code> file will be uncompressed within a
 * specified target directory.<br>
 *
 * @param srcDirectory//w  w  w.j ava 2 s  . c  om
 *            the source parent directory of the file/s to be unzipped. Must
 *            be an absolute pathname.
 * @param zipFilename
 *            the name of the file to be unzipped. Cannot contain wildcards.
 * @param targetDirectory
 *            the target directory in which the content of the
 *            <code>zip</code> file will be unzipped. Must be an absolute
 *            pathname.
 * @throws IOException
 *             If any error occurs during file uncompression.
 * @throws IllegalArgumentException
 *             if the arguments are invalid.
 */
public void unzipFile(String srcDirectory, String zipFilename, String targetDirectory) throws IOException {

    File srcDir = new File(srcDirectory);

    if (!srcDir.isAbsolute()) {
        throw new IllegalArgumentException(
                "The pathname of the source parent directory is NOT absolute: " + srcDirectory);
    }

    if (!srcDir.exists()) {
        throw new IllegalArgumentException(
                "Source parent directory " + srcDirectory + " NOT found on local filesystem.");
    }

    if (!srcDir.isDirectory()) {
        throw new IllegalArgumentException("Source parent directory " + srcDirectory + " is NOT a directory.");
    }

    File srcZipFile = new File(srcDirectory, zipFilename);
    if (!srcZipFile.exists()) {
        throw new IllegalArgumentException(
                "File to be unzipped (" + srcZipFile.getAbsolutePath() + ") NOT found on local filesystem.");
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(srcZipFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry currEntry = entries.nextElement();
            if (currEntry.isDirectory()) {
                String targetSubdirPathname = currEntry.getName();
                File dir = new File(targetDirectory, targetSubdirPathname);
                FileUtils.forceMkdir(dir);
                dir.setLastModified(currEntry.getTime());
            } else {
                InputStream is = null;
                OutputStream os = null;
                File file = null;
                try {
                    is = zipFile.getInputStream(currEntry);
                    FileUtils.forceMkdir(new File(targetDirectory, currEntry.getName()).getParentFile());
                    file = new File(targetDirectory, currEntry.getName());
                    os = new FileOutputStream(file);
                    IOUtils.copy(is, os);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }

                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException exc) {
                        // Do nothing
                    }

                    if (file != null) {
                        file.setLastModified(currEntry.getTime());
                    }
                }
            }
        }
    } finally {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
        } catch (Exception exc) {
            // do nothing
        }
    }
}

From source file:org.wso2.carbon.apimgt.impl.certificatemgt.CertificateManagerImpl.java

/**
 * Modify the sslProfiles.xml file after modifying the certificate.
 *
 * @return : True if the file modification is success.
 *///from ww w . j  a  va  2 s. co m
private boolean touchSSLSenderConfigFile() {

    boolean success = false;
    File file = new File(SSL_PROFILE_FILE_PATH);
    if (file.exists()) {
        success = file.setLastModified(System.currentTimeMillis());
        if (success) {
            log.info("The Transport Sender will be re-initialized in few minutes.");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Error when modifying the sslprofiles.xml file");
            }
            log.error("Could not modify the file '" + PROFILE_CONFIG + "'");
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("sslprofiles.xml file not found.");
        }
        log.error("Could not find the file '" + PROFILE_CONFIG + "'");
    }
    return success;
}

From source file:jfs.sync.encfs.JFSEncfsFile.java

/**
 * @see JFSFile#setLastModified(long)//from   www.j a va  2s  . c om
 */
@Override
public boolean setLastModified(long time) {
    if (log.isDebugEnabled()) {
        log.debug("setLastModified() " + info.getPath() + "/" + info.getName());
    } // if
    boolean success = false;

    info.setModificationDate(time);

    if (log.isDebugEnabled()) {
        log.debug("setLastModified() " + file.getParentPath() + ":" + file.getName() + " - " + file.getPath());
    } // if
      // TODO: Maybe fix this somewhere else...
    String encryptedPath = file.getEncryptedPath();
    int idx = encryptedPath.startsWith("//") ? 1 : 0;
    String encPath = getFileProducer().getRootPath() + encryptedPath.substring(idx);
    File encFile = new File(encPath);
    if (log.isDebugEnabled()) {
        log.debug("setLastModified(" + encPath + ") " + encFile.exists());
    } // if
    if (encFile.exists()) {
        encFile.setLastModified(info.getModificationDate());
    } // if

    return success;
}

From source file:org.apache.drill.exec.store.parquet.TestPushDownAndPruningForVarchar.java

private String createTable(String tableName, boolean removeMetadata) throws IOException {
    File rootDir = dirTestWatcher.getRootDir();
    File table = new File(rootDir, String.format("%s_%s", tableName, UUID.randomUUID()));
    FileUtils.copyDirectory(fileStore, table);
    File metadata = new File(table, ".drill.parquet_metadata");
    if (removeMetadata) {
        assertTrue(metadata.delete());//from  ww w.ja v  a  2  s.  c  o m
    } else {
        // metadata modification time should be higher
        // than directory modification time otherwise metadata file will be regenerated
        assertTrue(metadata.setLastModified(Instant.now().toEpochMilli()));
    }
    return String.format("dfs.`root`.`%s`", table.getName());
}

From source file:com.github.fritaly.dualcommander.Utils.java

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");
    }// ww  w.j  a va 2 s. co m

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
            pos += output.transferFrom(input, pos, count);
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

    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.apache.lucene.store.FSDirectory.java

/** Set the modified time of an existing file to now.
 *  @deprecated Lucene never uses this API; it will be
 *  removed in 4.0. *//*from  w  w w  .  jav  a 2s  .com*/
@Override
@Deprecated
public void touchFile(String name) {
    ensureOpen();
    File file = new File(directory, name);
    file.setLastModified(System.currentTimeMillis());
}

From source file:com.ikanow.infinit.e.application.handlers.polls.LogstashHarvestPollHandler.java

private void createConfigFileFromSource(SourcePojo src, long fileTime, String logstashDirName) {
    // Ignore anything malformed:
    if (null == src.getProcessingPipeline() || src.getProcessingPipeline().isEmpty()) {
        setSourceError(src.getId(), "Internal logic error: no processing pipeline");
        return;/*from  w  w w  .  jav  a2  s  .c  om*/
    }
    SourcePipelinePojo px = src.getProcessingPipeline().iterator().next();
    if ((null == px.logstash) || (null == px.logstash.config)) {
        setSourceError(src.getId(), "Internal logic error: no logstash block");
        return;
    }

    // Validate/tranform the configuration:
    StringBuffer errMessage = new StringBuffer();
    String logstashConfig = LogstashConfigUtils.validateLogstashInput(src.getKey(), px.logstash.config,
            errMessage, true);
    if (null == logstashConfig) { // Validation error...
        setSourceError(src.getId(), errMessage.toString());
        return;
    } //TESTED

    logstashConfig = logstashConfig.replace("_XXX_DOTSINCEDB_XXX_",
            LOGSTASH_WD + ".sincedb_" + src.getId().toString());
    // Replacement for #LOGSTASH{host} - currently only replacement supported (+ #IKANOW{} in main code)
    try {
        logstashConfig = logstashConfig.replace("#LOGSTASH{host}",
                java.net.InetAddress.getLocalHost().getHostName());
    } catch (Exception e) {
        logstashConfig = logstashConfig.replace("#LOGSTASH{host}", "localhost.localdomain");

    }

    String output = null;
    if ((null != px.logstash.streaming) && !px.logstash.streaming) {
        output = this._testOutputTemplate_stashed;
    } else {
        output = this._testOutputTemplate_live;
    }

    logstashConfig = logstashConfig
            + output.replace("_XXX_CLUSTER_XXX_", _clusterName).replace("_XXX_SOURCEKEY_XXX_", src.getKey())
                    .replace("_XXX_COMMUNITY_XXX_", src.getCommunityIds().iterator().next().toString());

    File outFile = new File(logstashDirName + src.getId() + LOGSTASH_CONFIG_EXTENSION);

    try {
        FileOutputStream outStream = new FileOutputStream(outFile);
        IOUtils.write(logstashConfig, outStream);
        outFile.setLastModified(fileTime);

        setSourceSuccess(src.getId());

    } //TESTED
    catch (IOException e) {
        // Error out:
        setSourceError(src.getId(), outFile.getName() + ": " + e.getMessage());
    }
}

From source file:org.wso2.carbon.apimgt.impl.certificatemgt.CertificateManagerImpl.java

/**
 * Modify the listenerProfiles.xml file after modifying the certificate.
 *
 * @return : True if the file modification is success.
 *//*from  ww  w.  j av a2s .c o m*/
private boolean touchSSLListenerConfigFile() {
    boolean success = false;
    if (listenerProfileFilePath != null) {
        File file = new File(listenerProfileFilePath);
        if (file.exists()) {
            success = file.setLastModified(System.currentTimeMillis());
            if (success) {
                log.info("The Transport listener will be re-initialized in few minutes.");
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Error when modifying listener profile config file in path "
                            + listenerProfileFilePath);
                }
                log.error("Could not modify the file listener profile config file");
            }
        }
    } else {
        log.warn(
                "Mutual SSL file path for listener is not configured correctly in axis2.xml. Please recheck the "
                        + "relevant configuration under transport listener.");
    }
    return success;
}