List of usage examples for java.io File setLastModified
public boolean setLastModified(long time)
From source file:com.jpeterson.util.etag.FileETagTest.java
/** * Test the calculate method when using file last modified, file size, and * file content values./*from w ww . j a v a2s . c o m*/ */ public void test_calculateLastModifiedSizeContent() { File file; String content = "Hello, world!"; String expected; 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); // determined expected MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(content.getBytes()); StringBuffer buffer = new StringBuffer(); buffer.append(lastModified); buffer.append(content.length()); expected = new String(Hex.encodeHex(messageDigest.digest(buffer.toString().getBytes()))); etag = new FileETag(); etag.setFlags(FileETag.FLAG_CONTENT | FileETag.FLAG_MTIME | FileETag.FLAG_SIZE); String value = etag.calculate(file); assertEquals("Unexpected value", expected, 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"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); fail("Unexpected exception"); } }
From source file:com.openedit.util.FileUtils.java
public void copyFiles(File source, File destination) throws IOException { if (source.isDirectory()) { if (destination.exists() && !destination.isDirectory()) { destination.delete();/*w w w . j a va2 s .com*/ } destination.mkdirs(); //loop over all the sub files File[] children = source.listFiles(); for (int i = 0; i < children.length; i++) { copyFiles(children[i], new File(destination, children[i].getName())); } } else { if (destination.isDirectory()) { copyFiles(source, new File(destination, source.getName())); } else { destination.getParentFile().mkdirs(); fieldFiller.fill(source, destination); destination.setLastModified(source.lastModified()); } } }
From source file:org.artifactory.repo.db.importexport.DbExportBase.java
private boolean exportFileContent(FileInfo sourceFile, File targetFile) throws IOException { log.debug("Exporting file content to {}", targetFile.getAbsolutePath()); OutputStream os = null;//from ww w . ja v a2 s . co m InputStream is = null; try { // get the stream directly from the datastore (no fs item locks) is = getBinaryStore().getBinary(sourceFile.getSha1()); os = new BufferedOutputStream(new FileOutputStream(targetFile)); IOUtils.copy(is, os); } catch (VfsItemNotFoundException e) { // since we work with an unlocked items there's a small chance the binary doesn't exist anymore status.warn("Binary not found for item '" + sourceFile.getRepoPath() + "'" + " with sha1 '" + sourceFile.getSha1() + "'", log); return false; } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } targetFile.setLastModified(sourceFile.getLastModified()); return true; }
From source file:org.ngrinder.infra.AgentConfig.java
private void copyDefaultConfigurationFiles() { checkNotNull(home);/*from w w w . ja v a2 s . com*/ final File agentConfig = home.getFile("agent.conf"); File newAgentConfig = new File(getCurrentDirectory(), "__agent.conf"); if (agentConfig.exists()) { if (System.getProperty(CommonConstants.PROP_OVERWRITE_CONFIG) != null) { LOGGER.info("Overwrite the existing agent.conf with __agent.conf"); } else if (newAgentConfig.exists()) { LOGGER.warn("The agent configuration file '{}' already exists.", agentConfig.getAbsolutePath()); LOGGER.warn("If you want to use the '{}' file", newAgentConfig.getAbsolutePath()); LOGGER.warn("Please run agent with -o option"); return; } } if (newAgentConfig.exists()) { home.copyFileTo(newAgentConfig, "agent.conf"); agentConfig.setLastModified(newAgentConfig.lastModified()); } else { try { home.writeFileTo(loadResource("/agent.conf"), "agent.conf"); } catch (IOException e) { throw processException(e); } } }
From source file:org.gradle.caching.internal.tasks.TarTaskOutputPacker.java
private void unpack(TaskOutputsInternal taskOutputs, TarInputStream tarInput, TaskOutputOriginReader readOriginAction) throws IOException { Map<String, TaskOutputFilePropertySpec> propertySpecs = Maps.uniqueIndex(taskOutputs.getFileProperties(), new Function<TaskFilePropertySpec, String>() { @Override// w ww. j a v a 2s.c o m public String apply(TaskFilePropertySpec propertySpec) { return propertySpec.getPropertyName(); } }); boolean originSeen = false; TarEntry entry; while ((entry = tarInput.getNextEntry()) != null) { String name = entry.getName(); if (name.equals(METADATA_PATH)) { // handle origin metadata originSeen = true; readOriginAction.execute(new CloseShieldInputStream(tarInput)); } else { // handle output property 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 UnsupportedOperationException( String.format("Could not set modification time for '%s'", outputFile)); } } } if (!originSeen) { throw new IllegalStateException("Cached result format error, no origin metadata was found."); } }
From source file:com.blackducksoftware.integration.hub.cli.CLIDownloadService.java
public void customInstall(HubProxyInfo hubProxyInfo, CLILocation cliLocation, CIEnvironmentVariables ciEnvironmentVariables, final URL archive, String hubVersion, final String localHostName) throws IOException, InterruptedException, HubIntegrationException, IllegalArgumentException, EncryptionException { boolean cliMismatch = true; try {// w w w .j av a 2 s . c om final File hubVersionFile = cliLocation.createHubVersionFile(); if (hubVersionFile.exists()) { final String storedHubVersion = IOUtils.toString(new FileReader(hubVersionFile)); if (hubVersion.equals(storedHubVersion)) { cliMismatch = false; } else { hubVersionFile.delete(); hubVersionFile.createNewFile(); } } final File cliInstallDirectory = cliLocation.getCLIInstallDir(); if (!cliInstallDirectory.exists()) { cliMismatch = true; } if (cliMismatch) { logger.debug("Attempting to download the Hub CLI."); final FileWriter writer = new FileWriter(hubVersionFile); writer.write(hubVersion); writer.close(); hubVersionFile.setLastModified(0L); } final long cliTimestamp = hubVersionFile.lastModified(); URLConnection connection = null; try { Proxy proxy = null; if (hubProxyInfo != null) { String proxyHost = hubProxyInfo.getHost(); int proxyPort = hubProxyInfo.getPort(); String proxyUsername = hubProxyInfo.getUsername(); String proxyPassword = hubProxyInfo.getDecryptedPassword(); if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } if (proxy != null) { if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyPassword)) { AuthenticatorUtil.setAuthenticator(proxyUsername, proxyPassword); } else { AuthenticatorUtil.resetAuthenticator(); } } } if (proxy != null) { connection = archive.openConnection(proxy); } else { connection = archive.openConnection(); } connection.setIfModifiedSince(cliTimestamp); connection.connect(); } catch (final IOException ioe) { logger.error("Skipping installation of " + archive + " to " + cliLocation.getCanonicalPath() + ": " + ioe.toString()); return; } if (connection instanceof HttpURLConnection && ((HttpURLConnection) connection).getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { // CLI has not been modified return; } final long sourceTimestamp = connection.getLastModified(); if (cliInstallDirectory.exists() && cliInstallDirectory.listFiles().length > 0) { if (!cliMismatch && sourceTimestamp == cliTimestamp) { logger.debug("The current Hub CLI is up to date."); return; } for (final File file : cliInstallDirectory.listFiles()) { FileUtils.deleteDirectory(file); } } else { cliInstallDirectory.mkdir(); } logger.debug("Updating the Hub CLI."); hubVersionFile.setLastModified(sourceTimestamp); logger.info("Unpacking " + archive.toString() + " to " + cliInstallDirectory.getCanonicalPath() + " on " + localHostName); final CountingInputStream cis = new CountingInputStream(connection.getInputStream()); try { unzip(cliInstallDirectory, cis, logger); updateJreSecurity(logger, cliLocation, ciEnvironmentVariables); } catch (final IOException e) { throw new IOException(String.format("Failed to unpack %s (%d bytes read of total %d)", archive, cis.getByteCount(), connection.getContentLength()), e); } } catch (final IOException e) { throw new IOException("Failed to install " + archive + " to " + cliLocation.getCanonicalPath(), e); } }
From source file:net.mybox.mybox.ClientStatus.java
private void handleInput(Common.Signal operation) { System.out.println("input operation: " + operation.toString()); setStatus(ClientStatus.SYNCING);// w w w. j a v a 2 s.c om if (operation == Common.Signal.s2c) { try { String file_name = ByteStream.toString(inStream); String fileTimeString = ByteStream.toString(inStream); long fileTime = Long.valueOf(fileTimeString); System.out.println("getting file: " + file_name); File file = new File(localDir + "/" + file_name); ByteStream.toFile(inStream, file); file.setLastModified(fileTime); } catch (Exception e) { System.out.println("Operation failed: " + e.getMessage()); } } else if (operation == Common.Signal.deleteOnClient) { // catchup operation try { String name = ByteStream.toString(inStream); Common.deleteLocal(localDir + "/" + name); // should assess return value } catch (Exception e) { System.out.println("Operation failed: " + e.getMessage()); } } else if (operation == Common.Signal.renameOnClient) { // catchup operation try { String arg = ByteStream.toString(inStream); String[] args = arg.split("->"); System.out.println("rename: " + args[0] + " to " + args[1]); Common.renameLocal(localDir + "/" + args[0], localDir + "/" + args[1]); } catch (Exception e) { System.out.println("Operation failed: " + e.getMessage()); } } else if (operation == Common.Signal.createDirectoryOnClient) { // catchup operation try { String name = ByteStream.toString(inStream); Common.createLocalDirectory(localDir + "/" + name); } catch (Exception e) { System.out.println("Operation failed: " + e.getMessage()); } } else if (operation == Common.Signal.clientWantsToSend_response) { try { String name = ByteStream.toString(inStream); String response = ByteStream.toString(inStream); System.out.println("clientWantsToSend_response: " + name + " = " + response); if (response.equals("yes")) { outQueue.push(new MyFile(name)); checkQueue(); } } catch (Exception e) { System.out.println("Operation failed: " + e.getMessage()); } } else if (operation == Common.Signal.requestServerFileList_response) { try { String jsonString = ByteStream.toString(inStream); S = decodeFileList(jsonString); System.out.println("Recieved jsonarray: " + jsonString); } catch (Exception e) { System.out.println("Exception while recieving jsonArray"); } } else if (operation == Common.Signal.attachaccount_response) { String jsonString = null; try { jsonString = ByteStream.toString(inStream); } catch (Exception e) { // } HashMap map = Common.jsonDecode(jsonString); if (!((String) map.get("status")).equals("success")) printWarning("Unable to attach account. Server response: " + map.get("error")); else { account.salt = (String) map.get("salt"); System.out.println("set account salt to: " + account.salt); // inline check of mybox versions if (!Common.appVersion.equals((String) map.get("serverMyboxVersion"))) printErrorExit("Client and Server Mybox versions do not match"); } } else { printMessage("unknown command from server (" + operation + ")"); } setStatus(ClientStatus.READY); lastReceivedOperation = operation; }
From source file:org.eclipse.hudson.init.InitialSetup.java
protected void refreshUpdateCenterMetadataCache() throws IOException { try {//from w w w . jav a2 s .c o m updateSiteManager.refreshFromUpdateSite(); return; } catch (Exception exc) { proxyNeeded = true; logger.info("Could not fetch update center metadata from " + updateSiteManager.getUpdateSiteUrl() + ". Using bundled update center metadata."); } URL updateCenterJsonUrl = servletContext.getResource("/WEB-INF/update-center.json"); if (updateCenterJsonUrl != null) { long lastModified = updateCenterJsonUrl.openConnection().getLastModified(); File localCacheFile = new File(hudsonHomeDir, "updates/default.json"); if (!localCacheFile.exists() || (localCacheFile.lastModified() < lastModified)) { String jsonStr = org.apache.commons.io.IOUtils.toString(updateCenterJsonUrl.openStream()); jsonStr = jsonStr.trim(); if (jsonStr.startsWith("updateCenter.post(")) { jsonStr = jsonStr.substring("updateCenter.post(".length()); } if (jsonStr.endsWith(");")) { jsonStr = jsonStr.substring(0, jsonStr.lastIndexOf(");")); } FileUtils.writeStringToFile(localCacheFile, jsonStr); localCacheFile.setLastModified(lastModified); updateSiteManager.refresh(); } } }
From source file:org.meshcms.core.WebSite.java
public boolean setFileTime(UserInfo user, Path filePath, long time) { if (user == null || !user.canWrite(this, filePath)) { return false; }/*w w w . j a va2s .c om*/ File file = getFile(filePath); if (!file.exists()) { return false; } file.setLastModified(time); return true; }
From source file:org.apache.wiki.providers.VersioningFileProvider.java
/** * {@inheritDoc}//from w w w. j av a 2 s. c o m */ public synchronized void putPageText(WikiPage page, String text) throws ProviderException { // // This is a bit complicated. We'll first need to // copy the old file to be the newest file. // File pageDir = findOldPageDir(page.getName()); if (!pageDir.exists()) { pageDir.mkdirs(); } 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; boolean firstUpdate = (versionNumber == 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 { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } } // // 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()); String authorFirst = null; if (firstUpdate) { // we might not yet have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties(page.getName()); // remember the simulated original author (or something) // in the new properties authorFirst = props2.getProperty("1.author", "unknown"); props.setProperty("1.author", authorFirst); } String newAuthor = page.getAuthor(); if (newAuthor == null) { newAuthor = (authorFirst != null) ? authorFirst : "unknown"; } page.setAuthor(newAuthor); props.setProperty(versionNumber + ".author", newAuthor); String changeNote = (String) page.getAttribute(WikiPage.CHANGENOTE); if (changeNote != null) { props.setProperty(versionNumber + ".changenote", changeNote); } // Get additional custom properties from page and add to props getCustomProperties(page, props); putPageProperties(page.getName(), props); } catch (IOException e) { log.error("Saving failed", e); throw new ProviderException("Could not save page text: " + e.getMessage()); } }