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.mule.module.launcher.DeploymentServiceTestCase.java

@Test
public void testTracksAppConfigUpdateTime() throws Exception {
    final URL url = getClass().getResource("/dummy-app.zip");
    File appFolder = new File(appsDir.getPath(), "dummy-app");
    FileUtils.unzip(new File(url.toURI()), appFolder);

    // Sets a modification time in the future
    File configFile = new File(appFolder, "mule-config.xml");
    configFile.setLastModified(System.currentTimeMillis() + ONE_HOUR_IN_MILLISECONDS);

    deploymentService.start();/* w w w  . j  a v  a 2s.co m*/
    assertDeploymentSuccess(deploymentListener, "dummy-app");
    reset(deploymentListener);

    assertNoDeploymentInvoked(deploymentListener);
}

From source file:org.rhq.plugins.storage.StorageNodeComponentITest.java

@Test(dependsOnMethods = "takeSnapshotsKeepLastNAndMove", priority = 3)
public void takeSnapshotsDeleteOlderThanN() {
    OperationManager operationManager = PluginContainer.getInstance().getOperationManager();
    OperationServicesAdapter operationsService = new OperationServicesAdapter(operationManager);

    long timeout = 1000 * 60;
    OperationContextImpl operationContext = new OperationContextImpl(storageNode.getId(), operationManager);

    // mark snaphosts left by takeSnapshotsKeepLastNAndMove test as 2 days old
    for (File parent : getSnaphostDirs()) {
        File snapshot = new File(parent, TAKE_SNAPSHOTS_MOVE_NAME);
        snapshot.setLastModified(System.currentTimeMillis() - (2 * 86400L * 1000L));
    }//from ww w .ja  v a  2s  .com

    int delOlderThan = 3;

    Configuration params = Configuration.builder().addSimple("retentionStrategy", "Delete Older Than N days")
            .addSimple("count", delOlderThan).build();
    OperationServicesResult result = operationsService.invokeOperation(operationContext, "takeSnapshot", params,
            timeout);
    assertEquals(result.getResultCode(), OperationServicesResultCode.SUCCESS,
            "The takeSnapshot operation failed.");
    // takeSnapshotsKeepLastNAndMove left 1 snapshot so now there has to be 2 of them
    assertSnaphotCount(getSnaphostDirs(), 2);

    File moveLocation = new File(basedir, "snaphosts-moved-2");
    delOlderThan = 1;
    params = Configuration.builder().addSimple("retentionStrategy", "Delete Older Than N days")
            .addSimple("count", delOlderThan).addSimple("deletionStrategy", "Move")
            .addSimple("location", moveLocation.getAbsolutePath()).build();
    result = operationsService.invokeOperation(operationContext, "takeSnapshot", params, timeout);
    assertEquals(result.getResultCode(), OperationServicesResultCode.SUCCESS,
            "The takeSnapshot operation failed.");
    // 2 snapshots left 1 created, but 1 moved
    assertSnaphotCount(getSnaphostDirs(), 2);
    assertSnaphotsContain(getMovedSnapshotDirs(moveLocation), TAKE_SNAPSHOTS_MOVE_NAME);
}

From source file:org.apache.jackrabbit.core.data.FileDataStore.java

/**
 * {@inheritDoc}/* ww w .  java2 s.  c om*/
 */
public DataRecord getRecordIfStored(DataIdentifier identifier) {
    File file = getFile(identifier);
    synchronized (this) {
        if (!file.exists()) {
            return null;
        }
        if (minModifiedDate != 0 && file.canWrite()) {
            if (file.lastModified() < minModifiedDate) {
                file.setLastModified(System.currentTimeMillis());
            }
        }
        usesIdentifier(identifier);
        return new FileDataRecord(identifier, file);
    }
}

From source file:hudson.PluginManager.java

/**
 * If the war file has any "/WEB-INF/plugins/*.hpi", extract them into the plugin directory.
 *//*from   w ww  .jav  a2s.c  om*/
private void loadBundledPlugins() {
    // this is used in tests, when we want to override the default bundled plugins with .hpl versions
    if (System.getProperty("hudson.bundled.plugins") != null) {
        return;
    }
    Set paths = context.getResourcePaths("/WEB-INF/plugins");
    if (paths == null)
        return; // crap
    for (String path : (Set<String>) paths) {
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        if (fileName.length() == 0) {
            // see http://www.nabble.com/404-Not-Found-error-when-clicking-on-help-td24508544.html
            // I suspect some containers are returning directory names.
            continue;
        }
        try {
            URL url = context.getResource(path);
            long lastModified = url.openConnection().getLastModified();
            File file = new File(rootDir, fileName);
            if (!file.exists() || file.lastModified() != lastModified) {
                FileUtils.copyURLToFile(url, file);
                file.setLastModified(url.openConnection().getLastModified());
                // lastModified is set for two reasons:
                // - to avoid unpacking as much as possible, but still do it on both upgrade and downgrade
                // - to make sure the value is not changed after each restart, so we can avoid
                // unpacking the plugin itself in ClassicPluginStrategy.explode
            }
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to extract the bundled plugin " + fileName, e);
        }
    }
}

From source file:org.apache.jackrabbit.core.data.FileDataStore.java

/**
 * {@inheritDoc}/*  w  w  w .  j  a  v  a 2 s .  co  m*/
 */
public DataRecord getRecordIfStored(DataIdentifier identifier) {
    File file = getFile(identifier);
    synchronized (this) {
        if (!file.exists()) {
            return null;
        }
        if (minModifiedDate != 0 && file.canWrite()) {
            if (file.lastModified() < minModifiedDate) {
                file.setLastModified(System.currentTimeMillis() + ACCESS_TIME_RESOLUTION);
            }
        }
        usesIdentifier(identifier);
        return new FileDataRecord(identifier, file);
    }
}

From source file:org.hardisonbrewing.s3j.FileSyncer.java

public GetObjectResult get(String path, boolean decrypt) throws Exception {

    if (!decrypt || privateKey == null) {
        return get(path);
    }/*from ww w.j a  va 2s .co m*/

    DataProperties properties = downloadProperties(path);
    String algorithm = properties.getProperty(PROP_ALGORITHM);
    long decryptedLength = properties.getLongProperty(PROP_DECRYPTED_LENGTH);
    long encryptedLength = properties.getLongProperty(PROP_ENCRYPTED_LENGTH);
    byte[] encryptedKey = properties.getBinaryProperty(PROP_KEY);
    long lastModified = properties.getLongProperty(PROP_LAST_MODIFIED);
    String originalFilePath = properties.getProperty(PROP_ORIG_FILE_PATH);

    System.out.println("  S3J Properties");
    PropertiesUtil.printProperties(properties);

    byte[] rawKey = RsaUtil.decrypt(privateKey, encryptedKey);

    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(rawKey, algorithm));

    String url = getUrl(path);
    HttpRequestBase httpRequest = new HttpGet(url);
    addHeaders(httpRequest, path);

    System.out.println("Downloading: " + url);
    HttpUtil.printHeaders(httpRequest);

    FileResponseHandler fileResponseHandler = new FileResponseHandler();
    fileResponseHandler.contentLength = encryptedLength;
    fileResponseHandler.cipher = cipher;

    File file = httpClient.execute(httpRequest, fileResponseHandler);
    file.setLastModified(lastModified);

    long fileLength = file.length();

    if (decryptedLength != fileLength) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("Downloaded size (");
        stringBuffer.append(fileLength);
        stringBuffer.append(") does not match the expected decrypted length (");
        stringBuffer.append(decryptedLength);
        stringBuffer.append(").");
        throw new IOException(stringBuffer.toString());
    }

    GetObjectResult response = new GetObjectResult();
    response.file = file;
    response.properties = properties;
    response.bucketPath = path;
    response.originalPath = originalFilePath;
    return response;
}

From source file:org.mule.module.launcher.DeploymentServiceTestCase.java

@Test
public void redeploysAppWhenConfigChanges() throws Exception {
    final URL url = getClass().getResource("/dummy-app.zip");
    assertNotNull("Test app file not found " + url, url);
    addAppArchive(url);//w  ww.j ava2  s  . c o m

    deploymentService.start();

    assertDeploymentSuccess(deploymentListener, "dummy-app");

    assertAppsDir(NONE, new String[] { "dummy-app" }, true);
    assertEquals("Application has not been properly registered with Mule", 1,
            deploymentService.getApplications().size());

    reset(deploymentListener);

    File configFile = new File(appsDir + "/dummy-app", "mule-config.xml");
    configFile.setLastModified(configFile.lastModified() + 1000);

    assertUndeploymentSuccess(deploymentListener, "dummy-app");
    assertDeploymentSuccess(deploymentListener, "dummy-app");
    assertEquals("Application has not been properly registered with Mule", 1,
            deploymentService.getApplications().size());
    assertAppsDir(NONE, new String[] { "dummy-app" }, true);
}

From source file:org.apache.maven.plugins.invoker.InstallMojo.java

private void copyFileIfDifferent(File src, File dst) throws IOException {
    if (src.lastModified() != dst.lastModified() || src.length() != dst.length()) {
        FileUtils.copyFile(src, dst);/*w  w  w. ja  va 2 s.co  m*/
        dst.setLastModified(src.lastModified());
    }
}

From source file:org.abstracthorizon.proximity.storage.local.WritableFileSystemStorage.java

public void storeItem(Item item) throws StorageException {
    if (!item.getProperties().isFile()) {
        throw new IllegalArgumentException("Only files can be stored!");
    }/*from  ww  w . j  a v  a 2s .  co  m*/
    logger.debug("Storing item in [{}] in storage directory {}", item.getProperties().getPath(),
            getStorageBaseDir());
    try {
        if (item.getStream() != null) {
            File file = new File(getStorageBaseDir(), item.getProperties().getPath());
            file.getParentFile().mkdirs();
            FileOutputStream os = new FileOutputStream(file);
            try {
                IOUtils.copy(item.getStream(), os);
                item.getStream().close();
                os.flush();
            } finally {
                os.close();
            }
            item.setStream(new FileInputStream(file));
            file.setLastModified(item.getProperties().getLastModified().getTime());
            if (isMetadataAware()) {
                item.getProperties().putAllMetadata(getProxiedItemPropertiesFactory()
                        .expandItemProperties(item.getProperties().getPath(), file, false).getAllMetadata());
                storeItemProperties(item.getProperties());
            }
        }
    } catch (IOException ex) {
        throw new StorageException("IOException in FS storage " + getStorageBaseDir(), ex);
    }
}

From source file:org.apache.archiva.consumers.core.repository.DaysOldRepositoryPurgeTest.java

@Test
public void testMetadataDrivenSnapshots() throws Exception {
    ManagedRepository repoConfiguration = getRepoConfiguration(TEST_REPO_ID, TEST_REPO_NAME);
    List<RepositoryListener> listeners = Collections.singletonList(listener);
    repoPurge = new DaysOldRepositoryPurge(getRepository(), repoConfiguration.getDaysOlder(),
            repoConfiguration.getRetentionCount(), repositorySession, listeners);

    String repoRoot = prepareTestRepos();

    String versionRoot = repoRoot + "/org/codehaus/plexus/plexus-utils/1.4.3-SNAPSHOT";

    Calendar currentDate = Calendar.getInstance(DateUtils.UTC_TIME_ZONE);
    setLastModified(versionRoot, currentDate.getTimeInMillis());

    String timestamp = new SimpleDateFormat("yyyyMMdd.HHmmss").format(currentDate.getTime());

    for (int i = 5; i <= 7; i++) {
        File jarFile = new File(versionRoot, "/plexus-utils-1.4.3-" + timestamp + "-" + i + ".jar");
        jarFile.createNewFile();/*from w w  w  .j a  va  2  s.c o  m*/
        File pomFile = new File(versionRoot, "/plexus-utils-1.4.3-" + timestamp + "-" + i + ".pom");
        pomFile.createNewFile();

        // set timestamp to older than 100 days for the first build, but ensure the filename timestamp is honoured instead
        if (i == 5) {
            jarFile.setLastModified(OLD_TIMESTAMP);
            pomFile.setLastModified(OLD_TIMESTAMP);
        }
    }

    // test listeners for the correct artifacts
    listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.codehaus.plexus", "plexus-utils",
            "1.4.3-20070113.163208-4", "plexus-utils-1.4.3-20070113.163208-4.jar");
    listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.codehaus.plexus", "plexus-utils",
            "1.4.3-20070113.163208-4", "plexus-utils-1.4.3-20070113.163208-4.pom");
    listenerControl.replay();

    repoPurge.process(PATH_TO_BY_DAYS_OLD_METADATA_DRIVEN_ARTIFACT);

    listenerControl.verify();

    // this should be deleted since the filename version (timestamp) is older than
    // 100 days even if the last modified date was <100 days ago
    assertDeleted(versionRoot + "/plexus-utils-1.4.3-20070113.163208-4.jar");
    assertDeleted(versionRoot + "/plexus-utils-1.4.3-20070113.163208-4.jar.sha1");
    assertDeleted(versionRoot + "/plexus-utils-1.4.3-20070113.163208-4.pom");
    assertDeleted(versionRoot + "/plexus-utils-1.4.3-20070113.163208-4.pom.sha1");

    // this should not be deleted because last modified date is <100 days ago
    assertExists(versionRoot + "/plexus-utils-1.4.3-SNAPSHOT.jar");
    assertExists(versionRoot + "/plexus-utils-1.4.3-SNAPSHOT.pom");

    for (int i = 5; i <= 7; i++) {
        assertExists(versionRoot + "/plexus-utils-1.4.3-" + timestamp + "-" + i + ".jar");
        assertExists(versionRoot + "/plexus-utils-1.4.3-" + timestamp + "-" + i + ".pom");
    }
}