List of usage examples for java.io File setLastModified
public boolean setLastModified(long time)
From source file:com.ibm.jaggr.core.impl.cache.GzipCacheImpl.java
@Override public InputStream getInputStream(final String key, final URI source, final MutableInt retLength) throws IOException { final String sourceMethod = "getInputStream"; //$NON-NLS-1$ final boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(sourceClass, sourceMethod, new Object[] { key, source, retLength }); }/*from w ww. j a v a 2s . co m*/ InputStream in = null, result = null; CacheEntry tryCacheEntry = (CacheEntry) super.get(key); URLConnection connection = source.toURL().openConnection(); try { long lastModified = connection.getLastModified(); if (tryCacheEntry != null) { // Make local copies of volatile CacheEntry fields byte[] bytes = tryCacheEntry.bytes; File file = tryCacheEntry.file; if (bytes != null) { // Important - CacheEntry.lastModified is set before CacheEntry.bytes so we can // safely // check CacheEntry.lastModified here even though we're not synchronized. if (lastModified != tryCacheEntry.lastModified) { // stale cache entry. Remove it and create a new one below cacheMap.remove(key, tryCacheEntry); } else { retLength.setValue(tryCacheEntry.bytes.length); result = new ByteArrayInputStream(tryCacheEntry.bytes); } } else if (file != null) { // Some platforms round file last modified times to nearest second. if (Math.abs(lastModified - file.lastModified()) > 1000) { // Stale cache entry, remove it and create a new one below cacheMap.remove(key, tryCacheEntry); // also delete the associated cache file asynchronously. cacheManager.deleteFileDelayed(file.getName()); } else { try { retLength.setValue(file.length()); result = new FileInputStream(file); } catch (FileNotFoundException ex) { // File doesn't exist (was probably deleted outside this program) // Not fatal, just fall through and create it again. cacheMap.remove(key, tryCacheEntry); } } } if (result != null) { // found result in cache. Return it. log.exiting(sourceClass, sourceMethod, result); return result; } } // Result not in cache (or we removed it). Try to create a new cache entry. CacheEntry newCacheEntry = new CacheEntry(); CacheEntry oldCacheEntry = (CacheEntry) cacheMap.putIfAbsent(key, newCacheEntry); final CacheEntry cacheEntry = oldCacheEntry != null ? oldCacheEntry : newCacheEntry; // Synchronize on the cache entry so that more than one thread won't try to create the // zipped content. synchronized (cacheEntry) { if (cacheEntry.ex != null) { // An exception occurred trying to create the gzip response in another thread. // Re-throw the exception here. throw cacheEntry.ex; } // First, check to make sure that another thread didn't beat us to the punch. // Even though we're synchronized on the cacheEntry object, cacheEntry.bytes can be // cleared by the createCacheFileAsync callback, so we need to copy this volatile // field // to a local variable and access it from there. byte[] bytes = cacheEntry.bytes; if (bytes != null) { retLength.setValue(bytes.length); result = new ByteArrayInputStream(bytes); } else if (cacheEntry.file != null) { // once set, cacheEntry.file does not change // by convention retLength.setValue(cacheEntry.file.length()); result = new FileInputStream(cacheEntry.file); } else { // Gzip encode the resource and save the result in the cache entry until the // cache // file is written asynchronously. try { in = connection.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); VariableGZIPOutputStream compress = new VariableGZIPOutputStream(bos, 10240); compress.setLevel(Deflater.BEST_COMPRESSION); CopyUtil.copy(in, compress); // Important - CacheEntry.lastModified must be set before cacheEntry.bytes cacheEntry.lastModified = lastModified; cacheEntry.bytes = bos.toByteArray(); result = new ByteArrayInputStream(cacheEntry.bytes); retLength.setValue(cacheEntry.bytes.length); // Call the cache manager to asynchronously save the gzipped response to // disk // Include the filename part of the source URI in the cached filename String path = source.getPath(); int idx = path.lastIndexOf("/"); //$NON-NLS-1$ String fname = (idx != -1) ? path.substring(idx + 1) : path; cacheManager.createCacheFileAsync(fname + ".gzip.", //$NON-NLS-1$ new ByteArrayInputStream(cacheEntry.bytes), new ICacheManager.CreateCompletionCallback() { @Override public void completed(String filename, Exception e) { if (e != null && log.isLoggable(Level.SEVERE)) { // Exception occurred saving file. Not much we can do // except log the error log.logp(Level.SEVERE, sourceClass, sourceMethod, e.getMessage(), e); return; } File cacheFile = new File(cacheManager.getCacheDir(), filename); cacheFile.setLastModified(cacheEntry.lastModified); // Important - cacheEntry.file must be set before clearing // cacheEntry.bytes cacheEntry.file = cacheFile; cacheEntry.bytes = null; } }); } catch (Throwable t) { cacheEntry.ex = (t instanceof IOException) ? (IOException) t : new IOException(t); cacheMap.remove(key, cacheEntry); throw cacheEntry.ex; } } } } finally { // URLConnection doesn't have a close method. The only way to make sure a connection is // closed is to close the input or output stream which is obtained from the connection. if (in != null) { in.close(); } else { connection.getInputStream().close(); } } if (isTraceLogging) { log.exiting(sourceClass, sourceClass, result); } return result; }
From source file:org.artifactory.repo.db.importexport.DbExportBase.java
private void writeChecksums(File targetFile, FileInfo sourceFile) throws IOException { // Write the checksum files next to the file which they belong to. for (ChecksumInfo checksumInfo : sourceFile.getChecksumsInfo().getChecksums()) { File checksumFile = new File(targetFile + checksumInfo.getType().ext()); FileUtils.writeStringToFile(checksumFile, checksumInfo.getActual(), "utf-8"); checksumFile.setLastModified(sourceFile.getLastModified()); }//from ww w . jav a2 s. c o m }
From source file:com.funambol.server.config.ConfigurationTest.java
/** * Test of plugin handling// w w w. j a va 2 s . c o m * @throws Exception */ public void testPlugin_2() throws Exception { Boolean b = (Boolean) PrivateAccessor.getField(Configuration.getConfiguration(), "engineComponentsInitialized"); assertFalse("The engine components should not be initialized", b.booleanValue()); // // engine components not initialized // PluginHandler pluginHandler = (PluginHandler) PrivateAccessor.getField(Configuration.getConfiguration(), "pluginHandler"); assertNull(pluginHandler); // // Touching a plugin file, nothing should happen // File f = new File(Configuration.getConfigPath() + "/com/funambol/server/plugin/dummy-plugin-1.xml"); if (!f.isFile()) { fail("Missing file: " + f); } assertTrue("Unable to set the last-modified time of the file", f.setLastModified(System.currentTimeMillis())); // Waiting for automatic change detection Thread.sleep(15 * 1000); // // engine components not initialized // pluginHandler = (PluginHandler) PrivateAccessor.getField(Configuration.getConfiguration(), "pluginHandler"); assertNull(pluginHandler); }
From source file:com.blackducksoftware.tools.scmconnector.integrations.ftp.FTPConnector.java
private void downloadFiles(String parentPath, FTPClient client, FTPFile folder) throws IllegalStateException, FileNotFoundException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException, FTPListParseException { client.changeDirectory(folder.getName()); File dir = new File(parentPath, folder.getName()); if (!dir.exists()) { dir.mkdir();//from www . java 2 s .c om } FTPFile[] list = client.list(); deleteFileInTargetDirectoryNotExistingInSource(dir, list); for (FTPFile f : list) { if (f.getType() == FTPFile.TYPE_FILE) { File targetFile = new File(dir.getPath(), f.getName()); if (f.getModifiedDate().getTime() != targetFile.lastModified()) { log.info("Obtaining file: " + f.getName()); client.download(f.getName(), targetFile); targetFile.setLastModified(f.getModifiedDate().getTime()); } } else if (f.getType() == FTPFile.TYPE_DIRECTORY) { log.info("Inspecting directory: " + f.getName()); downloadFiles(dir.getPath(), client, f); } } client.changeDirectoryUp(); }
From source file:org.evosuite.utils.FileIOUtils.java
private static void recursiveCopy(File src, File dest) throws IOException { if (src.isDirectory()) { //the destination might not exist. if so, let's create it if (!dest.exists()) { dest.mkdirs();/*from w w w . ja va 2 s.com*/ } //iterate over the children for (String file : src.list()) { File srcFile = new File(src, file); File destFile = new File(dest, file); //recursive call recursiveCopy(srcFile, destFile); } } else { boolean sameTime = src.lastModified() == dest.lastModified(); if (sameTime) { //file was not modified, so no need to copy over return; } try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest);) { byte[] buffer = new byte[2048]; int length; //copy the file content in bytes while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } } //as it is a copy, make sure to get same time stamp as src, otherwise it ll be always copied over dest.setLastModified(src.lastModified()); } }
From source file:org.socialbiz.cog.BackupUtils.java
private static void copyFile(File srcFile, File destFile) throws IOException { FileInputStream is = null;/*from w w w .j a v a 2s . c o m*/ FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { //Return the smallest of two long iterationBytes = Math.min(todoBytes, DEFAULT_COPY_BUFFER_SIZE); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.info("Could not change timestamp for {}. Index synchronization may be slow. " + destFile); } }
From source file:au.org.ala.delta.io.BinFile.java
public void setFileTime(long time) { File f = new File(_filename); f.setLastModified(time); }
From source file:org.brekka.stillingar.spring.snapshot.WatchedResourceMonitorTest.java
/** * Test method for {@link org.brekka.stillingar.spring.snapshot.WatchedResourceMonitor#hasChanged()}. *///from w w w .j ava 2 s .c o m @Test public void testHasChanged() throws Exception { File dir = new File(System.getProperty("java.io.tmpdir"), getClass().getSimpleName()); dir.mkdirs(); File file = new File(dir, "config.xml"); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); watchedResourceMonitor.initialise(new FileSystemResource(file)); assertFalse(watchedResourceMonitor.hasChanged()); Thread.sleep(500); for (int i = 0; i < 3; i++) { fos.write("Test\n".getBytes()); fos.flush(); file.setLastModified(System.currentTimeMillis()); Thread.sleep(500); assertTrue(watchedResourceMonitor.hasChanged()); Thread.sleep(500); assertFalse(watchedResourceMonitor.hasChanged()); } fos.close(); file.delete(); dir.delete(); }
From source file:org.opencms.search.documents.CmsExtractionResultCache.java
/** * Returns the extraction result in the requested file in the disk cache, or <code>null</code> if the * file is not found in the cache, or is found but out-dated.<p> * /* w w w . j a v a2s . co m*/ * @param rfsName the file RFS name to look up in the cache * * @return the extraction result stored in the requested file in the RFS disk cache, or <code>null</code> */ public CmsExtractionResult getCacheObject(String rfsName) { try { File f = new File(rfsName); if (f.exists()) { long age = f.lastModified(); if ((System.currentTimeMillis() - age) > 3600000) { // file has not been touched for 1 hour, touch the file with the current date f.setLastModified(System.currentTimeMillis()); } byte[] byteContent = CmsFileUtil.readFile(f); return CmsExtractionResult.fromBytes(byteContent); } } catch (IOException e) { // unable to read content } // this code can be reached only in case of an error return null; }
From source file:com.blackducksoftware.tools.scmconnector.integrations.ftp.FTPConnector.java
@Override public int sync() { try {// ww w.j a v a 2s .co m FTPClient client = new FTPClient(); client.connect(server); client.login(user, password); client.changeDirectory(path); FTPFile[] list = client.list(); String parentPath = getFinalSourceDirectory(); File dir = new File(parentPath); if (!dir.exists()) { dir.mkdir(); } deleteFileInTargetDirectoryNotExistingInSource(dir, list); for (FTPFile f : list) { if (f.getType() == FTPFile.TYPE_FILE) { File targetFile = new File(parentPath, f.getName()); if (f.getModifiedDate().getTime() != targetFile.lastModified()) { log.info("Obtaining file: " + f.getName()); client.download(f.getName(), targetFile); targetFile.setLastModified(f.getModifiedDate().getTime()); } } else if (f.getType() == FTPFile.TYPE_DIRECTORY) { log.info("Inspecting directory: " + f.getName()); downloadFiles(parentPath, client, f); } } } catch (Exception e) { log.error("Error performing FTP operation", e); return 1; } return 0; }