List of usage examples for java.io File setLastModified
public boolean setLastModified(long time)
From source file:ch.entwine.weblounge.dispatcher.impl.handler.PreviewRequestHandlerImpl.java
/** * Creates the preview image for the given resource and returns an input * stream to the preview or <code>null</code> if the preview could not be * created.// w w w . j av a2s .c o m */ private InputStream createPreview(WebloungeRequest request, WebloungeResponse response, Resource<?> resource, Language language, ImageStyle style, PreviewGenerator previewGenerator, File previewFile, ContentRepository contentRepository) { String pathToImageFile = previewFile.getAbsolutePath(); boolean firstOne = true; // Make sure the preview is not already being generated by another thread synchronized (previews) { while (previews.contains(pathToImageFile)) { logger.debug("Preview at {} is being created, waiting for it to be generated", pathToImageFile); firstOne = false; try { previews.wait(500); if (previews.contains(pathToImageFile)) { logger.trace("After waiting 500ms, preview at {} is still being worked on", pathToImageFile); DispatchUtils.sendServiceUnavailable(request, response); return null; } } catch (InterruptedException e) { DispatchUtils.sendServiceUnavailable(request, response); return null; } } // Make sure others are waiting until we are done if (firstOne) { previews.add(pathToImageFile); } } // Determine the resource's modification date long resourceLastModified = ResourceUtils.getModificationDate(resource, language).getTime(); // Create the preview if this is the first request if (firstOne) { ResourceURI resourceURI = resource.getURI(); if (style != null) logger.info("Creating preview of {} with style '{}' at {}", new String[] { resource.getIdentifier(), style.getIdentifier(), pathToImageFile }); else logger.info("Creating original preview of {} at {}", new String[] { resource.getIdentifier(), pathToImageFile }); // Get hold of the content ResourceContent resourceContents = resource.getContent(language); // Get the mime type final String mimetype = resourceContents.getMimetype(); final String format = mimetype.substring(mimetype.indexOf("/") + 1); boolean scalingFailed = false; InputStream is = null; FileOutputStream fos = null; try { is = contentRepository.getContent(resourceURI, language); // Remove the original image FileUtils.deleteQuietly(previewFile); // Create a work file File imageDirectory = previewFile.getParentFile(); String workFileName = "." + UUID.randomUUID() + "-" + previewFile.getName(); FileUtils.forceMkdir(imageDirectory); File workImageFile = new File(imageDirectory, workFileName); // Create the scaled image fos = new FileOutputStream(workImageFile); logger.debug("Creating scaled image '{}' at {}", resource, previewFile); previewGenerator.createPreview(resource, environment, language, style, format, is, fos); // Move the work image in place try { FileUtils.moveFile(workImageFile, previewFile); } catch (IOException e) { logger.warn("Concurrent creation of preview {} resolved by copy instead of rename", previewFile.getAbsolutePath()); FileUtils.copyFile(workImageFile, previewFile); FileUtils.deleteQuietly(workImageFile); } finally { previewFile.setLastModified(Math.max(new Date().getTime(), resourceLastModified)); } // Make sure preview generation was successful if (!previewFile.isFile()) { logger.warn("The file at {} is not a regular file", pathToImageFile); scalingFailed = true; } else if (previewFile.length() == 0) { logger.warn("The scaled file at {} has zero length", pathToImageFile); scalingFailed = true; } } catch (ContentRepositoryException e) { logger.error("Unable to load image {}: {}", new Object[] { resourceURI, e.getMessage(), e }); scalingFailed = true; DispatchUtils.sendInternalError(request, response); } catch (IOException e) { logger.error("Error sending image '{}' to the client: {}", resourceURI, e.getMessage()); scalingFailed = true; DispatchUtils.sendInternalError(request, response); } catch (Throwable t) { logger.error("Error creating scaled image '{}': {}", resourceURI, t.getMessage()); scalingFailed = true; DispatchUtils.sendInternalError(request, response); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); try { if (scalingFailed && previewFile != null) { logger.info("Cleaning up after failed scaling of {}", pathToImageFile); File f = previewFile; FileUtils.deleteQuietly(previewFile); f = previewFile.getParentFile(); while (f != null && f.isDirectory() && (f.listFiles() == null || f.listFiles().length == 0)) { FileUtils.deleteQuietly(f); f = f.getParentFile(); } } } catch (Throwable t) { logger.warn("Error cleaning up after failed scaling of {}", pathToImageFile); } synchronized (previews) { previews.remove(pathToImageFile); previews.notifyAll(); } } } // Make sure whoever was in charge of creating the preview, was // successful boolean scaledImageExists = previewFile.isFile(); boolean scaledImageIsOutdated = previewFile.lastModified() < resourceLastModified; if (!scaledImageExists || scaledImageIsOutdated) { logger.debug("Apparently, preview rendering for {} failed", previewFile.getAbsolutePath()); DispatchUtils.sendServiceUnavailable(request, response); return null; } else { try { return new FileInputStream(previewFile); } catch (Throwable t) { logger.error("Error reading content from preview at {}: {}", previewFile.getAbsolutePath(), t.getMessage()); DispatchUtils.sendServiceUnavailable(request, response); return null; } } }
From source file:edu.mit.mobile.android.locast.sync.MediaSync.java
/** * Checks the local file system and checks to see if the given media resource has been * downloaded successfully already. If not, it will download it from the server and store it in * the filesystem. This uses the last-modified header and file length to determine if a media * resource is up to date.//from w w w . j a va 2s . co m * * This method blocks for the course of the download, but shows a progress notification. * * @param pubUri * the http:// uri of the public resource * @param saveFile * the file that the resource will be saved to * @param castMediaUri * the content:// uri of the cast * @return true if anything has changed. False if this function has determined it doesn't need * to do anything. * @throws SyncException */ public boolean downloadMediaFile(String pubUri, File saveFile, Uri castMediaUri) throws SyncException { final NetworkClient nc = NetworkClient.getInstance(this, Authenticator.getFirstAccount(this)); try { boolean dirty = true; // String contentType = null; if (saveFile.exists()) { final HttpResponse headRes = nc.head(pubUri); final long serverLength = Long.valueOf(headRes.getFirstHeader("Content-Length").getValue()); // XXX should really be checking the e-tag too, but this will be // fine for our application. final Header remoteLastModifiedHeader = headRes.getFirstHeader("last-modified"); long remoteLastModified = 0; if (remoteLastModifiedHeader != null) { remoteLastModified = DateUtils.parseDate(remoteLastModifiedHeader.getValue()).getTime(); } final HttpEntity entity = headRes.getEntity(); if (entity != null) { entity.consumeContent(); } if (saveFile.length() == serverLength && saveFile.lastModified() >= remoteLastModified) { if (DEBUG) { Log.i(TAG, "Local copy of cast " + saveFile + " seems to be the same as the one on the server. Not re-downloading."); } dirty = false; } // fall through and re-download, as we have a different size // file locally. } if (dirty) { final Uri castUri = CastMedia.getCast(castMediaUri); String castTitle = Cast.getTitle(this, castUri); if (castTitle == null) { castTitle = "untitled"; } final HttpResponse res = nc.get(pubUri); final HttpEntity ent = res.getEntity(); final ProgressNotification notification = new ProgressNotification(this, getString(R.string.sync_downloading_cast, castTitle), ProgressNotification.TYPE_DOWNLOAD, PendingIntent.getActivity(this, 0, new Intent(Intent.ACTION_VIEW, castUri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0), false); final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); final NotificationProgressListener npl = new NotificationProgressListener(nm, notification, ent.getContentLength(), 0); final InputStreamWatcher is = new InputStreamWatcher(ent.getContent(), npl); try { if (DEBUG) { Log.d(TAG, "Downloading " + pubUri + " and saving it in " + saveFile.getAbsolutePath()); } final FileOutputStream fos = new FileOutputStream(saveFile); StreamUtils.inputStreamToOutputStream(is, fos); fos.close(); // set the file's last modified to match the remote. // We can check this later to see if everything is up to // date. final Header lastModified = res.getFirstHeader("last-modified"); if (lastModified != null) { saveFile.setLastModified(DateUtils.parseDate(lastModified.getValue()).getTime()); } // contentType = ent.getContentType().getValue(); } finally { npl.done(); ent.consumeContent(); is.close(); } // XXX avoid this to prevent adding to local collection // final String filePath = saveFile.getAbsolutePath(); // scanMediaItem(castMediaUri, filePath, contentType); return true; } } catch (final Exception e) { final SyncException se = new SyncException("Error downloading content item."); se.initCause(e); throw se; } return false; }
From source file:org.mnsoft.pdfocr.Wrapper.java
/** * Run the Wrapper.//from w w w . jav a 2 s .c o m * * @throws IOException * @throws InterruptedException * @throws DocumentException */ @SuppressWarnings("rawtypes") public void run() throws IOException, InterruptedException, DocumentException { RecursiveFileListIterator it = new RecursiveFileListIterator(new File(wd), new FileFilter(".pdf")); while (it.hasNext()) { final File originalFile = it.next(); final String originalFilePath = originalFile.getAbsolutePath(); /* * Open the reader on the original File */ PdfReader readerOnOriginalFile; try { readerOnOriginalFile = new PdfReader(originalFilePath); } catch (Exception e) { log.error("! ERROR: " + e.getMessage() + " File: " + originalFilePath); continue; } /* * Get the document information */ Map info = readerOnOriginalFile.getInfo(); /* * Get the document creator. If the document * has already been worked on, continue with * the next document. */ String doc_creator = (String) info.get("Creator"); if (this.OCR_CREATOR.equals(doc_creator)) { log.debug( "+ INFO: File " + originalFilePath + " had already been run trough OCR engine. Skipping."); continue; } /* * Get the document time stamp so that we can set it later. */ final Date doc_timestamp = new Date(originalFile.lastModified()); /* * Get the number of pages in the original file */ int nOri = readerOnOriginalFile.getNumberOfPages(); log.debug("+ Working on: " + originalFilePath + " (" + nOri + " pages)."); final StringBuffer sb = new StringBuffer(); sb.append(originalFilePath + " ... "); /* * Get the remaining meta data */ String doc_title = ((String) info.get("Title") == null) ? "" : (String) info.get("Title"); String doc_subject = ((String) info.get("Subject") == null) ? "" : (String) info.get("Subject"); String doc_keywords = ((String) info.get("Keywords") == null) ? "" : (String) info.get("Keywords"); String doc_author = ((String) info.get("Author") == null) ? "" : (String) info.get("Author"); readerOnOriginalFile.close(); /* * Set the creator to our marker */ doc_creator = this.OCR_CREATOR; /* * Run the OCR Engine */ File outputFileFromOCR = null; try { outputFileFromOCR = ocr(originalFile); } catch (Exception e) { log.error("! ERROR: " + e.getMessage()); continue; } /* * Check for the result of the OCR Engine */ if ((outputFileFromOCR == null) || !outputFileFromOCR.exists()) { continue; } log.debug("+ " + outputFileFromOCR.getAbsolutePath() + " has come out of the OCR engine."); /* * Create final output */ /* * Create a temporary file and copy the source * file to it, to avoid UTF-8 encoding problems * on the filename confusing the OCR engine */ final File temp = File.createTempFile("ocr", ".pdf", new File(this.TMP_DIR)); temp.deleteOnExit(); mergePDFs(originalFile, outputFileFromOCR, temp, doc_title, doc_subject, doc_keywords, doc_author, doc_creator); FileUtils.deleteQuietly(originalFile); FileUtils.moveFile(temp, new File(originalFilePath)); /* * Set the file access time */ if ("true".equals(getAttribute("KEEPTS"))) { if (originalFile.exists()) { originalFile.setLastModified(doc_timestamp.getTime() + 1000); } } /* * Finally, remove the temporary document */ FileUtils.deleteQuietly(temp); FileUtils.deleteQuietly(outputFileFromOCR); } }
From source file:edu.mit.mobile.android.net.DownloadLoader.java
@Override public Uri loadInBackground() { boolean alreadyHasDownload = false; if (!outdir.exists() && !outdir.mkdirs()) { mException = new IOException("could not mkdirs: " + outdir.getAbsolutePath()); return null; }//from w w w .j ava 2 s. c o m final String fname = mUrl.substring(mUrl.lastIndexOf('/')); final File outfile = new File(outdir, fname); alreadyHasDownload = outfile.exists() && outfile.length() > MINIMUM_REASONABLE_VIDEO_SIZE; final long lastModified = outfile.exists() ? outfile.lastModified() : 0; try { final NetworkInfo netInfo = mCm.getActiveNetworkInfo(); if (netInfo == null || !netInfo.isConnected()) { // no connection, but there's already a file. Hopefully it works! if (alreadyHasDownload) { return Uri.fromFile(outfile); } else { mException = new IOException(getContext().getString(R.string.err_no_data_connection)); return null; } } HttpURLConnection hc = (HttpURLConnection) new URL(mUrl).openConnection(); hc.setInstanceFollowRedirects(true); if (lastModified != 0) { hc.setIfModifiedSince(lastModified); } int resp = hc.getResponseCode(); if (resp >= 300 && resp < 400) { final String redirectUrl = hc.getURL().toExternalForm(); if (BuildConfig.DEBUG) { Log.d(TAG, "following redirect to " + redirectUrl); } hc = (HttpURLConnection) new URL(redirectUrl).openConnection(); if (lastModified != 0) { hc.setIfModifiedSince(lastModified); } resp = hc.getResponseCode(); } if (resp != HttpStatus.SC_OK && resp != HttpStatus.SC_NOT_MODIFIED) { Log.e(TAG, "got a non-200 response from server"); mException = new NetworkProtocolException("Received " + resp + " response from server"); return null; } if (resp == HttpStatus.SC_NOT_MODIFIED) { if (Constants.DEBUG) { Log.d(TAG, "got NOT MODIFIED"); } // verify the integrity of the file if (alreadyHasDownload) { if (Constants.DEBUG) { Log.d(TAG, fname + " has not been modified since it was downloaded last"); } return Uri.fromFile(outfile); } else { // re-request without the if-modified header. This shouldn't happen. hc = (HttpURLConnection) new URL(mUrl).openConnection(); final int responseCode = hc.getResponseCode(); if (responseCode != HttpStatus.SC_OK) { Log.e(TAG, "got a non-200 response from server"); mException = new NetworkProtocolException( "Received " + responseCode + " response from server"); return null; } } } final int contentLength = hc.getContentLength(); if (contentLength == 0) { Log.e(TAG, "got an empty response from server"); mException = new IOException("Received an empty response from server."); return null; } else if (contentLength < MINIMUM_REASONABLE_VIDEO_SIZE) { // this is probably not a // video Log.e(TAG, "got a very small response from server of length " + hc.getContentLength()); mException = new IOException("Received an unusually-small response from server."); return null; } boolean downloadSucceeded = false; try { final BufferedInputStream bis = new BufferedInputStream(hc.getInputStream()); final FileOutputStream fos = new FileOutputStream(outfile); if (Constants.DEBUG) { Log.d(TAG, "downloading..."); } StreamUtils.inputStreamToOutputStream(bis, fos); fos.close(); // store the server's last modified date in the filesystem outfile.setLastModified(hc.getLastModified()); downloadSucceeded = true; if (Constants.DEBUG) { Log.d(TAG, "done! Saved to " + outfile); } return Uri.fromFile(outfile); } finally { hc.disconnect(); // cleanup if this is the first attempt to download if (!alreadyHasDownload && !downloadSucceeded) { outfile.delete(); } } } catch (final IOException e) { Log.e(TAG, "error downloading file", e); mException = e; return null; } }
From source file:com.krawler.portal.tools.ServiceBuilder.java
public static void writeFile(File file, String content, String author, Map<String, Object> jalopySettings) throws IOException { String packagePath = "com/krawler/esp/hibernate/impl";//_getPackagePath(file); String className = file.getName(); className = className.substring(0, className.length() - 5); content = SourceFormatter.stripImports(content, packagePath, className); File tempFile = new File("ServiceBuilder.temp"); Writer output = new BufferedWriter(new FileWriter(tempFile)); output.write(content);/*from w w w .ja v a2 s. c om*/ output.close(); StringBuffer sb = new StringBuffer(); Jalopy jalopy = new Jalopy(); jalopy.setFileFormat(FileFormat.UNIX); jalopy.setInput(tempFile); jalopy.setOutput(sb); // try { // Jalopy.setConvention("../tools/jalopy.xml"); // } // catch (FileNotFoundException fnne) { // System.out.print(fnne.getMessage()); // } // try { // Jalopy.setConvention("../../misc/jalopy.xml"); // } // catch (FileNotFoundException fnne) { // System.out.print(fnne.getMessage()); // } if (jalopySettings == null) { jalopySettings = new HashMap<String, Object>(); } Environment env = Environment.getInstance(); // Author author = GetterUtil.getString((String) jalopySettings.get("author"), author); env.set("author", author); // File name env.set("fileName", file.getName()); Convention convention = Convention.getInstance(); String classMask = "/**\n" + " * <a href=\"$fileName$.html\"><b><i>View Source</i></b></a>\n" + " *\n" + " * @author $author$\n" + " *\n" + "*/"; convention.put(ConventionKeys.COMMENT_JAVADOC_TEMPLATE_CLASS, env.interpolate(classMask)); convention.put(ConventionKeys.COMMENT_JAVADOC_TEMPLATE_INTERFACE, env.interpolate(classMask)); jalopy.format(); String newContent = sb.toString(); /* // Remove blank lines after try { newContent = StringUtil.replace(newContent, "try {\n\n", "try {\n"); // Remove blank lines after ) { newContent = StringUtil.replace(newContent, ") {\n\n", ") {\n"); // Remove blank lines empty braces { } newContent = StringUtil.replace(newContent, "\n\n\t}", "\n\t}"); // Add space to last } newContent = newContent.substring(0, newContent.length() - 2) + "\n\n}"; */ // Write file if and only if the file has changed String oldContent = null; if (file.exists()) { // Read file Reader reader = new BufferedReader(new FileReader(file)); CharBuffer cbuf = new CharBuffer(reader); oldContent = cbuf.toString(); reader.close(); // Keep old version number int x = oldContent.indexOf("@version $Revision:"); if (x != -1) { int y = oldContent.indexOf("$", x); y = oldContent.indexOf("$", y + 1); String oldVersion = oldContent.substring(x, y + 1); newContent = com.krawler.portal.util.StringUtil.replace(newContent, "@version $Rev: $", oldVersion); } } else { // newContent = com.krawler.portal.util.StringUtil.replace( // newContent, "@version $Rev: $", "@version $Revision: 1.183 $"); file.createNewFile(); } if (oldContent == null || !oldContent.equals(newContent)) { output = new BufferedWriter(new FileWriter(file)); output.write(content); output.close(); // FileUtil.write(file, newContent); System.out.println("Writing " + file); // Workaround for bug with XJavaDoc file.setLastModified(System.currentTimeMillis() - (Time.SECOND * 5)); } tempFile.deleteOnExit(); }
From source file:nl.strohalm.cyclos.http.lifecycle.CustomizedFileInitialization.java
public void init(final ServletContext context) { // First, clear the customized css files to ensure proper migration from previous versions when css files were not customized final File customizedStylesDir = new File( context.getRealPath(CustomizationHelper.customizedPathFor(context, CustomizedFile.Type.STYLE))); for (final File css : customizedStylesDir.listFiles((FilenameFilter) new SuffixFileFilter(".css"))) { css.delete();// w w w. ja va2s .c om } final LocalSettings localSettings = SettingsHelper.getLocalSettings(context); final CustomizedFileQuery query = new CustomizedFileQuery(); query.fetch(CustomizedFile.Relationships.GROUP); query.setAll(true); final List<CustomizedFile> files = customizedFileService.search(query); for (final CustomizedFile customizedFile : files) { final CustomizedFile.Type type = customizedFile.getType(); final String name = customizedFile.getName(); final File physicalFile = CustomizationHelper.customizedFileOf(context, customizedFile); final File originalFile = CustomizationHelper.originalFileOf(context, type, name); try { // No conflicts are checked for style sheet files if (type != CustomizedFile.Type.STYLE) { final boolean wasConflict = customizedFile.isConflict(); // Check if the file contents has changed since the customization String originalFileContents = null; if (originalFile.exists()) { originalFileContents = FileUtils.readFileToString(originalFile); if (originalFileContents.length() == 0) { originalFileContents = null; } } // Check if the file is now on conflict (or the new contents has changed) boolean contentsChanged; boolean newContentsChanged; if (type == CustomizedFile.Type.APPLICATION_PAGE) { contentsChanged = !StringUtils.trimToEmpty(originalFileContents) .equals(StringUtils.trimToEmpty(customizedFile.getOriginalContents())) && !StringUtils.trimToEmpty(originalFileContents) .equals(StringUtils.trimToEmpty(customizedFile.getContents())); newContentsChanged = contentsChanged && !StringUtils.trimToEmpty(originalFileContents) .equals(StringUtils.trimToEmpty(customizedFile.getNewContents())); } else { contentsChanged = !StringUtils.trimToEmpty(originalFileContents) .equals(StringUtils.trimToEmpty(customizedFile.getOriginalContents())); newContentsChanged = !StringUtils.trimToEmpty(originalFileContents) .equals(StringUtils.trimToEmpty(customizedFile.getNewContents())); } if (!wasConflict && contentsChanged) { // Save the new contents, marking the file as conflicts customizedFile.setNewContents(originalFileContents); customizedFileService.save(customizedFile); // Generate an alert if the file is customized for the whole system if (customizedFile.getGroup() == null && customizedFile.getGroupFilter() == null) { SystemAlert.Alerts alertType = null; switch (type) { case APPLICATION_PAGE: alertType = SystemAlert.Alerts.NEW_VERSION_OF_APPLICATION_PAGE; break; case HELP: alertType = SystemAlert.Alerts.NEW_VERSION_OF_HELP_FILE; break; case STATIC_FILE: alertType = SystemAlert.Alerts.NEW_VERSION_OF_STATIC_FILE; break; } alertService.create(alertType, customizedFile.getName()); } } else if (wasConflict && newContentsChanged) { // The file has changed again. Update the new contents customizedFile.setNewContents(originalFileContents); customizedFileService.save(customizedFile); } } // Check if we must update an style file final long lastModified = customizedFile.getLastModified() == null ? System.currentTimeMillis() : customizedFile.getLastModified().getTimeInMillis(); if (!physicalFile.exists() || physicalFile.lastModified() != lastModified) { physicalFile.getParentFile().mkdirs(); FileUtils.writeStringToFile(physicalFile, customizedFile.getContents(), localSettings.getCharset()); physicalFile.setLastModified(lastModified); } } catch (final IOException e) { LOG.warn("Error handling customized file: " + physicalFile.getAbsolutePath(), e); } } // We must copy all non-customized style sheets to the customized dir, so there will be no problems for locating images final File originalDir = new File( context.getRealPath(CustomizationHelper.originalPathFor(context, CustomizedFile.Type.STYLE))); for (final File original : originalDir.listFiles()) { final File customized = new File(customizedStylesDir, original.getName()); if (!customized.exists()) { try { FileUtils.copyFile(original, customized); } catch (final IOException e) { LOG.warn("Error copying style sheet file: " + customized.getAbsolutePath(), e); } } } }
From source file:hd3gtv.mydmam.useraction.fileoperation.CopyMove.java
private void copyFile(File source_file, File destination_file) throws IOException { if (destination_file.exists()) { Log2Dump dump = new Log2Dump(); dump.add("source_file", source_file); dump.add("destination_file", destination_file); dump.add("delete_after_copy", delete_after_copy); if (fileexistspolicy == FileExistsPolicy.IGNORE) { Log2.log.debug("Destination file exists, ignore copy/move", dump); return; } else if (fileexistspolicy == FileExistsPolicy.OVERWRITE) { Log2.log.debug("Destination file exists, overwrite it", dump); FileUtils.forceDelete(destination_file); } else if (fileexistspolicy == FileExistsPolicy.RENAME) { // destination_file int cursor = 1; int dot_pos; StringBuilder sb;/*from w w w .j a v a 2s. c o m*/ while (destination_file.exists()) { sb = new StringBuilder(); sb.append(destination_file.getParent()); sb.append(File.separator); dot_pos = destination_file.getName().lastIndexOf("."); if (dot_pos > 0) { sb.append(destination_file.getName().substring(0, dot_pos)); sb.append(" ("); sb.append(cursor); sb.append(")"); sb.append( destination_file.getName().substring(dot_pos, destination_file.getName().length())); } else { sb.append(destination_file.getName()); sb.append(" ("); sb.append(cursor); sb.append(")"); } destination_file = new File(sb.toString()); cursor++; } dump.add("new destination file name", destination_file); Log2.log.debug("Destination file exists, change destionation name", dump); } } /** * Imported from org.apache.commons.io.FileUtils * Licensed to the Apache Software Foundation, * http://www.apache.org/licenses/LICENSE-2.0 */ FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(source_file); fos = new FileOutputStream(destination_file); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); if (progression != null) { actual_progress_value = (int) ((pos + progress_copy) / (1024 * 1024)); if (actual_progress_value > last_progress_value) { last_progress_value = actual_progress_value; progression.updateProgress(actual_progress_value, progress_size); } } } } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(input); IOUtils.closeQuietly(fis); } if (source_file.length() != destination_file.length()) { throw new IOException( "Failed to copy full contents from '" + source_file + "' to '" + destination_file + "'"); } if (destination_file.setExecutable(source_file.canExecute()) == false) { Log2.log.error("Can't set Executable status to dest file", new IOException(destination_file.getPath())); } if (destination_file.setLastModified(source_file.lastModified()) == false) { Log2.log.error("Can't set LastModified status to dest file", new IOException(destination_file.getPath())); } }
From source file:com.dragoniade.deviantart.favorites.FavoritesDownloader.java
private STATUS downloadFile(Deviation da, String downloadUrl, String filename, boolean reportError, YesNoAllDialog matureMoveDialog, YesNoAllDialog overwriteDialog, YesNoAllDialog overwriteNewerDialog, YesNoAllDialog deleteEmptyDialog) { AtomicBoolean download = new AtomicBoolean(true); File art = getFile(da, downloadUrl, filename, download, matureMoveDialog, overwriteDialog, overwriteNewerDialog, deleteEmptyDialog); if (art == null) { return null; }//from w ww.j av a2 s . c o m if (download.get()) { File parent = art.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { showMessageDialog(owner, "Unable to create '" + parent.getPath() + "'.", "Error", JOptionPane.ERROR_MESSAGE); return null; } } GetMethod method = new GetMethod(downloadUrl); try { int sc = -1; do { sc = client.executeMethod(method); requestCount++; if (sc != 200) { if (sc == 404 || sc == 403) { method.releaseConnection(); return STATUS.NOTFOUND; } else { LoggableException ex = new LoggableException(method.getResponseBodyAsString()); Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ex); int res = showConfirmDialog(owner, "An error has occured when contacting deviantART : error " + sc + ". Try again?", "Continue?", JOptionPane.YES_NO_CANCEL_OPTION); if (res == JOptionPane.NO_OPTION) { String text = "<br/><a style=\"color:red;\" href=\"" + da.getUrl() + "\">" + downloadUrl + " has an error" + "</a>"; setPaneText(text); method.releaseConnection(); progress.incremTotal(); return STATUS.SKIP; } if (res == JOptionPane.CANCEL_OPTION) { return null; } try { Thread.sleep(500); } catch (InterruptedException e) { } } } } while (sc != 200); int length = (int) method.getResponseContentLength(); int copied = 0; progress.setUnitMax(length); InputStream is = method.getResponseBodyAsStream(); File tmpFile = new File(art.getParentFile(), art.getName() + ".tmp"); FileOutputStream fos = new FileOutputStream(tmpFile, false); byte[] buffer = new byte[16184]; int read = -1; while ((read = is.read(buffer)) > 0) { fos.write(buffer, 0, read); copied += read; progress.setUnitValue(copied); if (progress.isCancelled()) { is.close(); method.releaseConnection(); tmpFile.delete(); return null; } } fos.close(); method.releaseConnection(); if (art.exists()) { if (!art.delete()) { showMessageDialog(owner, "Unable to delete '" + art.getPath() + "'.", "Error", JOptionPane.ERROR_MESSAGE); return null; } } if (!tmpFile.renameTo(art)) { showMessageDialog(owner, "Unable to rename '" + tmpFile.getPath() + "' to '" + art.getPath() + "'.", "Error", JOptionPane.ERROR_MESSAGE); return null; } art.setLastModified(da.getTimestamp().getTime()); return STATUS.DOWNLOADED; } catch (HttpException e) { showMessageDialog(owner, "Error contacting deviantART: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return null; } catch (IOException e) { showMessageDialog(owner, "Error contacting deviantART: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return null; } } else { progress.setText("Skipping file '" + filename + "' from " + da.getArtist()); return STATUS.SKIP; } }
From source file:nl.strohalm.cyclos.initializations.CustomizedFileInitialization.java
@Override public void initialize() { // First, clear the customized css files to ensure proper migration from previous versions when css files were not customized final File customizedStylesDir = new File( servletContext.getRealPath(customizationHelper.customizedPathFor(CustomizedFile.Type.STYLE))); for (final File css : customizedStylesDir.listFiles((FilenameFilter) new SuffixFileFilter(".css"))) { css.delete();/* w ww. java2 s . c o m*/ } final LocalSettings localSettings = settingsServiceLocal.getLocalSettings(); final CustomizedFileQuery query = new CustomizedFileQuery(); query.fetch(CustomizedFile.Relationships.GROUP); query.setAll(true); final List<CustomizedFile> files = customizedFileService.search(query); for (final CustomizedFile customizedFile : files) { final CustomizedFile.Type type = customizedFile.getType(); final String name = customizedFile.getName(); final File physicalFile = customizationHelper.customizedFileOf(customizedFile); final File originalFile = customizationHelper.originalFileOf(type, name); if (!originalFile.exists()) { // Probably an old file which is no longer relevant. Remove the customized file from DB customizedFileService.stopCustomizing(customizedFile); continue; } try { // No conflicts are checked for style sheet files if (type != CustomizedFile.Type.STYLE) { final boolean wasConflict = customizedFile.isConflict(); // Check if the file contents has changed since the customization String originalFileContents = null; if (originalFile.exists()) { originalFileContents = FileUtils.readFileToString(originalFile); if (originalFileContents.length() == 0) { originalFileContents = null; } } // Check if the file is now on conflict (or the new contents has changed) boolean contentsChanged; boolean newContentsChanged; if (type == CustomizedFile.Type.APPLICATION_PAGE) { contentsChanged = !StringUtils.trimToEmpty(originalFileContents) .equals(StringUtils.trimToEmpty(customizedFile.getOriginalContents())) && !StringUtils.trimToEmpty(originalFileContents) .equals(StringUtils.trimToEmpty(customizedFile.getContents())); newContentsChanged = contentsChanged && !StringUtils.trimToEmpty(originalFileContents) .equals(StringUtils.trimToEmpty(customizedFile.getNewContents())); } else { contentsChanged = !StringUtils.trimToEmpty(originalFileContents) .equals(StringUtils.trimToEmpty(customizedFile.getOriginalContents())); newContentsChanged = !StringUtils.trimToEmpty(originalFileContents) .equals(StringUtils.trimToEmpty(customizedFile.getNewContents())); } if (!wasConflict && contentsChanged) { // Save the new contents, marking the file as conflicts customizedFile.setNewContents(originalFileContents); customizedFileService.save(customizedFile); // Generate an alert if the file is customized for the whole system if (customizedFile.getGroup() == null && customizedFile.getGroupFilter() == null) { SystemAlert.Alerts alertType = null; switch (type) { case APPLICATION_PAGE: alertType = SystemAlert.Alerts.NEW_VERSION_OF_APPLICATION_PAGE; break; case HELP: alertType = SystemAlert.Alerts.NEW_VERSION_OF_HELP_FILE; break; case STATIC_FILE: alertType = SystemAlert.Alerts.NEW_VERSION_OF_STATIC_FILE; break; } customizedFileService.notifyNewVersion(alertType, customizedFile); } } else if (wasConflict && newContentsChanged) { // The file has changed again. Update the new contents customizedFile.setNewContents(originalFileContents); customizedFileService.save(customizedFile); } } // Check if we must update an style file final long lastModified = customizedFile.getLastModified() == null ? System.currentTimeMillis() : customizedFile.getLastModified().getTimeInMillis(); if (!physicalFile.exists() || physicalFile.lastModified() != lastModified) { physicalFile.getParentFile().mkdirs(); FileUtils.writeStringToFile(physicalFile, customizedFile.getContents(), localSettings.getCharset()); physicalFile.setLastModified(lastModified); } } catch (final IOException e) { LOG.warn("Error handling customized file: " + physicalFile.getAbsolutePath(), e); } } // We must copy all non-customized style sheets to the customized dir, so there will be no problems for locating images String virtualPath = customizationHelper.originalPathFor(CustomizedFile.Type.STYLE); final File originalDir = new File(servletContext.getRealPath(virtualPath)); if (originalDir == null || originalDir.listFiles() == null) { // this happens in case something is wrong with the directory, and servletContext.getRealPath returns null LOG.error( "Error copying any style sheet file due to path problems. Images may not be locatable now. Unresolvable path: " + virtualPath); return; } for (final File original : originalDir.listFiles()) { final File customized = new File(customizedStylesDir, original.getName()); if (!customized.exists()) { try { FileUtils.copyFile(original, customized); } catch (final IOException e) { LOG.warn("Error copying style sheet file: " + customized.getAbsolutePath(), e); } } } }
From source file:org.rhq.enterprise.server.core.plugin.AgentPluginScanner.java
/** * This method scans the database for any new or updated agent plugins and make sure this server * has a plugin file on the filesystem for each of those new/updated agent plugins. * * @return a list of files that appear to be new or updated and should be deployed *///from w ww. ja v a2 s. c om List<File> agentPluginScanDatabase() throws Exception { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; // these are plugins (name/path/md5/mtime) that have changed in the DB but are missing from the file system List<Plugin> updatedPlugins = new ArrayList<Plugin>(); // the same list as above, only they are the files that are written to the filesystem and no longer missing List<File> updatedFiles = new ArrayList<File>(); try { DataSource ds = LookupUtil.getDataSource(); conn = ds.getConnection(); // get all the plugins ps = conn.prepareStatement("SELECT NAME, PATH, MD5, MTIME, VERSION FROM " + Plugin.TABLE_NAME + " WHERE DEPLOYMENT = 'AGENT' AND ENABLED=?"); setEnabledFlag(conn, ps, 1, true); rs = ps.executeQuery(); while (rs.next()) { String name = rs.getString(1); String path = rs.getString(2); String md5 = rs.getString(3); long mtime = rs.getLong(4); String version = rs.getString(5); // let's see if we have this logical plugin on the filesystem (it may or may not be under the same filename) File expectedFile = new File(this.agentPluginDeployer.getPluginDir(), path); File currentFile = null; // will be non-null if we find that we have this plugin on the filesystem already Plugin cachedPluginOnFilesystem = this.agentPluginsOnFilesystem.get(expectedFile); if (cachedPluginOnFilesystem != null) { currentFile = expectedFile; // we have it where we are expected to have it if (!cachedPluginOnFilesystem.getName().equals(name)) { // I have no idea when or if this would ever happen, but at least log it so we'll see it if it does happen log.warn("For some reason, the plugin file [" + expectedFile + "] is plugin [" + cachedPluginOnFilesystem.getName() + "] but the database says it should be [" + name + "]"); } else { log.debug("File system and database agree on a plugin location for [" + expectedFile + "]"); } } else { // the plugin might still be on the file system but under a different filename, see if we can find it for (Map.Entry<File, Plugin> cachePluginEntry : this.agentPluginsOnFilesystem.entrySet()) { if (cachePluginEntry.getValue().getName().equals(name)) { currentFile = cachePluginEntry.getKey(); cachedPluginOnFilesystem = cachePluginEntry.getValue(); log.info("Filesystem has a plugin [" + name + "] at the file [" + currentFile + "] which is different than where the DB thinks it should be [" + expectedFile + "]"); break; // we found it, no need to continue the loop } } } if (cachedPluginOnFilesystem != null && currentFile != null && currentFile.exists()) { Plugin dbPlugin = new Plugin(name, path); dbPlugin.setMd5(md5); dbPlugin.setVersion(version); dbPlugin.setMtime(mtime); Plugin obsoletePlugin = AgentPluginDescriptorUtil.determineObsoletePlugin(dbPlugin, cachedPluginOnFilesystem); if (obsoletePlugin == cachedPluginOnFilesystem) { // yes use == for reference equality! StringBuilder logMsg = new StringBuilder(); logMsg.append("Found agent plugin [").append(name); logMsg.append("] in the DB that is newer than the one on the filesystem: "); logMsg.append("DB path=[").append(path); logMsg.append("]; file path=[").append(currentFile.getName()); logMsg.append("]; DB MD5=[").append(md5); logMsg.append("]; file MD5=[").append(cachedPluginOnFilesystem.getMd5()); logMsg.append("]; DB version=[").append(version); logMsg.append("]; file version=[").append(cachedPluginOnFilesystem.getVersion()); logMsg.append("]; DB timestamp=[").append(new Date(mtime)); logMsg.append("]; file timestamp=[").append(new Date(cachedPluginOnFilesystem.getMtime())); logMsg.append("]"); log.info(logMsg.toString()); updatedPlugins.add(dbPlugin); if (currentFile.delete()) { log.info("Deleted the obsolete agent plugin file to be updated: " + currentFile); this.agentPluginsOnFilesystem.remove(currentFile); } else { log.warn("Failed to delete the obsolete (to-be-updated) agent plugin file: " + currentFile); } currentFile = null; } else if (obsoletePlugin == null) { // the db is up-to-date, but update the cache so we don't check MD5 or parse the descriptor again currentFile.setLastModified(mtime); cachedPluginOnFilesystem.setMtime(mtime); cachedPluginOnFilesystem.setVersion(version); cachedPluginOnFilesystem.setMd5(md5); } else { String message = "It appears the agent plugin [" + dbPlugin + "] in the database may be obsolete. If so, it will be updated soon by the version on the filesystem [" + currentFile + "]."; if (currentFile.getAbsolutePath().equals(expectedFile.getAbsolutePath())) { if (log.isDebugEnabled()) { log.debug(message); } } else { //inform on the info level so that it's clear from the logs that the new file //is going to be used. log.info(message); } } } else { log.info("Found agent plugin in the DB that we do not yet have: " + name); Plugin plugin = new Plugin(name, path, md5); plugin.setMtime(mtime); plugin.setVersion(version); updatedPlugins.add(plugin); this.agentPluginsOnFilesystem.remove(expectedFile); // paranoia, make sure the cache doesn't have this } } JDBCUtil.safeClose(ps, rs); // write all our updated plugins to the file system if (!updatedPlugins.isEmpty()) { ps = conn.prepareStatement("SELECT CONTENT FROM " + Plugin.TABLE_NAME + " WHERE DEPLOYMENT = 'AGENT' AND NAME = ? AND ENABLED = ?"); for (Plugin plugin : updatedPlugins) { File file = new File(this.agentPluginDeployer.getPluginDir(), plugin.getPath()); ps.setString(1, plugin.getName()); setEnabledFlag(conn, ps, 2, true); rs = ps.executeQuery(); rs.next(); InputStream content = rs.getBinaryStream(1); StreamUtil.copy(content, new FileOutputStream(file)); rs.close(); file.setLastModified(plugin.getMtime()); // so our file matches the database mtime updatedFiles.add(file); } } } finally { JDBCUtil.safeClose(conn, ps, rs); } return updatedFiles; }