List of usage examples for java.io File setLastModified
public boolean setLastModified(long time)
From source file:org.pepstock.jem.node.executors.gfs.WriteChunk.java
@Override public final Boolean execute() throws ExecutorException { String parentPath = null;//from w w w .j a va 2 s . c o m File file = null; // checks here the type of file-system to scan switch (chunk.getType()) { case GfsFileType.LIBRARY: // gets system property as parent parentPath = System.getProperty(ConfigKeys.JEM_LIBRARY_PATH_NAME); break; case GfsFileType.SOURCE: // gets system property as parent parentPath = System.getProperty(ConfigKeys.JEM_SOURCE_PATH_NAME); break; case GfsFileType.CLASS: // gets system property as parent parentPath = System.getProperty(ConfigKeys.JEM_CLASSPATH_PATH_NAME); break; case GfsFileType.BINARY: // gets system property as parent parentPath = System.getProperty(ConfigKeys.JEM_BINARY_PATH_NAME); break; default: // if here, the GFS type is wrong or not acceptable (like data path) throw new ExecutorException(NodeMessage.JEMC264E); } // a temporary file with parent path and chunk code file = new File(parentPath, chunk.getFilePath() + "." + chunk.getFileCode()); try { // test the parent folder exists if (!file.getParentFile().exists()) { FileUtils.forceMkdir(file.getParentFile()); } // if tmp file does not exists create it with all directory structure if (!file.exists() && !file.createNewFile()) { throw new ExecutorException(NodeMessage.JEMC266E, file.getAbsolutePath()); } // if the transferred is complete just rename the tmp file if (chunk.isTransferComplete()) { File finalFile = new File(parentPath, chunk.getFilePath()); // removes final file if exists if (finalFile.exists() && !finalFile.delete()) { throw new ExecutorException(NodeMessage.JEMC268E, finalFile.getAbsolutePath()); } // renames the uploaded file to final one if (!file.renameTo(finalFile)) { throw new ExecutorException(NodeMessage.JEMC267E, file.getAbsolutePath(), finalFile.getAbsolutePath()); } // updates also the last modified attribute if (!finalFile.setLastModified(chunk.getLastUpdate())) { // if it can't, no prob. just a debug LogAppl.getInstance().debug("Unable to set last modified date! Ignored!"); } return true; } // write to the temporary file in APPEND mode FileOutputStream output = new FileOutputStream(file.getAbsolutePath(), true); try { // write the buffer of chunkf output.write(chunk.getChunk(), 0, chunk.getNumByteToWrite()); } finally { output.close(); } } catch (Exception e) { // upload get an exception so delete tmp file try { FileUtils.deleteDirectory(file); } catch (IOException e1) { LogAppl.getInstance().ignore(e1.getMessage(), e1); } // throw the exception throw new ExecutorException(NodeMessage.JEMC265E, e, file.getAbsolutePath(), e.getMessage()); } return true; }
From source file:org.nuxeo.ecm.core.blob.binary.LocalBinaryManager.java
/** * Does an atomic move of the tmp (or source) file to the final file. * <p>//from ww w . jav a2 s . c om * Tries to work well with NFS mounts and different filesystems. */ protected void atomicMove(File source, File dest) throws IOException { if (dest.exists()) { // The file with the proper digest is already there so don't do // anything. This is to avoid "Stale NFS File Handle" problems // which would occur if we tried to overwrite it anyway. // Note that this doesn't try to protect from the case where // two identical files are uploaded at the same time. // Update date for the GC. dest.setLastModified(source.lastModified()); return; } if (!source.renameTo(dest)) { // Failed to rename, probably a different filesystem. // Do *NOT* use Apache Commons IO's FileUtils.moveFile() // because it rewrites the destination file so is not atomic. // Do a copy through a tmp file on the same filesystem then // atomic rename. File tmp = File.createTempFile(dest.getName(), ".tmp", dest.getParentFile()); try { try (InputStream in = new FileInputStream(source); // OutputStream out = new FileOutputStream(tmp)) { IOUtils.copy(in, out); } // then do the atomic rename tmp.renameTo(dest); } finally { tmp.delete(); } // finally remove the original source source.delete(); } if (!dest.exists()) { throw new IOException("Could not create file: " + dest); } }
From source file:org.apache.flume.client.avro.TestReliableSpoolingFileEventReader.java
@Test public void testConsumeFileOldestWithLexicographicalComparision() throws IOException, InterruptedException { ReliableEventReader reader = new ReliableSpoolingFileEventReader.Builder().spoolDirectory(WORK_DIR) .consumeOrder(ConsumeOrder.OLDEST).build(); File file1 = new File(WORK_DIR, "new-file1"); File file2 = new File(WORK_DIR, "new-file2"); File file3 = new File(WORK_DIR, "new-file3"); Thread.sleep(1000L);// w w w . j av a 2 s . c o m FileUtils.write(file3, "New file3 created.\n"); FileUtils.write(file2, "New file2 created.\n"); FileUtils.write(file1, "New file1 created.\n"); file1.setLastModified(file3.lastModified()); file1.setLastModified(file2.lastModified()); // file ages are same now they need to be ordered // lexicographically (file1, file2, file3). List<String> actual = Lists.newLinkedList(); readEventsForFilesInDir(WORK_DIR, reader, actual); List<String> expected = Lists.newLinkedList(); createExpectedFromFilesInSetup(expected); expected.add(""); // Empty file was added in the last in setup. expected.add("New file1 created."); expected.add("New file2 created."); expected.add("New file3 created."); Assert.assertEquals(expected, actual); }
From source file:org.apache.flume.client.avro.TestReliableSpoolingFileEventReader.java
@Test public void testConsumeFileYoungestWithLexicographicalComparision() throws IOException, InterruptedException { ReliableEventReader reader = new ReliableSpoolingFileEventReader.Builder().spoolDirectory(WORK_DIR) .consumeOrder(ConsumeOrder.YOUNGEST).build(); File file1 = new File(WORK_DIR, "new-file1"); File file2 = new File(WORK_DIR, "new-file2"); File file3 = new File(WORK_DIR, "new-file3"); Thread.sleep(1000L);// w w w.j av a2 s . c o m FileUtils.write(file1, "New file1 created.\n"); FileUtils.write(file2, "New file2 created.\n"); FileUtils.write(file3, "New file3 created.\n"); file1.setLastModified(file3.lastModified()); file1.setLastModified(file2.lastModified()); // file ages are same now they need to be ordered // lexicographically (file1, file2, file3). List<String> actual = Lists.newLinkedList(); readEventsForFilesInDir(WORK_DIR, reader, actual); List<String> expected = Lists.newLinkedList(); createExpectedFromFilesInSetup(expected); expected.add(0, ""); // Empty file was added in the last in setup. expected.add(0, "New file3 created."); expected.add(0, "New file2 created."); expected.add(0, "New file1 created."); Assert.assertEquals(expected, actual); }
From source file:org.nuxeo.ecm.core.storage.binary.LocalBinaryManager.java
/** * Does an atomic move of the tmp (or source) file to the final file. * <p>//from w ww . j a v a 2 s . c o m * Tries to work well with NFS mounts and different filesystems. */ protected void atomicMove(File source, File dest) throws IOException { if (dest.exists()) { // The file with the proper digest is already there so don't do // anything. This is to avoid "Stale NFS File Handle" problems // which would occur if we tried to overwrite it anyway. // Note that this doesn't try to protect from the case where // two identical files are uploaded at the same time. // Update date for the GC. dest.setLastModified(source.lastModified()); return; } if (!source.renameTo(dest)) { // Failed to rename, probably a different filesystem. // Do *NOT* use Apache Commons IO's FileUtils.moveFile() // because it rewrites the destination file so is not atomic. // Do a copy through a tmp file on the same filesystem then // atomic rename. File tmp = File.createTempFile(dest.getName(), ".tmp", dest.getParentFile()); try { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new FileOutputStream(tmp); IOUtils.copy(in, out); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } // then do the atomic rename tmp.renameTo(dest); } finally { tmp.delete(); } // finally remove the original source source.delete(); } if (!dest.exists()) { throw new IOException("Could not create file: " + dest); } }
From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java
@Override public void createSkin(String name, InputStream data, Date date, boolean overwrite) throws SkinException, IOException { File file = createTempZip(data); File mySkinDir = null; boolean isSucceeded = false; try {// w w w.j a v a 2 s.c o m validateSkinZip(file); mySkinDir = prepareSkinDir(name, date, overwrite); installSkin(mySkinDir, file); isSucceeded = true; mySkinDir.setLastModified(date.getTime()); } finally { if (!file.delete()) { LOG.warn("Unable to delete tmp file: " + file); } if (!isSucceeded && mySkinDir != null && mySkinDir.isDirectory()) { FileSystemUtils.purge(mySkinDir); } } }
From source file:org.shredzone.commons.gravatar.impl.GravatarServiceImpl.java
/** * Fetches a Gravatar icon from the server and stores it in the given {@link File}. * * @param url/*from w ww . j av a 2 s.c o m*/ * Gravatar URL to fetch * @param file * {@link File} to store the icon to */ private void fetchGravatar(URL url, File file) throws IOException { limitUpstreamRequests(); URLConnection conn = url.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); if (file.exists()) { conn.setIfModifiedSince(file.lastModified()); } conn.connect(); long lastModified = conn.getLastModified(); if (lastModified > 0L && lastModified <= file.lastModified()) { // Cache file exists and is unchanged if (log.isDebugEnabled()) { log.debug("Cached Gravatar is still good: {}", url); } file.setLastModified(System.currentTimeMillis()); // touch return; } try (InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(file)) { byte[] buffer = new byte[8192]; int total = 0; int len; while ((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); total += len; if (total > MAX_GRAVATAR_SIZE) { log.warn("Gravatar exceeded maximum size: {}", url); break; } } out.flush(); if (log.isDebugEnabled()) { log.debug("Downloaded Gravatar: {}", url); } } }
From source file:org.rhq.enterprise.server.core.plugin.PluginDeploymentScanner.java
/** * Take the plugins placed in the user directory, and copy them to their apprpriate places * in the server./* w ww. j av a 2 s .c om*/ */ private void scanUserDirectory() { File userDir = getUserPluginDir(); if (userDir == null || !userDir.isDirectory()) { return; // not configured for a user directory, just return immediately and do nothing } File[] listFiles = userDir.listFiles(); if (listFiles == null || listFiles.length == 0) { return; // nothing to do } for (File file : listFiles) { File destinationDirectory; if (file.getName().endsWith(".jar")) { try { if (null == AgentPluginDescriptorUtil.loadPluginDescriptorFromUrl(file.toURI().toURL())) { throw new NullPointerException("no xml descriptor found in jar"); } destinationDirectory = getAgentPluginDir(); } catch (Exception e) { try { log.debug("[" + file.getAbsolutePath() + "] is not an agent plugin jar (Cause: " + ThrowableUtil.getAllMessages(e) + "). Will see if its a server plugin jar"); if (null == ServerPluginDescriptorUtil.loadPluginDescriptorFromUrl(file.toURI().toURL())) { throw new NullPointerException("no xml descriptor found in jar"); } destinationDirectory = getServerPluginDir(); } catch (Exception e1) { // skip it, doesn't look like a valid plugin jar File fixmeFile = new File(file.getAbsolutePath() + ".fixme"); boolean renamed = file.renameTo(fixmeFile); log.warn("Does not look like [" + (renamed ? fixmeFile : file).getAbsolutePath() + "] is a plugin jar -(Cause: " + ThrowableUtil.getAllMessages(e1) + "). It will be ignored. Please fix that file or remove it."); continue; } } try { String fileMd5 = MessageDigestGenerator.getDigestString(file); File realPluginFile = new File(destinationDirectory, file.getName()); String realPluginFileMd5 = null; if (realPluginFile.exists()) { realPluginFileMd5 = MessageDigestGenerator.getDigestString(realPluginFile); } if (!fileMd5.equals(realPluginFileMd5)) { if (file.lastModified() > realPluginFile.lastModified()) { FileUtil.copyFile(file, realPluginFile); boolean succeeded = realPluginFile.setLastModified(file.lastModified()); if (!succeeded) { log.error("Failed to set mtime to [" + new Date(file.lastModified()) + "] on file [" + realPluginFile + "]."); } log.info("Found plugin jar at [" + file.getAbsolutePath() + "] and placed it at [" + realPluginFile.getAbsolutePath() + "]"); } } boolean deleted = file.delete(); if (!deleted) { log.info("The plugin jar found at[" + file.getAbsolutePath() + "] has been processed and can be deleted. It failed to get deleted, " + "so it may get processed again. You should delete it manually now."); } } catch (Exception e) { log.error("Failed to process plugin [" + file.getAbsolutePath() + "], ignoring it", e); } } } return; }
From source file:com.virtualparadigm.packman.processor.JPackageManagerBU.java
public static boolean configure(File tempDir, Configuration configuration) { logger.info("PackageManager::configure()"); boolean status = true; if (tempDir != null && configuration != null && !configuration.isEmpty()) { VelocityEngine velocityEngine = new VelocityEngine(); Properties vProps = new Properties(); vProps.setProperty("resource.loader", "string"); vProps.setProperty("string.resource.loader.class", "org.apache.velocity.runtime.resource.loader.StringResourceLoader"); velocityEngine.init(vProps);/* ww w . ja v a 2 s . c o m*/ Template template = null; VelocityContext velocityContext = JPackageManagerBU.createVelocityContext(configuration); StringResourceRepository stringResourceRepository = StringResourceLoader.getRepository(); String templateContent = null; StringWriter stringWriter = null; long lastModified; Collection<File> patchFiles = FileUtils.listFiles( new File(tempDir.getAbsolutePath() + "/" + JPackageManagerBU.PATCH_DIR_NAME + "/" + JPackageManagerBU.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.replaceAll("(\\$)(\\{)([^\\}]*)(\\:)([^\\}]*)(\\})", "#$2$3$4$5$6"); stringResourceRepository.putStringResource(JPackageManagerBU.CURRENT_TEMPLATE_NAME, templateContent); stringWriter = new StringWriter(); template = velocityEngine.getTemplate(JPackageManagerBU.CURRENT_TEMPLATE_NAME); template.merge(velocityContext, stringWriter); templateContent = stringWriter.toString(); templateContent = templateContent.replaceAll("(#)(\\{)([^\\}]*)(\\:)([^\\}]*)(\\})", "\\$$2$3$4$5$6"); FileUtils.writeStringToFile(pfile, templateContent); pfile.setLastModified(lastModified); } catch (Exception e) { e.printStackTrace(); } } } Collection<File> scriptFiles = FileUtils.listFiles( new File(tempDir.getAbsolutePath() + "/" + JPackageManagerBU.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.replaceAll("(\\$)(\\{)([^\\}]*)(\\:)([^\\}]*)(\\})", "#$2$3$4$5$6"); stringResourceRepository.putStringResource(JPackageManagerBU.CURRENT_TEMPLATE_NAME, templateContent); stringWriter = new StringWriter(); template = velocityEngine.getTemplate(JPackageManagerBU.CURRENT_TEMPLATE_NAME); template.merge(velocityContext, stringWriter); templateContent = stringWriter.toString(); templateContent = templateContent.replaceAll("(#)(\\{)([^\\}]*)(\\:)([^\\}]*)(\\})", "\\$$2$3$4$5$6"); FileUtils.writeStringToFile(scriptfile, templateContent); scriptfile.setLastModified(lastModified); } catch (Exception e) { e.printStackTrace(); } } } } return status; }
From source file:com.sun.faban.harness.webclient.Uploader.java
/** * Responsible for uploading the runs./* w w w.j a v a 2 s. c om*/ * @param request * @param response * @return String * @throws java.io.IOException * @throws javax.servlet.ServletException * @throws java.lang.ClassNotFoundException */ public String uploadRuns(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, ClassNotFoundException { // 3. Upload the run HashSet<String> duplicateSet = new HashSet<String>(); HashSet<String> replaceSet = new HashSet<String>(); String host = null; String key = null; boolean origin = false; // Whether the upload is to the original // run requestor. If so, key is needed. DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(4096); // the location for saving data that is larger than // getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("host".equals(fieldName)) { host = item.getString(); } else if ("replace".equals(fieldName)) { replaceSet.add(item.getString()); } else if ("key".equals(fieldName)) { key = item.getString(); } else if ("origin".equals(fieldName)) { String value = item.getString(); origin = Boolean.parseBoolean(value); } continue; } if (host == null) { logger.warning("Host not received on upload request!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } // The host, origin, key info must be here before we receive // any file. if (origin) { if (Config.daemonMode != Config.DaemonModes.POLLEE) { logger.warning("Origin upload requested. Not pollee!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (key == null) { logger.warning("Origin upload requested. No key!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (!RunRetriever.authenticate(host, key)) { logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } } if (!"jarfile".equals(fieldName)) // ignore continue; String fileName = item.getName(); if (fileName == null) // We don't process files without names continue; // Now, this name may have a path attached, dependent on the // source browser. We need to cover all possible clients... char[] pathSeparators = { '/', '\\' }; // Well, if there is another separator we did not account for, // just add it above. for (int j = 0; j < pathSeparators.length; j++) { int idx = fileName.lastIndexOf(pathSeparators[j]); if (idx != -1) { fileName = fileName.substring(idx + 1); break; } } // Ignore all non-jarfiles. if (!fileName.toLowerCase().endsWith(".jar")) continue; File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName); try { item.write(uploadFile); } catch (Exception e) { throw new ServletException(e); } int runIdx = fileName.lastIndexOf("."); String runName = host + '.' + fileName.substring(0, runIdx); File runTmp = unjarTmp(uploadFile); //Check if archived recently if (checkIfArchived(runName) && !(replaceSet.contains(fileName.substring(0, runIdx)))) { //Now check if timestamps are same //Get the timestamp of run being uploaded at this point //ts is timestamp of run being uploaded String ts = getRunIdTimestamp(runName, Config.TMP_DIR); l1: while (true) { //reposTs is timestamp of run being compared in the //repository String reposTs = getRunIdTimestamp(runName, Config.OUT_DIR); if (reposTs.equals(ts)) { duplicateSet.add(fileName.substring(0, runIdx)); } else { runName = getNextRunId(runName); if (checkIfArchived(runName)) continue l1; File newRunNameFile = new File(Config.OUT_DIR, runName); if (newRunNameFile.exists()) { recursiveDelete(newRunNameFile); } if (recursiveCopy(runTmp, newRunNameFile)) { newRunNameFile.setLastModified(runTmp.lastModified()); uploadTags(runName); uploadFile.delete(); recursiveDelete(runTmp); } else { logger.warning("Origin upload requested. " + "Copy error!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); break; } response.setStatus(HttpServletResponse.SC_CREATED); } break; } } else { //File runTmp = unjarTmp(uploadFile); String runId = null; if (origin) { // Change origin file to know where this run came from. File metaInf = new File(runTmp, "META-INF"); File originFile = new File(metaInf, "origin"); if (!originFile.exists()) { logger.warning("Origin upload requested. " + "Origin file does not exist!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!"); break; } RunId origRun; try { origRun = new RunId(readStringFromFile(originFile).trim()); } catch (IndexOutOfBoundsException e) { response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file error. " + e.getMessage()); break; } runId = origRun.getBenchName() + '.' + origRun.getRunSeq(); String localHost = origRun.getHostName(); if (!localHost.equals(Config.FABAN_HOST)) { logger.warning("Origin upload requested. Origin " + "host" + localHost + " does not match this host " + Config.FABAN_HOST + '!'); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } writeStringToFile(runTmp.getName(), originFile); } else { runId = runTmp.getName(); } File newRunFile = new File(Config.OUT_DIR, runId); if (newRunFile.exists()) { recursiveDelete(newRunFile); } if (recursiveCopy(runTmp, newRunFile)) { newRunFile.setLastModified(runTmp.lastModified()); uploadFile.delete(); uploadTags(runId); recursiveDelete(runTmp); } else { logger.warning("Origin upload requested. Copy error!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); break; } } response.setStatus(HttpServletResponse.SC_CREATED); //break; } request.setAttribute("duplicates", duplicateSet); return "/duplicates.jsp"; }