List of usage examples for org.apache.commons.fileupload FileItem delete
void delete();
From source file:org.ow2.proactive_grid_cloud_portal.rm.server.nodesource.serialization.export.ExportToFileServlet.java
private void downloadJsonFile(HttpServletRequest request, HttpServletResponse response) { try {//from ww w . j av a 2s .c o m response.setContentType("application/json"); Map<String, String> exportParameters = new HashMap<>(); for (FileItem requestItem : new ServletRequestTransformer().getFormItems(request)) { if (requestItem.isFormField()) { String name = requestItem.getFieldName(); String value = requestItem.getString(); if (name.equalsIgnoreCase(FILE_CONTENT_PARAM)) { exportParameters.put(FILE_CONTENT_PARAM, value); } else if (name.equalsIgnoreCase(FILE_SUFFIX_PARAM)) { exportParameters.put(FILE_SUFFIX_PARAM, value); } else if (name.equalsIgnoreCase(NODE_SOURCE_NAME_PARAM)) { exportParameters.put(NODE_SOURCE_NAME_PARAM, value); } } requestItem.delete(); } response.setHeader("Content-disposition", "attachment; filename=" + exportParameters.get(NODE_SOURCE_NAME_PARAM) + exportParameters.get(FILE_SUFFIX_PARAM)); response.setHeader("Location", exportParameters.get(NODE_SOURCE_NAME_PARAM) + exportParameters.get(FILE_SUFFIX_PARAM)); response.getWriter().write(exportParameters.get(FILE_CONTENT_PARAM)); } catch (Exception e) { try { LOGGER.warn("Export node source failed", e); response.getWriter().write(e.getMessage()); } catch (IOException ioe) { LOGGER.warn("Failed to return node source export error to client", ioe); } } }
From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.ExportNodeSourceToCatalogServlet.java
private CatalogObjectAction buildCatalogObjetAction(HttpServletRequest request) throws Exception { CatalogObjectAction catalogObjectAction = new CatalogObjectAction(); for (FileItem formItem : new ServletRequestTransformer().getFormItems(request)) { if (formItem.isFormField()) { String fieldValue = formItem.getString(); switch (formItem.getFieldName()) { case SESSION_ID_PARAM: catalogObjectAction.setSessionId(fieldValue); break; case BUCKET_NAME_PARAM: catalogObjectAction.setBucketName(fieldValue); break; case NAME_PARAM: catalogObjectAction.setNodeSourceName(fieldValue); break; case FILE_CONTENT_PARAM: File nodeSourceJsonFile = File.createTempFile("node-source-configuration", ".json"); try (PrintWriter writer = new PrintWriter(nodeSourceJsonFile)) { writer.write(fieldValue); }//from w ww .j a va 2 s . c o m formItem.write(nodeSourceJsonFile); catalogObjectAction.setNodeSourceJsonFile(nodeSourceJsonFile); break; case KIND_PARAM: catalogObjectAction.setKind(fieldValue); break; case COMMIT_MESSAGE_PARAM: catalogObjectAction.setCommitMessage(fieldValue); break; case OBJECT_CONTENT_TYPE_PARAM: catalogObjectAction.setObjectContentType(fieldValue); break; case REVISED_PARAM: catalogObjectAction.setRevised(Boolean.parseBoolean(fieldValue)); break; default: } } formItem.delete(); } return catalogObjectAction; }
From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.ExportNodeSourceToFileServlet.java
private String extractJsonStringFromRequest(HttpServletRequest request) throws FileUploadException { String jsonContent = ""; for (FileItem requestItem : new ServletRequestTransformer().getFormItems(request)) { if (requestItem.isFormField()) { String name = requestItem.getFieldName(); String value = requestItem.getString(); if (name.equalsIgnoreCase(MAIN_FORM_ITEM_NAME)) { jsonContent = value;//from w ww .j a va2 s . c om } } requestItem.delete(); } return jsonContent; }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.UploadServlet.java
private void upload(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); File job = null;//from w ww . j av a 2s.c om try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1000000); List<?> fileItems = upload.parseRequest(request); Iterator<?> i = fileItems.iterator(); String sessionId = null; boolean edit = false; /* * * edit=0, simply submit the job descriptor * edit=1, open the descriptor and return * it as a string */ while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { if (fi.getFieldName().equals("sessionId")) { sessionId = fi.getString(); } else if (fi.getFieldName().equals("edit")) { if (fi.getString().equals("1")) { edit = true; } else { edit = false; } } } else { job = File.createTempFile("job_upload", ".xml"); fi.write(job); } fi.delete(); } boolean isJar = isJarFile(job); if (!isJar) { // this _loosely_ checks that the file we got is an XML file try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(job); if (edit) { // don't go on with edition if there are no variables if (doc.getElementsByTagName("variables").getLength() < 1 || doc.getElementsByTagName("variable").getLength() < 1) { response.getWriter().write("This job descriptor contains no variable definition.<br>" + "Uncheck <strong>Edit variables</strong> or submit another descriptor."); return; } } } catch (Throwable e) { response.getWriter().write("Job descriptor must be valid XML<br>" + e.getMessage()); return; } } if (edit && !isJar) { String ret = IOUtils.toString(new FileInputStream(job), "UTF-8"); response.getWriter().write("{ \"jobEdit\" : \"" + Base64Utils.toBase64(ret.getBytes()) + "\" }"); } else { String responseS = ((SchedulerServiceImpl) Service.get()).submitXMLFile(sessionId, job); if (responseS == null || responseS.length() == 0) { response.getWriter().write("Job submission returned without a value!"); } else { response.getWriter().write(responseS); } } } catch (Exception e) { try { String msg = e.getMessage().replace("<", "<").replace(">", ">"); response.getWriter().write(msg); } catch (IOException ignored) { } } finally { if (job != null) job.delete(); } }
From source file:org.owasp.esapi.reference.DefaultHTTPUtilities.java
/** * {@inheritDoc}// ww w . j av a 2s . c o m */ public List<File> getFileUploads(HttpServletRequest request, File finalDir, List allowedExtensions) throws ValidationException { File tempDir = ESAPI.securityConfiguration().getUploadTempDirectory(); if (!tempDir.exists()) { if (!tempDir.mkdirs()) throw new ValidationUploadException("Upload failed", "Could not create temp directory: " + tempDir.getAbsolutePath()); } if (finalDir != null) { if (!finalDir.exists()) { if (!finalDir.mkdirs()) throw new ValidationUploadException("Upload failed", "Could not create final upload directory: " + finalDir.getAbsolutePath()); } } else { if (!ESAPI.securityConfiguration().getUploadDirectory().exists()) { if (!ESAPI.securityConfiguration().getUploadDirectory().mkdirs()) throw new ValidationUploadException("Upload failed", "Could not create final upload directory: " + ESAPI.securityConfiguration().getUploadDirectory().getAbsolutePath()); } finalDir = ESAPI.securityConfiguration().getUploadDirectory(); } List<File> newFiles = new ArrayList<File>(); try { final HttpSession session = request.getSession(false); if (!ServletFileUpload.isMultipartContent(request)) { throw new ValidationUploadException("Upload failed", "Not a multipart request"); } // this factory will store ALL files in the temp directory, // regardless of size DiskFileItemFactory factory = new DiskFileItemFactory(0, tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxBytes); // Create a progress listener ProgressListener progressListener = new ProgressListener() { private long megaBytes = -1; private long progress = 0; public void update(long pBytesRead, long pContentLength, int pItems) { if (pItems == 0) return; long mBytes = pBytesRead / 1000000; if (megaBytes == mBytes) return; megaBytes = mBytes; progress = (long) (((double) pBytesRead / (double) pContentLength) * 100); if (session != null) { session.setAttribute("progress", Long.toString(progress)); } // logger.logSuccess(Logger.SECURITY, " Item " + pItems + " (" + progress + "% of " + pContentLength + " bytes]"); } }; upload.setProgressListener(progressListener); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField() && item.getName() != null && !(item.getName().equals(""))) { String[] fparts = item.getName().split("[\\/\\\\]"); String filename = fparts[fparts.length - 1]; if (!ESAPI.validator().isValidFileName("upload", filename, allowedExtensions, false)) { throw new ValidationUploadException( "Upload only simple filenames with the following extensions " + allowedExtensions, "Upload failed isValidFileName check"); } logger.info(Logger.SECURITY_SUCCESS, "File upload requested: " + filename); File f = new File(finalDir, filename); if (f.exists()) { String[] parts = filename.split("\\/."); String extension = ""; if (parts.length > 1) { extension = parts[parts.length - 1]; } String filenm = filename.substring(0, filename.length() - extension.length()); f = File.createTempFile(filenm, "." + extension, finalDir); } item.write(f); newFiles.add(f); // delete temporary file item.delete(); logger.fatal(Logger.SECURITY_SUCCESS, "File successfully uploaded: " + f); if (session != null) { session.setAttribute("progress", Long.toString(0)); } } } } catch (Exception e) { if (e instanceof ValidationUploadException) { throw (ValidationException) e; } throw new ValidationUploadException("Upload failure", "Problem during upload:" + e.getMessage(), e); } return Collections.synchronizedList(newFiles); }
From source file:org.paxle.gui.impl.servlets.BundleView.java
private void handleFileUpload(final HttpServletRequest request, final Context context) throws Exception { final IServiceManager manager = (IServiceManager) context.get(IServiceManager.SERVICE_MANAGER); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // // Set factory constraints // factory.setSizeThreshold(yourMaxMemorySize); // factory.setRepository(yourTempDirectory); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // // Set overall request size constraint // upload.setSizeMax(yourMaxRequestSize); final boolean replace = request.getParameter(PARAM_REPLACE) != null; final BundleUpdater updater = createUpdater(context, replace); if (updater == null) return;/*ww w . j av a 2 s .c o m*/ // Parse the request @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) continue; try { if (!item.getFieldName().equals("bundleJar")) { String errorMsg = String.format("Unknown file-upload field '%s'.", item.getFieldName()); this.logger.warn(errorMsg); context.put("errorMsg", errorMsg); continue; } String fileName = item.getName(); if (fileName != null) { fileName = FilenameUtils.getName(fileName); } else { String errorMsg = String.format("Fileupload field '%s' has no valid filename.", item.getFieldName()); this.logger.warn(errorMsg); context.put("errorMsg", errorMsg); continue; } final InputStream content = item.getInputStream(); try { if (!updater.findAndRemoveOldBundle(fileName, content)) continue; } finally { try { content.close(); } catch (IOException e) { /* ignore */ } } // write the bundle to disk final File targetFile = updater.getSaveLocation(fileName, false); if (targetFile == null) continue; item.write(targetFile); // installing bundle final Bundle bundle = manager.installBundle(targetFile.toURI().toURL().toString()); // start bundle if original bundle's state was started if (updater.wasOldBundleStarted()) bundle.start(); } finally { // cleanup item.delete(); } } }
From source file:org.paxle.gui.impl.servlets.ConfigView.java
private Map<String, Dictionary<String, Object>> importConfig(HttpServletRequest request, Context context) throws Exception { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (!item.isFormField()) { if (!item.getFieldName().equals("configFile")) { String errorMsg = String.format("Unknown file-upload field '%s'.", item.getFieldName()); this.logger.warn(errorMsg); context.put("errorMsg", errorMsg); continue; }/*from w ww . j av a2s .co m*/ String fileName = item.getName(); if (fileName != null) { fileName = FilenameUtils.getName(fileName); } else { String errorMsg = String.format("Fileupload field '%s' has no valid filename.", item.getFieldName()); this.logger.warn(errorMsg); context.put("errorMsg", errorMsg); continue; } // write the bundle to disk File targetFile = File.createTempFile(fileName, ".tmp"); item.write(targetFile); // cleanup item.delete(); // read Settings IServiceManager manager = (IServiceManager) context.get(IServiceManager.SERVICE_MANAGER); IConfigurationIEPorter importer = (IConfigurationIEPorter) manager .getService(IConfigurationIEPorter.class.getName()); Map<String, Dictionary<String, Object>> propsMap = importer.importConfigurations(targetFile); return propsMap; } } return null; }
From source file:org.paxle.gui.impl.servlets.ConfigView.java
private void installStyle(IStyleManager styleManager, HttpServletRequest request, Context context) throws Exception { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (!item.isFormField()) { if (!item.getFieldName().equals("styleJar")) { String errorMsg = String.format("Unknown file-upload field '%s'.", item.getFieldName()); this.logger.warn(errorMsg); context.put("errorMsg", errorMsg); continue; }//from w ww . j av a 2 s . c om String fileName = item.getName(); if (fileName != null) { fileName = FilenameUtils.getName(fileName); } else { String errorMsg = String.format("Fileupload field '%s' has no valid filename.", item.getFieldName()); this.logger.warn(errorMsg); context.put("errorMsg", errorMsg); continue; } // write the bundle to disk File targetFile = new File(styleManager.getDataPath(), fileName); if (targetFile.exists()) { String errorMsg = String.format("Targetfile '%s' already exists.", targetFile.getCanonicalFile().toString()); this.logger.warn(errorMsg); context.put("errorMsg", errorMsg); continue; } item.write(targetFile); // cleanup item.delete(); } } }
From source file:org.paxle.gui.impl.servlets.ParserTestServlet.java
protected void fillContext(Context context, HttpServletRequest request) { String cmdLocation = null;//from w w w.j ava2 s . c om String cDocCharset = "UTF-8"; File cDocContentFile = null; String cDocContentType = null; boolean mimeTypeDetection = false; boolean charsetDetection = false; try { context.put(CONTEXT_MIMETYPE_DETECTOR, this.mimeTypeDetector); context.put(CONTEXT_CHARSET_DETECTOR, this.charsetDetector); if (ServletFileUpload.isMultipartContent(request)) { // Create a factory for disk-based file items final FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler final ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request @SuppressWarnings("unchecked") final List<FileItem> items = upload.parseRequest(request); // Process the uploaded items final Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { final FileItem item = iter.next(); final String fieldName = item.getFieldName(); if (item.isFormField()) { if (fieldName.equals(PARAM_COMMAND_URI)) { cmdLocation = item.getString(); context.put(PARAM_COMMAND_URI, cmdLocation); } else if (fieldName.equals(PARAM_ENABLE_MIMETYPE_DETECTION)) { mimeTypeDetection = true; } else if (fieldName.equals(PARAM_ENABLE_CHARSET_DETECTION)) { charsetDetection = true; } } else { try { // ignore unknown items if (!fieldName.equals(PARAM_CRAWLERDOC_NAME)) continue; // getting the content type cDocContentType = item.getContentType(); // getting the file-Name String fileName = item.getName(); if (fileName != null) { context.put(PARAM_CRAWLERDOC_NAME, fileName); fileName = FilenameUtils.getName(fileName); } else { String errorMsg = String.format("Fileupload field '%s' has no valid filename '%s'.", PARAM_CRAWLERDOC_NAME, item.getFieldName()); this.logger.warn(errorMsg); context.put(CONTEXT_ERROR_MSG, errorMsg); continue; } // creating a temp-file cDocContentFile = this.tfm.createTempFile(); // getting the content item.write(cDocContentFile); } finally { // delete uploaded item item.delete(); } } } // detect the mime-type of the uploaded file if (this.mimeTypeDetector != null && mimeTypeDetection) { final String tempMimeType = this.mimeTypeDetector.getMimeType(cDocContentFile); if (tempMimeType != null) cDocContentType = tempMimeType; } // determine the charset of the uploaded file if (this.charsetDetector != null && charsetDetection) { final String tempCharset = this.charsetDetector.detectCharset(cDocContentFile); if (tempCharset != null) cDocCharset = tempCharset; } // creating a crawler-document final ICrawlerDocument cDoc = this.cDocFactory.createDocument(ICrawlerDocument.class); cDoc.setStatus(ICrawlerDocument.Status.OK); cDoc.setContent(cDocContentFile); cDoc.setMimeType(cDocContentType); cDoc.setCharset(cDocCharset); // creating a dummy command final ICommand cmd = this.cmdFactory.createDocument(ICommand.class); cmd.setLocation(URI.create(cmdLocation)); cmd.setCrawlerDocument(cDoc); // parsing the command this.parser.process(cmd); if (cmd.getResult() != Result.Passed) { context.put(CONTEXT_ERROR_MSG, String.format("Unable to parse the document: %s", cmd.getResultText())); return; } // trying to get the parsed content final IParserDocument pdoc = cmd.getParserDocument(); if (pdoc == null) { context.put("errorMsg", "Unable to parse the document: parser-document is null."); return; } else if (pdoc.getStatus() != Status.OK) { context.put(CONTEXT_ERROR_MSG, String.format("Unable to parse the document: %s", pdoc.getStatusText())); return; } /* * Remembering some object in the request-context * This is required for cleanup. See #requestCleanup(...) */ request.setAttribute(CONTEXT_CMD, cmd); request.setAttribute(REQ_ATTR_LINEITERS, new ArrayList<Reader>()); /* * Passing some properties to the rendering engine */ context.put(CONTEXT_CMD, cmd); context.put(CONTEXT_PROP_UTIL, new PropertyUtils()); context.put(CONTEXT_SERVLET, this); if (mimeTypeDetection && this.mimeTypeDetector != null) { context.put(PARAM_ENABLE_MIMETYPE_DETECTION, Boolean.TRUE); } if (charsetDetection && this.charsetDetector != null) { context.put(PARAM_ENABLE_CHARSET_DETECTION, Boolean.TRUE); } } } catch (Throwable e) { this.logger.error(e); // delete temp-file if (cDocContentFile != null) { try { this.tfm.releaseTempFile(cDocContentFile); } catch (IOException e2) { /* ignore this */} } } }
From source file:org.rhq.coregui.server.gwt.FileUploadServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL); if (ServletFileUpload.isMultipartContent(req)) { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); if (tmpDir == null) { tmpDir = LookupUtil.getCoreServer().getJBossServerTempDir(); }/*from w w w . ja va 2 s .c o m*/ fileItemFactory.setRepository(tmpDir); //fileItemFactory.setSizeThreshold(0); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); List<FileItem> fileItemsList; try { fileItemsList = servletFileUpload.parseRequest(req); } catch (FileUploadException e) { writeExceptionResponse(resp, "File upload failed", e); return; } List<FileItem> actualFiles = new ArrayList<FileItem>(); Map<String, String> formFields = new HashMap<String, String>(); boolean retrieve = false; boolean obfuscate = false; Subject authenticatedSubject = null; for (FileItem fileItem : fileItemsList) { if (fileItem.isFormField()) { if (fileItem.getFieldName() != null) { formFields.put(fileItem.getFieldName(), fileItem.getString()); } if ("retrieve".equals(fileItem.getFieldName())) { retrieve = true; } else if ("obfuscate".equals(fileItem.getFieldName())) { obfuscate = Boolean.parseBoolean(fileItem.getString()); } else if ("sessionid".equals(fileItem.getFieldName())) { int sessionid = Integer.parseInt(fileItem.getString()); SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager(); try { authenticatedSubject = subjectManager.getSubjectBySessionId(sessionid); } catch (Exception e) { throw new ServletException("Cannot authenticate request", e); } } fileItem.delete(); } else { // file item contains an actual uploaded file actualFiles.add(fileItem); log("file was uploaded: " + fileItem.getName()); } } if (authenticatedSubject == null) { for (FileItem fileItem : actualFiles) { fileItem.delete(); } throw new ServletException("Cannot process unauthenticated request"); } if (retrieve && actualFiles.size() == 1) { // sending in "retrieve" form element with a single file means the client just wants the content echoed back resp.setContentType("text/html"); FileItem fileItem = actualFiles.get(0); ServletOutputStream outputStream = resp.getOutputStream(); outputStream.print("<html>"); InputStream inputStream = fileItem.getInputStream(); try { // we have to HTML escape inputStream before writing it to outputStream StreamUtil.copy(inputStream, outputStream, false, true); } finally { inputStream.close(); } outputStream.print("</html>"); outputStream.flush(); fileItem.delete(); } else { Map<String, File> allUploadedFiles = new HashMap<String, File>(); // maps form field name to the actual file Map<String, String> allUploadedFileNames = new HashMap<String, String>(); // maps form field name to upload file name for (FileItem fileItem : actualFiles) { File theFile = forceToFile(fileItem); if (obfuscate) { // The commons fileupload API has a file tracker that deletes the file when the File object is garbage collected (huh?). // Because we will be using these files later, and because they are going to be obfuscated, we don't want this to happen, // so just rename the file to move it away from the file tracker and thus won't get // prematurely deleted before we get a chance to use it. File movedFile = new File(theFile.getAbsolutePath() + ".temp"); if (theFile.renameTo(movedFile)) { theFile = movedFile; } try { FileUtil.compressFile(theFile); // we really just compress it with our special compressor since its faster than obsfucation } catch (Exception e) { throw new ServletException("Cannot obfuscate uploaded files", e); } } allUploadedFiles.put(fileItem.getFieldName(), theFile); allUploadedFileNames.put(fileItem.getFieldName(), (fileItem.getName() != null) ? fileItem.getName() : theFile.getName()); } processUploadedFiles(authenticatedSubject, allUploadedFiles, allUploadedFileNames, formFields, req, resp); } } }