List of usage examples for java.io File setLastModified
public boolean setLastModified(long time)
From source file:org.grouter.core.readers.FtpReaderJob.java
@Override protected List<CommandMessage> readFromSource() { logger.info("Reading files from :" + node.getInBound().getUri()); // a list of full paths on ftp server we will download from Map endPointContext = node.getInBound().getEndPointContext(); List<String> remoteFtpUriToFile = getPathIncludingFile((String) endPointContext.get(FILE_LIST)); List<CommandMessage> commandMessages = new ArrayList<CommandMessage>(); FTPClient client = null;//from www . ja va2 s .c om try { client = initConnection(); for (String fullPathToFile : remoteFtpUriToFile) { // should only return one file - since we are using a complete file uri and not a uri to a folder FTPFile[] ftpFilesAtPath = client.listFiles(fullPathToFile); if (ftpFilesAtPath.length > 0) { //String localFileName = fullPathToFile; File internalInFile = new File(node.getRouter().getHomePath() + File.separator + "nodes" + File.separator + node.getId() + File.separator + "internal" + File.separator + "in" + File.separator + fullPathToFile.replace("/", "_")); FileOutputStream fos = new FileOutputStream(internalInFile); logger.info("Downloading file from ftp server:" + fullPathToFile); // we have a valid fullPathToFile and there is a file at that fullPathToFile boolean status = client.retrieveFile(fullPathToFile, fos); if (status) { logger.info("Downloading complete :" + internalInFile); internalInFile.setLastModified(ftpFilesAtPath[0].getTimestamp().getTimeInMillis()); // Get part of the message to store for querying purposes String message = getMessage(internalInFile); CommandMessage cmdMessage = new CommandMessage(message, internalInFile); commandMessages.add(cmdMessage); } else { logger.error("Failed to download remote file :" + fullPathToFile + " Status code received :" + status); } fos.close(); } } } catch (Exception e) { // TODO We need to reset state if we start working again node.setNodeStatus(NodeStatus.ERROR); node.setStatusMessage( "Failed reading files from :" + node.getInBound().getUri() + " Error:" + e.getMessage()); logStrategy.log(node); logger.warn("Connection problem with FTP server.", e); } finally { if (client != null) { try { client.logout(); client.disconnect(); } catch (IOException e) { //ignore } } } return commandMessages; }
From source file:net.sf.jvifm.model.FileModelManager.java
/*****************************************************************************************/ private void copyFile(File srcFile, File dstFile) throws IOException { if (Thread.currentThread().isInterrupted()) return;/*from w ww .ja v a2s. c o m*/ File dstParent = dstFile.getParentFile(); if (!dstParent.exists()) dstParent.mkdirs(); FileInputStream input = new FileInputStream(srcFile); FileOutputStream output = new FileOutputStream(dstFile); try { byte[] buffer = new byte[1024 * 16]; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } dstFile.setLastModified(srcFile.lastModified()); } finally { try { if (input != null) input.close(); } catch (Exception e) { } try { if (output != null) output.close(); } catch (Exception e) { } } }
From source file:com.fizzed.rocker.reload.ReloadTest.java
@Test public void reload() throws Exception { // render initial String out = Rocker.template("views/index.rocker.html", "Home", "Joe").render().toString(); assertThat(out, containsString("<h1>Hi, Joe!</h1>")); // to find path reliably of source file, we'll take something on classpath // for this project and then do something relative to it URL logbackUrl = ReloadTest.class.getResource("/logback.xml"); File projectDir = new File(logbackUrl.toURI()).getParentFile().getParentFile().getParentFile(); File currentTemplateFile = new File(projectDir, "src/test/java/views/index.rocker.html"); FileInputStream fis = new FileInputStream(currentTemplateFile); String currentTemplate = IOUtils.toString(fis, "UTF-8"); String newTemplate = currentTemplate.replace("<h1>Hi, @name!</h1>", "<h1>Hi, @name!?!</h1>"); try {//from w w w . ja v a 2 s . c o m FileOutputStream fos = new FileOutputStream(currentTemplateFile); IOUtils.write(newTemplate, fos, "UTF-8"); out = Rocker.template("views/index.rocker.html", "Home", "Joe").render().toString(); assertThat(out, containsString("<h1>Hi, Joe!?!</h1>")); } finally { // restore template back... FileOutputStream fos = new FileOutputStream(currentTemplateFile); IOUtils.write(currentTemplate, fos, "UTF-8"); } // since we base reloading on timestamp, need to force something // different since these tests run so quickly currentTemplateFile.setLastModified(System.currentTimeMillis() + 5000); // try the restored file one more time out = Rocker.template("views/index.rocker.html", "Home", "Joe").render().toString(); assertThat(out, containsString("<h1>Hi, Joe!</h1>")); }
From source file:org.geowebcache.storage.blobstore.file.FileBlobStore.java
/** * Store a tile.// w w w .ja v a2 s .co m */ public void put(TileObject stObj) throws StorageException { final File fh = getFileHandleTile(stObj, true); final long oldSize = fh.length(); final boolean existed = oldSize > 0; writeFile(fh, stObj, existed); // mark the last modification as the tile creation time if set, otherwise // we'll leave it to the writing time if (stObj.getCreated() > 0) { try { fh.setLastModified(stObj.getCreated()); } catch (Exception e) { log.debug("Failed to set the last modified time to match the tile request time", e); } } /* * This is important because listeners may be tracking tile existence */ stObj.setBlobSize((int) padSize(stObj.getBlobSize())); if (existed) { listeners.sendTileUpdated(stObj, padSize(oldSize)); } else { listeners.sendTileStored(stObj); } }
From source file:com.ecyrd.jspwiki.providers.WikiVersioningFileProvider.java
@Override 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 ////from w w w.j a v a2 s . co m try { Properties props = getPageProperties(page); props.remove(((latest > 0) ? latest : 1) + ".author"); putPageProperties(page, props); } catch (IOException e) { SilverTrace.error("wiki", "WikiVersioningFileProvider.deleteVersion()", "wiki.EX_MODIFY_PROPERTIES", e); throw new ProviderException("Could not modify page properties"); } // 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) { SilverTrace.fatal("wiki", "WikiVersioningFileProvider.deleteVersion()", "root.EXCEPTION", "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()) { SilverTrace.error("wiki", "WikiVersioningFileProvider.deleteVersion()", "wiki.EX_DELETE_PAGE_FAILED"); } } else { throw new NoSuchVersionException("Page " + page + ", version=" + version); } }
From source file:org.apache.jackrabbit.core.data.LocalCache.java
/** * This method add file to {@link LocalCache} and tries that file can be * added to {@link AsyncUploadCache}. If file is added to * {@link AsyncUploadCache} successfully, it sets * {@link AsyncUploadResult#setAsyncUpload(boolean)} to true. * * @param fileName name of the file./* www. j a v a 2 s . co m*/ * @param src source file. * @param tryForAsyncUpload If true it tries to add fileName to * {@link AsyncUploadCache} * @return {@link AsyncUploadCacheResult}. This method sets * {@link AsyncUploadResult#setAsyncUpload(boolean)} to true, if * fileName is added to {@link AsyncUploadCache} successfully else * it sets {@link AsyncUploadCacheResult#setAsyncUpload(boolean)} to * false. {@link AsyncUploadCacheResult#getFile()} contains cached * file, if it is added to {@link LocalCache} or original file. * @throws IOException */ public synchronized AsyncUploadCacheResult store(String fileName, File src, boolean tryForAsyncUpload) throws IOException { fileName = fileName.replace("\\", "/"); File dest = getFile(fileName); File parent = dest.getParentFile(); AsyncUploadCacheResult result = new AsyncUploadCacheResult(); result.setFile(src); result.setAsyncUpload(false); boolean destExists = false; if ((destExists = dest.exists()) || (src.exists() && !dest.exists() && !src.equals(dest) && canAdmitFile(src.length()) && (parent.exists() || parent.mkdirs()) && (src.renameTo(dest)))) { if (destExists) { dest.setLastModified(System.currentTimeMillis()); } cache.put(fileName, dest.length()); LOG.debug("file [{}] added to local cache.", fileName); result.setFile(dest); if (tryForAsyncUpload) { result.setAsyncUpload(asyncUploadCache.add(fileName).canAsyncUpload()); } } cache.tryPurge(); return result; }
From source file:org.gradle.api.internal.tasks.cache.TarTaskOutputPacker.java
private void unpack(TaskOutputsInternal taskOutputs, TarInputStream tarInput) throws IOException { Map<String, TaskOutputFilePropertySpec> propertySpecs = Maps.uniqueIndex(taskOutputs.getFileProperties(), new Function<TaskFilePropertySpec, String>() { @Override// w ww. j av a2s. c om public String apply(TaskFilePropertySpec propertySpec) { return propertySpec.getPropertyName(); } }); TarEntry entry; while ((entry = tarInput.getNextEntry()) != null) { String name = entry.getName(); Matcher matcher = PROPERTY_PATH.matcher(name); if (!matcher.matches()) { throw new IllegalStateException("Cached result format error, invalid contents: " + name); } String propertyName = matcher.group(1); CacheableTaskOutputFilePropertySpec propertySpec = (CacheableTaskOutputFilePropertySpec) propertySpecs .get(propertyName); if (propertySpec == null) { throw new IllegalStateException(String.format("No output property '%s' registered", propertyName)); } File specRoot = propertySpec.getOutputFile(); String path = matcher.group(2); File outputFile; if (Strings.isNullOrEmpty(path)) { outputFile = specRoot; } else { outputFile = new File(specRoot, path); } if (entry.isDirectory()) { if (propertySpec.getOutputType() != OutputType.DIRECTORY) { throw new IllegalStateException( "Property should be an output directory property: " + propertyName); } FileUtils.forceMkdir(outputFile); } else { Files.asByteSink(outputFile).writeFrom(tarInput); } //noinspection OctalInteger fileSystem.chmod(outputFile, entry.getMode() & 0777); long lastModified = getModificationTime(entry); if (!outputFile.setLastModified(lastModified)) { throw new IOException(String.format("Could not set modification time for '%s'", outputFile)); } } }
From source file:org.apache.hadoop.gateway.services.topology.impl.DefaultTopologyService.java
private void redeployTopology(Topology topology) { File topologyFile = new File(topology.getUri()); try {/* ww w. j a va2 s .c om*/ TopologyValidator tv = new TopologyValidator(topology); if (tv.validateTopology()) { throw new SAXException(tv.getErrorString()); } long start = System.currentTimeMillis(); long limit = 1000L; // One second. long elapsed = 1; while (elapsed <= limit) { try { long origTimestamp = topologyFile.lastModified(); long setTimestamp = Math.max(System.currentTimeMillis(), topologyFile.lastModified() + elapsed); if (topologyFile.setLastModified(setTimestamp)) { long newTimstamp = topologyFile.lastModified(); if (newTimstamp > origTimestamp) { break; } else { Thread.sleep(10); elapsed = System.currentTimeMillis() - start; continue; } } else { auditor.audit(Action.REDEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE); log.failedToRedeployTopology(topology.getName()); break; } } catch (InterruptedException e) { auditor.audit(Action.REDEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE); log.failedToRedeployTopology(topology.getName(), e); e.printStackTrace(); } } } catch (SAXException e) { auditor.audit(Action.REDEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE); log.failedToRedeployTopology(topology.getName(), e); } }
From source file:tests.unit.util.file.FileChangeMonitorTestCase.java
/** * @throws Exception//from ww w .ja v a2s . c o m */ public void testMultiFileChange() throws Exception { System.out.println("---- testMultiFileChange"); TestListener tl0 = new TestListener(null); TestListener tl1 = new TestListener(TEST_FILE_1); File f1 = new File(TEST_FILE_1); f1.createNewFile(); TestListener tl2 = new TestListener(TEST_FILE_2); File f2 = new File(TEST_FILE_2); f2.createNewFile(); TestListener tl3 = new TestListener(TEST_FILE_3); File f3 = new File(TEST_FILE_3); f3.createNewFile(); FileChangeMonitor.addFileChangeListener(tl0); FileChangeMonitor.addFileChangeListener(tl1, TEST_FILE_1); assertFalse("Resource " + TEST_FILE_1 + " already modified", tl1.isChanged()); FileChangeMonitor.addFileChangeListener(tl2, TEST_FILE_2); assertFalse("Resource " + TEST_FILE_2 + " already modified", tl2.isChanged()); FileChangeMonitor.addFileChangeListener(tl3, TEST_FILE_3); assertFalse("Resource " + TEST_FILE_3 + " already modified", tl3.isChanged()); Thread.sleep(1000); f1.setLastModified(System.currentTimeMillis()); Thread.sleep(6000); assertTrue("Resource " + TEST_FILE_1 + " modified", tl0.isChanged()); assertTrue("Resource " + TEST_FILE_1 + " modified", tl1.isChanged()); assertFalse("Resource " + TEST_FILE_2 + " NOT modified", tl2.isChanged()); assertFalse("Resource " + TEST_FILE_3 + " NOT modified", tl3.isChanged()); tl0.resetChanged(); tl1.resetChanged(); tl2.resetChanged(); tl3.resetChanged(); Thread.sleep(1000); f2.setLastModified(System.currentTimeMillis()); Thread.sleep(6000); assertTrue("Resource " + TEST_FILE_2 + " modified", tl0.isChanged()); assertFalse("Resource " + TEST_FILE_1 + " NOT modified", tl1.isChanged()); assertTrue("Resource " + TEST_FILE_2 + " modified", tl2.isChanged()); assertFalse("Resource " + TEST_FILE_3 + " NOT modified", tl3.isChanged()); tl0.resetChanged(); tl1.resetChanged(); tl2.resetChanged(); tl3.resetChanged(); Thread.sleep(1000); f3.setLastModified(System.currentTimeMillis()); Thread.sleep(6000); assertTrue("Resource " + TEST_FILE_3 + " modified", tl0.isChanged()); assertFalse("Resource " + TEST_FILE_1 + " NOT modified", tl1.isChanged()); assertFalse("Resource " + TEST_FILE_2 + " NOT modified", tl2.isChanged()); assertTrue("Resource " + TEST_FILE_3 + " modified", tl3.isChanged()); tl0.resetChanged(); tl1.resetChanged(); tl2.resetChanged(); tl3.resetChanged(); System.out.println("---- testMultiFileChange"); }
From source file:org.apache.ivy.util.url.HttpClientHandler.java
public void download(URL src, File dest, CopyProgressListener l) throws IOException { GetMethod get = doGet(src, 0);//from w w w. j ava 2 s. c o m try { // We can only figure the content we got is want we want if the status is success. if (!checkStatusCode(src, get)) { throw new IOException("The HTTP response code for " + src + " did not indicate a success." + " See log for more detail."); } Header encoding = get.getResponseHeader("Content-Encoding"); InputStream is = getDecodingInputStream(encoding == null ? null : encoding.getValue(), get.getResponseBodyAsStream()); FileUtil.copy(is, dest, l); dest.setLastModified(getLastModified(get)); } finally { get.releaseConnection(); } }