List of usage examples for java.io File setLastModified
public boolean setLastModified(long time)
From source file:org.apache.karaf.decanter.kibana6.KibanaController.java
public void download() throws Exception { File target = new File(workingDirectory, KIBANA_FOLDER); if (target.exists()) { LOGGER.warn("Kibana folder already exists, download is skipped"); return;/*ww w. ja va2 s. c o m*/ } LOGGER.debug("Downloading Kibana from {}", KIBANA_LOCATION); if (isWindows()) { try (ZipArchiveInputStream inputStream = new ZipArchiveInputStream( new URL(KIBANA_LOCATION).openStream())) { ZipArchiveEntry entry; while ((entry = (ZipArchiveEntry) inputStream.getNextEntry()) != null) { File file = new File(workingDirectory, entry.getName()); if (entry.isDirectory()) { file.mkdirs(); } else { int read; byte[] buffer = new byte[4096]; try (FileOutputStream outputStream = new FileOutputStream(file)) { while ((read = inputStream.read(buffer, 0, 4096)) != -1) { outputStream.write(buffer, 0, read); } } } } } } else { try (GzipCompressorInputStream gzInputStream = new GzipCompressorInputStream( new URL(KIBANA_LOCATION).openStream())) { try (TarArchiveInputStream inputStream = new TarArchiveInputStream(gzInputStream)) { TarArchiveEntry entry; while ((entry = (TarArchiveEntry) inputStream.getNextEntry()) != null) { File file = new File(workingDirectory, entry.getName()); if (entry.isDirectory()) { file.mkdirs(); } else { int read; byte[] buffer = new byte[4096]; try (FileOutputStream outputStream = new FileOutputStream(file)) { while ((read = inputStream.read(buffer, 0, 4096)) != -1) { outputStream.write(buffer, 0, read); } } file.setLastModified(entry.getLastModifiedDate().getTime()); if (entry instanceof TarArchiveEntry) { int mode = ((TarArchiveEntry) entry).getMode(); if ((mode & 00100) > 0) { file.setExecutable(true, (mode & 00001) == 0); } } } } } } } overrideConfig(); }
From source file:com.emc.ecs.sync.target.FilesystemTarget.java
@Override public void filter(SyncObject obj) { File destFile = createFile(targetRoot.getPath(), obj.getRelativePath()); obj.setTargetIdentifier(destFile.getPath()); log.debug("Writing {} to {}", obj.getSourceIdentifier(), destFile); Date mtime = FilesystemUtil.getMtime(obj); // make sure parent directory exists mkdirs(destFile.getParentFile());//from w ww . jav a 2s. c o m // if required we will need to update metadata after any streaming operation boolean dataCopied = false; if (obj.isDirectory()) { synchronized (this) { if (!destFile.exists() && !destFile.mkdir()) throw new RuntimeException("Failed to create directory " + destFile); } } else { // If forced, retrying, newer or different size, copy the file data if (force || obj.getFailureCount() > 0 || mtime == null || !destFile.exists() || mtime.after(new Date(destFile.lastModified())) || obj.getMetadata().getContentLength() != destFile.length()) { copyData(obj, destFile); dataCopied = true; } else { log.debug("No change in content timestamps for {}", obj.getSourceIdentifier()); } } // encapsulate metadata from source system if (!ignoreMetadata) { File metaFile = createFile(null, SyncMetadata.getMetaPath(destFile.getPath(), destFile.isDirectory())); File metaDir = metaFile.getParentFile(); Date ctime = null; if (obj.getMetadata() instanceof AtmosMetadata) { // check for ctime in system meta UserMetadata m = ((AtmosMetadata) obj.getMetadata()).getSystemMetadata().get("ctime"); if (m != null) ctime = Iso8601Util.parse(m.getValue()); } if (ctime == null) ctime = mtime; // use mtime if there is no ctime // create metadata directory if it doesn't already exist synchronized (this) { if (!metaDir.exists() && !metaDir.mkdir()) throw new RuntimeException("Failed to create metadata directory " + metaDir); } // if *ctime* is newer or forced, write the metadata file.. also if object has generated new metadata from // a streaming operation if (force || ctime == null || !metaFile.exists() || ctime.after(new Date(metaFile.lastModified())) || (dataCopied && obj.requiresPostStreamMetadataUpdate())) { try { String metaJson = obj.getMetadata().toJson(); copyData(new ByteArrayInputStream(metaJson.getBytes("UTF-8")), metaFile); if (ctime != null) { // Set the metadata file mtime to the source ctime (i.e. this // metadata file's content is modified at the same // time as the source's metadata modification time) if (!metaFile.setLastModified(ctime.getTime())) log.warn("Failed to set mtime of {}", metaFile); } } catch (IOException e) { throw new RuntimeException("Failed to write metadata to: " + metaFile, e); } } else { log.debug("No change in metadata for {}", obj.getSourceIdentifier()); } } try { // TODO: figure out "preserve"/"restore" option // TODO: make the behavior here configurable (do we fail? do we track in the DB?) FilesystemUtil.applyFilesystemMetadata(destFile, obj.getMetadata(), includeAcl, true); } catch (Exception e) { log.warn("could not apply filesystem metadata to " + destFile, e); } }
From source file:org.jenkinsci.modules.optpluginhelper.PluginHelper.java
/** * List all the optional plugins (while populating the staging area with any new ones we discover). * * @return the list of optional plugins available from all the current defined {@link PluginSource} extensions. *///from ww w . ja va 2 s . co m private List<File> listPlugins() { // TODO figure out what to do if two sources provide different versions of the same plugin, currently undefined List<File> result = new ArrayList<File>(); final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { return result; } File baseDir = new File(jenkins.root, OPTIONAL_PLUGIN_DIR); if (baseDir.exists() && !baseDir.isDirectory()) { LOGGER.log(Level.SEVERE, "Optional plugin working directory {0} exists and is not a directory", baseDir); return result; } if (!baseDir.isDirectory()) { if (!baseDir.mkdirs()) { LOGGER.log(Level.SEVERE, "Could not create optional plugin working directory {0}", baseDir); return result; } } for (URL resource : PluginSource.allPlugins()) { try { final String externalForm = resource.toExternalForm(); ExtractedPluginMetadata metadata = extractedPluginMetadataMap.get(externalForm); if (metadata != null) { File archive = new File(baseDir, metadata.shortName + ".jpi"); if (archive.isFile() && archive.length() == metadata.length && Util.getDigestOf(archive).equals(metadata.digest)) { result.add(archive); continue; } } final URLConnection connection = resource.openConnection(); long lastModified = connection.getLastModified(); long size = connection.getContentLength(); String path = resource.getPath(); String fileName = FilenameUtils.getBaseName(path); boolean nameCheck = false; if (StringUtils.isBlank(fileName)) { nameCheck = true; fileName = Util.getDigestOf(resource.toString()); } File file = new File(baseDir, fileName + ".jpi"); if (file.isFile() && (file.lastModified() == lastModified || lastModified == 0) && file.length() == size) { final String fileDigest = Util.getDigestOf(file); final String resourceDigest; final InputStream stream = connection.getInputStream(); try { resourceDigest = Util.getDigestOf(stream); } finally { IOUtils.closeQuietly(stream); } if (fileDigest.equals(resourceDigest)) { result.add(file); extractedPluginMetadataMap.put(externalForm, new ExtractedPluginMetadata(file)); continue; } } FileUtils.copyURLToFile(resource, file); if (nameCheck) { final String shortName = jenkins.getPluginManager().getPluginStrategy().getShortName(file); if (!fileName.equals(shortName)) { File newFile = new File(baseDir, shortName + ".jpi"); if (!newFile.isFile() || !Util.getDigestOf(newFile).equals(Util.getDigestOf(file))) { FileUtils.moveFile(file, newFile); } file = newFile; } } if (lastModified != 0) { if (!file.setLastModified(lastModified)) { LOGGER.log(Level.FINE, "Couldn't set last modified on {0}", file); } } result.add(file); extractedPluginMetadataMap.put(externalForm, new ExtractedPluginMetadata(file)); } catch (IOException e) { LOGGER.log(Level.WARNING, String.format("Could not process optional plugin from %s", resource), e); } } LOGGER.log(Level.FINE, "List of plugins: " + result); return result; }
From source file:com.apache.ivy.BasicURLHandler.java
public void download(URL src, File dest, CopyProgressListener l) throws IOException { // Install the IvyAuthenticator if ("http".equals(src.getProtocol()) || "https".equals(src.getProtocol())) { IvyAuthenticator.install();// ww w . j a va 2s. c o m } URLConnection srcConn = null; try { src = normalizeToURL(src); srcConn = src.openConnection(); srcConn.setRequestProperty("User-Agent", "Apache Ivy/1.0");// + Ivy.getIvyVersion()); srcConn.setRequestProperty("Accept-Encoding", "gzip,deflate"); if (srcConn instanceof HttpURLConnection) { HttpURLConnection httpCon = (HttpURLConnection) srcConn; if (!checkStatusCode(src, httpCon)) { throw new IOException("The HTTP response code for " + src + " did not indicate a success." + " See log for more detail."); } } // do the download InputStream inStream = getDecodingInputStream(srcConn.getContentEncoding(), srcConn.getInputStream()); FileUtil.copy(inStream, dest, l); // check content length only if content was not encoded if (srcConn.getContentEncoding() == null) { int contentLength = srcConn.getContentLength(); if (contentLength != -1 && dest.length() != contentLength) { dest.delete(); throw new IOException("Downloaded file size doesn't match expected Content Length for " + src + ". Please retry."); } } // update modification date long lastModified = srcConn.getLastModified(); if (lastModified > 0) { dest.setLastModified(lastModified); } } finally { disconnect(srcConn); } }
From source file:hudson.FilePath.java
/** * Creates a file (if not already exist) and sets the timestamp. * * @since 1.299//from w w w. j ava 2s.c om */ public void touch(final long timestamp) throws IOException, InterruptedException { act(new FileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { if (!f.exists()) new FileOutputStream(f).close(); if (!f.setLastModified(timestamp)) throw new IOException("Failed to set the timestamp of " + f + " to " + timestamp); return null; } }); }
From source file:net.sf.jvifm.ui.FileLister.java
private void updateEditItem(Text textEditor, String itemType) { if (!textEditor.getText().trim().equals("")) { TableItem item = table.getItem(currentRow); File currentFile = new File(FilenameUtils.concat(pwd, textEditor.getText())); boolean isSuccess = false; if (itemType.equals("file")) { isSuccess = true;//from ww w. j av a2s . c om if (!currentFile.exists()) { try { currentFile.createNewFile(); } catch (IOException e) { isSuccess = false; } } else { currentFile.setLastModified(System.currentTimeMillis()); } } else if (itemType.equals("folder")) { isSuccess = fileModelManager.mkdir(currentFile.getPath()); } else if (itemType.equals("rename")) { isSuccess = currentFile.renameTo(new File(FilenameUtils.concat(pwd, textEditor.getText().trim()))); } if (isSuccess) { fileManager.setStatusInfo("command successed."); //$NON-NLS-1$ } else { fileManager.setStatusInfo("command failed."); //$NON-NLS-1$ } item.setText(0, textEditor.getText().trim()); textEditor.dispose(); editor.dispose(); } updateStatusText(); }
From source file:net.tourbook.photo.internal.manager.PhotoImageLoader.java
/** * Get image from thumb store with the requested image quality. * /*from w ww .j a va 2 s . co m*/ * @param _photo * @param requestedImageQuality * @return */ private Image loadImageFromStore(final ImageQuality requestedImageQuality) { /* * check if image is available in the thumbstore */ final IPath requestedStoreImageFilePath = ThumbnailStore.getStoreImagePath(_photo, requestedImageQuality); final String imageStoreFilePath = requestedStoreImageFilePath.toOSString(); final File storeImageFile = new File(imageStoreFilePath); if (storeImageFile.isFile() == false) { return null; } // photo image is available in the thumbnail store Image storeImage = null; /* * touch store file when it is not yet done today, this is done to track last access time so * that a store cleanup can check the date */ final LocalDate dtModified = TimeTools.getZonedDateTime(storeImageFile.lastModified()).toLocalDate(); if (dtModified.equals(LocalDate.now()) == false) { storeImageFile.setLastModified(TimeTools.now().toInstant().toEpochMilli()); } try { storeImage = new Image(_display, imageStoreFilePath); loadImageProperties(requestedStoreImageFilePath); } catch (final Exception e) { StatusUtil.log(NLS.bind("Image cannot be loaded with SWT (1): \"{0}\"", //$NON-NLS-1$ imageStoreFilePath), e); } finally { if (storeImage == null) { String message = "Image \"{0}\" cannot be loaded and an exception did not occure.\n" //$NON-NLS-1$ + "The image file is available but it's possible that SWT.ERROR_NO_HANDLES occured"; //$NON-NLS-1$ System.out.println(UI.timeStampNano() + NLS.bind(message, imageStoreFilePath)); PhotoImageCache.disposeThumbs(null); /* * try loading again */ try { storeImage = new Image(_display, imageStoreFilePath); } catch (final Exception e) { StatusUtil.log(NLS.bind("Image cannot be loaded with SWT (2): \"{0}\"", //$NON-NLS-1$ imageStoreFilePath), e); } finally { if (storeImage == null) { message = "Image cannot be loaded again with SWT, even when disposing the image cache: \"{0}\" "; //$NON-NLS-1$ System.out.println(UI.timeStampNano() + NLS.bind(message, imageStoreFilePath)); } } } } return storeImage; }
From source file:io.sloeber.core.managers.InternalPackageManager.java
public static IStatus extract(ArchiveInputStream in, File destFolder, int stripPath, boolean overwrite, IProgressMonitor pMonitor) throws IOException, InterruptedException { // Folders timestamps must be set at the end of archive extraction // (because creating a file in a folder alters the folder's timestamp) Map<File, Long> foldersTimestamps = new HashMap<>(); String pathPrefix = new String(); Map<File, File> hardLinks = new HashMap<>(); Map<File, Integer> hardLinksMode = new HashMap<>(); Map<File, String> symLinks = new HashMap<>(); Map<File, Long> symLinksModifiedTimes = new HashMap<>(); // Cycle through all the archive entries while (true) { ArchiveEntry entry = in.getNextEntry(); if (entry == null) { break; }/*from w w w .j a v a 2 s . c om*/ // Extract entry info long size = entry.getSize(); String name = entry.getName(); boolean isDirectory = entry.isDirectory(); boolean isLink = false; boolean isSymLink = false; String linkName = null; Integer mode = null; Long modifiedTime = new Long(entry.getLastModifiedDate().getTime()); pMonitor.subTask("Processing " + name); //$NON-NLS-1$ { // Skip MacOSX metadata // http://superuser.com/questions/61185/why-do-i-get-files-like-foo-in-my-tarball-on-os-x int slash = name.lastIndexOf('/'); if (slash == -1) { if (name.startsWith("._")) { //$NON-NLS-1$ continue; } } else { if (name.substring(slash + 1).startsWith("._")) { //$NON-NLS-1$ continue; } } } // Skip git metadata // http://www.unix.com/unix-for-dummies-questions-and-answers/124958-file-pax_global_header-means-what.html if (name.contains("pax_global_header")) { //$NON-NLS-1$ continue; } if (entry instanceof TarArchiveEntry) { TarArchiveEntry tarEntry = (TarArchiveEntry) entry; mode = new Integer(tarEntry.getMode()); isLink = tarEntry.isLink(); isSymLink = tarEntry.isSymbolicLink(); linkName = tarEntry.getLinkName(); } // On the first archive entry, if requested, detect the common path // prefix to be stripped from filenames int localstripPath = stripPath; if (localstripPath > 0 && pathPrefix.isEmpty()) { int slash = 0; while (localstripPath > 0) { slash = name.indexOf("/", slash); //$NON-NLS-1$ if (slash == -1) { throw new IOException(Messages.Manager_archiver_eror_single_root_folder_required); } slash++; localstripPath--; } pathPrefix = name.substring(0, slash); } // Strip the common path prefix when requested if (!name.startsWith(pathPrefix)) { throw new IOException(Messages.Manager_archive_error_root_folder_name_mismatch.replace(FILE, name) .replace(FOLDER, pathPrefix)); } name = name.substring(pathPrefix.length()); if (name.isEmpty()) { continue; } File outputFile = new File(destFolder, name); File outputLinkedFile = null; if (isLink && linkName != null) { if (!linkName.startsWith(pathPrefix)) { throw new IOException(Messages.Manager_archive_error_root_folder_name_mismatch .replace(FILE, name).replace(FOLDER, pathPrefix)); } linkName = linkName.substring(pathPrefix.length()); outputLinkedFile = new File(destFolder, linkName); } if (isSymLink) { // Symbolic links are referenced with relative paths outputLinkedFile = new File(linkName); if (outputLinkedFile.isAbsolute()) { System.err.println(Messages.Manager_archive_error_symbolic_link_to_absolute_path .replace(FILE, outputFile.toString()).replace(FOLDER, outputLinkedFile.toString())); System.err.println(); } } // Safety check if (isDirectory) { if (outputFile.isFile() && !overwrite) { throw new IOException( Messages.Manager_Cant_create_folder_exists.replace(FILE, outputFile.getPath())); } } else { // - isLink // - isSymLink // - anything else if (outputFile.exists() && !overwrite) { throw new IOException( Messages.Manager_Cant_extract_file_exist.replace(FILE, outputFile.getPath())); } } // Extract the entry if (isDirectory) { if (!outputFile.exists() && !outputFile.mkdirs()) { throw new IOException(Messages.Manager_Cant_create_folder.replace(FILE, outputFile.getPath())); } foldersTimestamps.put(outputFile, modifiedTime); } else if (isLink) { hardLinks.put(outputFile, outputLinkedFile); hardLinksMode.put(outputFile, mode); } else if (isSymLink) { symLinks.put(outputFile, linkName); symLinksModifiedTimes.put(outputFile, modifiedTime); } else { // Create the containing folder if not exists if (!outputFile.getParentFile().isDirectory()) { outputFile.getParentFile().mkdirs(); } copyStreamToFile(in, size, outputFile); outputFile.setLastModified(modifiedTime.longValue()); } // Set file/folder permission if (mode != null && !isSymLink && outputFile.exists()) { chmod(outputFile, mode.intValue()); } } for (Map.Entry<File, File> entry : hardLinks.entrySet()) { if (entry.getKey().exists() && overwrite) { entry.getKey().delete(); } link(entry.getValue(), entry.getKey()); Integer mode = hardLinksMode.get(entry.getKey()); if (mode != null) { chmod(entry.getKey(), mode.intValue()); } } for (Map.Entry<File, String> entry : symLinks.entrySet()) { if (entry.getKey().exists() && overwrite) { entry.getKey().delete(); } symlink(entry.getValue(), entry.getKey()); entry.getKey().setLastModified(symLinksModifiedTimes.get(entry.getKey()).longValue()); } // Set folders timestamps for (Map.Entry<File, Long> entry : foldersTimestamps.entrySet()) { entry.getKey().setLastModified(entry.getValue().longValue()); } return Status.OK_STATUS; }
From source file:net.paissad.waqtsalat.utils.DownloadHelper.java
/** * <p>/*from w w w .ja v a 2s . co m*/ * Download a resource from the specified url and save it to the specified * file. * </p> * <b>Note</b>: If you plan to cancel the download at any time, then this * method should be embed into it's own thread. * <p> * <b>Example</b>: * * <pre> * final DownloadHelper downloader = new DownloadHelper(); * Thread t = new Thread() { * public void run() { * try { * downloader.download("http://domain.com/file.zip", new File("/tmp/output.zip")); * } catch (Exception e) { * ... * } * } * }; * t.start(); * // Waits 3 seconds and then cancels the download. * Thread.sleep(3 * 1000L); * downloader.cancel(); * ... * </pre> * * </p> * * @param url * - The url of the file to download. * @param file * - The downloaded file (where it will be stored). * @throws IOException * @throws HttpException */ public void download(final String url, final File file) throws HttpException, IOException { GetMethod method = null; InputStream responseBody = null; OutputStream out = null; try { final boolean fileExisted = file.exists(); HttpClient client = new HttpClient(); method = new GetMethod(url); method.setFollowRedirects(true); method.setRequestHeader("User-Agent", WSConstants.WS_USER_AGENT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); method.getParams().setParameter(HttpMethodParams.WARN_EXTRA_INPUT, Boolean.TRUE); // Execute the method. int responseCode = client.executeMethod(method); if (responseCode != HttpStatus.SC_OK) { logger.error("Http method failed : {}.", method.getStatusLine().toString()); } // Read the response body. responseBody = method.getResponseBodyAsStream(); // Let's try to compute the amount of total bytes of the file to // download. URL u = new URL(url); URLConnection urlc = u.openConnection(); this.totalBytes = urlc.getContentLength(); long lastModified = urlc.getLastModified(); // The OutputStream for the 'downloaded' file. out = new BufferedOutputStream(new FileOutputStream(file)); this.updateState(DownloadState.IN_PROGRESS); byte[] data = new byte[BUFFER_SIZE]; int length; while ((length = responseBody.read(data, 0, BUFFER_SIZE)) != -1 && !isCancelled) { out.write(data, 0, length); this.bytesDownloaded += length; setChanged(); notifyObservers(getBytesDownloaded()); } if (isCancelled) { this.updateState(DownloadState.CANCELED); logger.info("The download has been cancelled."); } else { // The download was not cancelled. out.flush(); if (lastModified > 0) { file.setLastModified(lastModified); } if (bytesDownloaded != totalBytes) { logger.warn("The expected bytes to download is {}, but got {}.", getTotalBytes(), getBytesDownloaded()); this.updateState(DownloadState.ERROR); } this.updateState(DownloadState.FINISHED); logger.info("Download of '{}' finished successfully.", url); } // If the file did not exist before the download but does exit now, // we must remove it if an error occurred or if the download was // cancelled. if (getState() == DownloadState.CANCELED || getState() == DownloadState.ERROR) { if (!fileExisted && file.exists()) { FileUtils.forceDelete(file); } } } catch (HttpException he) { this.updateState(DownloadState.ERROR); logger.error("Fatal protocol violation : " + he); throw new HttpException("Error while downloading from the url '" + url + "'", he); } catch (IOException ioe) { this.updateState(DownloadState.ERROR); logger.error("Fatal transport error : " + ioe); throw new IOException(ioe); } finally { if (method != null) method.releaseConnection(); if (responseBody != null) responseBody.close(); if (out != null) out.close(); } }