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:com.virtualparadigm.packman.processor.JPackageManagerOld.java

public static boolean configure(File tempDir, Configuration configuration) {
    logger.info("PackageManager::configure()");
    boolean status = true;
    if (tempDir != null && configuration != null && !configuration.isEmpty()) {
        ST stringTemplate = null;/*from   w ww .  j  a v a  2 s  .c  o m*/
        String templateContent = null;
        long lastModified;

        Collection<File> patchFiles = FileUtils.listFiles(
                new File(tempDir.getAbsolutePath() + "/" + JPackageManagerOld.PATCH_DIR_NAME + "/"
                        + JPackageManagerOld.PATCH_FILES_DIR_NAME),
                TEMPLATE_SUFFIX_FILE_FILTER, DirectoryFileFilter.DIRECTORY);

        if (patchFiles != null) {
            for (File pfile : patchFiles) {
                logger.debug("  processing patch fileset file: " + pfile.getAbsolutePath());
                try {
                    lastModified = pfile.lastModified();
                    templateContent = FileUtils.readFileToString(pfile);
                    templateContent = templateContent.replace("${", "\\${");
                    templateContent = templateContent.replace("@", "\\@");
                    stringTemplate = new ST(JPackageManagerOld.ST_GROUP, templateContent);
                    //                       stringTemplate = new ST(FileUtils.readFileToString(pfile));
                    JPackageManagerOld.addTemplateAttributes(stringTemplate, configuration);
                    templateContent = stringTemplate.render();
                    templateContent = templateContent.replace("\\${", "${");
                    templateContent = templateContent.replace("\\@", "@");
                    FileUtils.writeStringToFile(pfile, templateContent);
                    pfile.setLastModified(lastModified);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        Collection<File> scriptFiles = FileUtils.listFiles(
                new File(tempDir.getAbsolutePath() + "/" + JPackageManagerOld.AUTORUN_DIR_NAME),
                TEMPLATE_SUFFIX_FILE_FILTER, DirectoryFileFilter.DIRECTORY);

        if (scriptFiles != null) {
            for (File scriptfile : scriptFiles) {
                logger.debug("  processing script file: " + scriptfile.getAbsolutePath());
                try {
                    lastModified = scriptfile.lastModified();
                    templateContent = FileUtils.readFileToString(scriptfile);
                    templateContent = templateContent.replace("${", "\\${");
                    templateContent = templateContent.replace("@", "\\@");
                    stringTemplate = new ST(JPackageManagerOld.ST_GROUP, templateContent);
                    //                       stringTemplate = new ST(FileUtils.readFileToString(pfile));
                    JPackageManagerOld.addTemplateAttributes(stringTemplate, configuration);
                    templateContent = stringTemplate.render();
                    templateContent = templateContent.replace("\\${", "${");
                    templateContent = templateContent.replace("\\@", "@");
                    FileUtils.writeStringToFile(scriptfile, templateContent);
                    scriptfile.setLastModified(lastModified);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return status;
}

From source file:org.datavaultplatform.common.io.FileCopy.java

/**
 * Internal copy directory method.// ww w  .j  ava  2 s. com
 * 
 * @param progress  the progress tracking object
 * @param srcDir  the validated source directory, must not be {@code null}
 * @param destDir  the validated destination directory, must not be {@code null}
 * @param filter  the filter to apply, null means copy all directories and files
 * @param preserveFileDate  whether to preserve the file date
 * @param exclusionList  List of files and directories to exclude from the copy, may be null
 * @throws IOException if an error occurs
 * @since 1.1
 */
private static void doCopyDirectory(Progress progress, File srcDir, File destDir, FileFilter filter,
        boolean preserveFileDate, List<String> exclusionList) throws IOException {
    // recurse
    File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
    if (srcFiles == null) { // null if abstract pathname does not denote a directory, or if an I/O error occurs
        throw new IOException("Failed to list contents of " + srcDir);
    }
    if (destDir.exists()) {
        if (destDir.isDirectory() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }
    } else {
        if (!destDir.mkdirs() && !destDir.isDirectory()) {
            throw new IOException("Destination '" + destDir + "' directory cannot be created");
        }
    }
    if (destDir.canWrite() == false) {
        throw new IOException("Destination '" + destDir + "' cannot be written to");
    }
    for (File srcFile : srcFiles) {
        File dstFile = new File(destDir, srcFile.getName());
        if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) {
            if (srcFile.isDirectory()) {
                doCopyDirectory(progress, srcFile, dstFile, filter, preserveFileDate, exclusionList);
            } else {
                doCopyFile(progress, srcFile, dstFile, preserveFileDate);
            }
        }
    }

    // Do this last, as the above has probably affected directory metadata
    if (preserveFileDate) {
        destDir.setLastModified(srcDir.lastModified());
    }

    progress.dirCount += 1;
}

From source file:com.sentaroh.android.SMBExplorer.FileIo.java

final public static boolean isSetLastModifiedFunctional(String lmp) {
    boolean result = false;
    File lf = new File(lmp + "/" + "SMBExplorerLastModifiedTest.temp");
    File dir = new File(lmp + "/");
    try {//from  ww  w .  j a v a 2  s. co m
        if (dir.canWrite()) {
            if (lf.exists())
                lf.delete();
            lf.createNewFile();
            result = lf.setLastModified(0);
            lf.delete();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    //      Log.v("","result="+result+", lmp="+lmp);
    return result;
}

From source file:de.xirp.plugin.PluginManager.java

/**
 * Extracts files from the plugins jar.// w w w .ja v a2s  . com
 * 
 * @param info
 *            the information about the plugin
 * @param destination
 *            destination for extraction
 * @param comparer
 *            comparer which returns <code>0</code> if an
 *            element from the jar should be extracted
 * @param replace
 *            string of the elements path which should be deleted
 * @param deleteOnExit
 *            <code>true</code> if the extracted files should be
 *            deleted on exit of the application.
 * @return <code>false</code> if an error occurred while
 *         extraction
 */
private static boolean extractFromJar(PluginInfo info, String destination, Comparable<String> comparer,
        String replace, boolean deleteOnExit) {
    if (logClass.isTraceEnabled()) {
        logClass.trace(Constants.LINE_SEPARATOR + "Extracting for Plugin: " + info.getDefaultName() //$NON-NLS-1$
                + " to path " + destination + Constants.LINE_SEPARATOR); //$NON-NLS-1$
    }
    ZipInputStream zip = null;
    FileInputStream in = null;
    try {
        in = new FileInputStream(info.getAbsoluteJarPath());
        zip = new ZipInputStream(in);

        ZipEntry entry = null;
        while ((entry = zip.getNextEntry()) != null) {
            // relative name with slashes to separate dirnames.
            String elementName = entry.getName();
            // Check if it's an entry within Plugin Dir.
            // Only need to extract these

            if (comparer.compareTo(elementName) == 0) {
                // Remove Help Dir Name, because we don't like
                // to extract this parent dir
                elementName = elementName.replaceFirst(replace + JAR_SEPARATOR, "").trim(); //$NON-NLS-1$ 

                if (!elementName.equalsIgnoreCase("")) { //$NON-NLS-1$
                    // if parent dir for File does not exist,
                    // create
                    // it
                    File elementFile = new File(destination, elementName);
                    if (!elementFile.exists()) {
                        elementFile.getParentFile().mkdirs();
                        if (deleteOnExit) {
                            DeleteManager.deleteOnShutdown(elementFile);
                        }
                    }

                    // Only extract files, directorys are created
                    // above with mkdirs
                    if (!entry.isDirectory()) {
                        FileOutputStream fos = new FileOutputStream(elementFile);
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = zip.read(buf)) > 0) {
                            fos.write(buf, 0, len);
                        }
                        fos.close();
                        elementFile.setLastModified(entry.getTime());
                    }
                    logClass.trace("Extracted: " + elementName + Constants.LINE_SEPARATOR); //$NON-NLS-1$
                }
            }
            zip.closeEntry();
        }

    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        return false;
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
    }

    return true;
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

@Override
public boolean restoreBackupResource(BackupResource resource) {
    if (resource != null && BACKUP_RESOURCE_NAME_KEYSTORE.equalsIgnoreCase(resource.getBackupPath())) {
        final File ksFile = new File(getKeyStorePath());
        final File ksDir = ksFile.getParentFile();
        if (!ksDir.isDirectory()) {
            if (!ksDir.mkdirs()) {
                log.warn("Error creating keystore directory {}", ksDir.getAbsolutePath());
                return false;
            }/* ww  w.ja v  a  2  s .c  o m*/
        }
        synchronized (this) {
            try {
                FileCopyUtils.copy(resource.getInputStream(), new FileOutputStream(ksFile));
                ksFile.setLastModified(resource.getModificationDate());
                return true;
            } catch (IOException e) {
                log.error("IO error restoring keystore resource {}: {}", ksFile.getAbsolutePath(),
                        e.getMessage());
                return false;
            }
        }
    }
    return false;
}

From source file:com.jpeterson.util.etag.FileETagTest.java

/**
 * Test the calculate method when using no flags.
 *//* ww w  .j a  v  a 2 s .  c om*/
public void test_calculateNoFlags() {
    File file;
    String content = "Hello, world!";
    FileETag etag;

    try {
        // create temporary file
        file = File.createTempFile("temp", "txt");

        // make sure that it gets cleaned up
        file.deleteOnExit();

        // put some date in the file
        FileOutputStream out = new FileOutputStream(file);
        out.write(content.getBytes());
        out.flush();
        out.close();

        // manipulate the last modified value to a "known" value
        SimpleDateFormat date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        long lastModified = date.parse("06/21/2007 11:19:36").getTime();
        file.setLastModified(lastModified);

        etag = new FileETag();
        etag.setFlags(0);
        String value = etag.calculate(file);

        assertNotNull("Unexpected value", value);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    } catch (IOException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    } catch (ParseException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    }
}

From source file:com.dattasmoon.pebble.plugin.EditNotificationActivity.java

public void save() {
    String selectedPackages = "";
    ArrayList<String> tmpArray = new ArrayList<String>();
    if (lvPackages == null || lvPackages.getAdapter() == null) {
        return;/*from ww  w  .j av  a2 s.c o  m*/
    }
    for (String strPackage : ((packageAdapter) lvPackages.getAdapter()).selected) {
        if (!strPackage.isEmpty()) {
            if (!tmpArray.contains(strPackage)) {
                tmpArray.add(strPackage);
                selectedPackages += strPackage + ",";
            }
        }
    }
    tmpArray.clear();
    tmpArray = null;
    if (!selectedPackages.isEmpty()) {
        selectedPackages = selectedPackages.substring(0, selectedPackages.length() - 1);
    }
    if (Constants.IS_LOGGABLE) {
        switch (mMode) {
        case OFF:
            Log.i(Constants.LOG_TAG, "Mode is: off");
            break;
        case EXCLUDE:
            Log.i(Constants.LOG_TAG, "Mode is: exclude");
            break;
        case INCLUDE:
            Log.i(Constants.LOG_TAG, "Mode is: include");
            break;
        }

        Log.i(Constants.LOG_TAG, "Package list is: " + selectedPackages);
    }

    if (mode == Mode.STANDARD) {

        Editor editor = sharedPreferences.edit();
        editor.putInt(Constants.PREFERENCE_MODE, mMode.ordinal());
        editor.putString(Constants.PREFERENCE_PACKAGE_LIST, selectedPackages);
        editor.putString(Constants.PREFERENCE_PKG_RENAMES, arrayRenames.toString());

        // we saved via the application, reset the variable if it exists
        editor.remove(Constants.PREFERENCE_TASKER_SET);

        // clear out legacy preference, if it exists
        editor.remove(Constants.PREFERENCE_EXCLUDE_MODE);

        // save!
        editor.commit();

        // notify service via file that it needs to reload the preferences
        File watchFile = new File(getFilesDir() + "PrefsChanged.none");
        if (!watchFile.exists()) {
            try {
                watchFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        watchFile.setLastModified(System.currentTimeMillis());
    } else if (mode == Mode.LOCALE) {
        if (!isCanceled()) {
            final Intent resultIntent = new Intent();
            final Bundle resultBundle = new Bundle();

            // set the version, title and body
            resultBundle.putInt(Constants.BUNDLE_EXTRA_INT_VERSION_CODE,
                    Constants.getVersionCode(getApplicationContext()));
            resultBundle.putInt(Constants.BUNDLE_EXTRA_INT_TYPE, Constants.Type.SETTINGS.ordinal());
            resultBundle.putInt(Constants.BUNDLE_EXTRA_INT_MODE, mMode.ordinal());
            resultBundle.putString(Constants.BUNDLE_EXTRA_STRING_PACKAGE_LIST, selectedPackages);
            resultBundle.putString(Constants.BUNDLE_EXTRA_STRING_PKG_RENAMES, arrayRenames.toString());
            String blurb = "";
            switch (mMode) {
            case OFF:
                blurb = getResources().getStringArray(R.array.mode_choices)[0];
                break;
            case INCLUDE:
                blurb = getResources().getStringArray(R.array.mode_choices)[2];
                break;
            case EXCLUDE:
                blurb = getResources().getStringArray(R.array.mode_choices)[1];
            }
            Log.i(Constants.LOG_TAG, resultBundle.toString());

            resultIntent.putExtra(com.twofortyfouram.locale.Intent.EXTRA_BUNDLE, resultBundle);
            resultIntent.putExtra(com.twofortyfouram.locale.Intent.EXTRA_STRING_BLURB, blurb);
            setResult(RESULT_OK, resultIntent);
        }
    }

}

From source file:org.apache.wiki.providers.VersioningFileProvider.java

/**
 *  {@inheritDoc}// w w  w. ja va  2  s .  c om
 *  
 *  Deleting versions has never really worked,
 *  JSPWiki assumes that version histories are "not gappy". 
 *  Using deleteVersion() is definitely not recommended.
 *  
 */
public void deleteVersion(String page, int version) throws ProviderException {
    File dir = findOldPageDir(page);

    int latest = findLatestVersion(page);

    if (version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1)) {
        //
        //  Delete the properties
        //
        try {
            Properties props = getPageProperties(page);
            props.remove(((latest > 0) ? latest : 1) + ".author");
            putPageProperties(page, props);
        } catch (IOException e) {
            log.error("Unable to modify page properties", e);
            throw new ProviderException("Could not modify page properties: " + e.getMessage());
        }

        // We can let the FileSystemProvider take care
        // of the actual deletion
        super.deleteVersion(page, WikiPageProvider.LATEST_VERSION);

        //
        //  Copy the old file to the new location
        //
        latest = findLatestVersion(page);

        File pageDir = findOldPageDir(page);
        File previousFile = new File(pageDir, Integer.toString(latest) + FILE_EXT);

        InputStream in = null;
        OutputStream out = null;

        try {
            if (previousFile.exists()) {
                in = new BufferedInputStream(new FileInputStream(previousFile));
                File pageFile = findPage(page);
                out = new BufferedOutputStream(new FileOutputStream(pageFile));

                FileUtil.copyContents(in, out);

                //
                // We need also to set the date, since we rely on this.
                //
                pageFile.setLastModified(previousFile.lastModified());
            }
        } catch (IOException e) {
            log.fatal("Something wrong with the page directory - you may have just lost data!", e);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }

        return;
    }

    File pageFile = new File(dir, "" + version + FILE_EXT);

    if (pageFile.exists()) {
        if (!pageFile.delete()) {
            log.error("Unable to delete page.");
        }
    } else {
        throw new NoSuchVersionException("Page " + page + ", version=" + version);
    }
}

From source file:com.ecyrd.jspwiki.providers.WikiVersioningFileProvider.java

public synchronized void putPageText(WikiPage page, String text) throws ProviderException {
    int pageId = -1;
    ////ww  w  .  j  a  va2 s . com
    // This is a bit complicated. We'll first need to
    // copy the old file to be the newest file.
    //
    File pageDir = findOldPageDir(page.getName());

    try {
        if (!pageDir.exists()) {
            pageId = pageDAO
                    .createPage(new PageDetail(-1, page.getName(), WikiMultiInstanceManager.getComponentId()));
            pageDir.mkdirs();
        } else {
            PageDetail pageDetail = pageDAO.getPage(page.getName(), WikiMultiInstanceManager.getComponentId());
            pageId = pageDetail.getId();
        }
    } catch (WikiException e) {
        SilverTrace.error("wiki", "WikiVersioningFileProvider.putPageText()", "root.EX_PUT_PAGE_FAILED", e);
        throw new ProviderException("Could not save page text: " + e.getMessage());
    }

    int latest = findLatestVersion(page.getName());

    try {
        //
        // Copy old data to safety, if one exists.
        //
        File oldFile = findPage(page.getName());

        // Figure out which version should the old page be?
        // Numbers should always start at 1.
        // "most recent" = -1 ==> 1
        // "first" = 1 ==> 2

        int versionNumber = (latest > 0) ? latest : 1;

        if (oldFile != null && oldFile.exists()) {
            InputStream in = null;
            OutputStream out = null;

            try {
                in = new BufferedInputStream(new FileInputStream(oldFile));
                File pageFile = new File(pageDir, Integer.toString(versionNumber) + FILE_EXT);
                out = new BufferedOutputStream(new FileOutputStream(pageFile));

                FileUtil.copyContents(in, out);

                //
                // We need also to set the date, since we rely on this.
                //
                pageFile.setLastModified(oldFile.lastModified());

                //
                // Kludge to make the property code to work properly.
                //
                versionNumber++;
            } finally {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            }
        }

        //
        // Let superclass handler writing data to a new version.
        //

        super.putPageText(page, text);

        //
        // Finally, write page version data.
        //

        // FIXME: No rollback available.
        Properties props = getPageProperties(page.getName());

        props.setProperty(versionNumber + ".author", (page.getAuthor() != null) ? page.getAuthor() : "unknown");
        props.setProperty(versionNumber + ".id", String.valueOf(pageId));

        String changeNote = (String) page.getAttribute(WikiPage.CHANGENOTE);
        if (changeNote != null) {
            props.setProperty(versionNumber + ".changenote", changeNote);
        }

        putPageProperties(page.getName(), props);
    } catch (IOException e) {
        SilverTrace.error("wiki", "WikiVersioningFileProvider.putPageText()", "root.EX_PUT_PAGE_FAILED", e);
        throw new ProviderException("Could not save page text: " + e.getMessage());
    }
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void libraries() throws Exception {
    TestJarFile libJar = new TestJarFile(this.temporaryFolder);
    libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class, JAN_1_1985);
    File libJarFile = libJar.getFile();
    File libJarFileToUnpack = libJar.getFile();
    File libNonJarFile = this.temporaryFolder.newFile();
    FileCopyUtils.copy(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, libNonJarFile);
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    this.testJarFile.addFile("BOOT-INF/lib/" + libJarFileToUnpack.getName(), libJarFileToUnpack);
    File file = this.testJarFile.getFile();
    libJarFile.setLastModified(JAN_1_1980);
    Repackager repackager = new Repackager(file);
    repackager.repackage((callback) -> {
        callback.library(new Library(libJarFile, LibraryScope.COMPILE));
        callback.library(new Library(libJarFileToUnpack, LibraryScope.COMPILE, true));
        callback.library(new Library(libNonJarFile, LibraryScope.COMPILE));
    });//from w  w w.ja va2 s. co  m
    assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFile.getName())).isTrue();
    assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName())).isTrue();
    assertThat(hasEntry(file, "BOOT-INF/lib/" + libNonJarFile.getName())).isFalse();
    JarEntry entry = getEntry(file, "BOOT-INF/lib/" + libJarFile.getName());
    assertThat(entry.getTime()).isEqualTo(JAN_1_1985);
    entry = getEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName());
    assertThat(entry.getComment()).startsWith("UNPACK:");
    assertThat(entry.getComment().length()).isEqualTo(47);
}