List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold
public void setSizeThreshold(int sizeThreshold)
From source file:org.apache.felix.webconsole.AbstractWebConsolePluginServlet.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static String getRequestParameter(HttpServletRequest request, String name) { // just get the parameter if not a multipart/form-data POST if (!ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) { return request.getParameter(name); }/*from w ww . jav a2s . c o m*/ // check, whether we alread have the parameters Map params = (Map) request.getAttribute(ATTR_FILEUPLOAD); if (params == null) { // parameters not read yet, read now // Create a factory for disk-based file items DiskFileItemFactory myFactory = new DiskFileItemFactory(); myFactory.setSizeThreshold(FACTORY_LIMIT); // Create a new file upload handler ServletFileUpload uploadServlet = new ServletFileUpload(myFactory); uploadServlet.setSizeMax(-1); // Parse the request params = new HashMap(); try { List parseItems = uploadServlet.parseRequest(request); for (Iterator fIter = parseItems.iterator(); fIter.hasNext();) { FileItem fileItem = (FileItem) fIter.next(); FileItem[] currentItem = (FileItem[]) params.get(fileItem.getFieldName()); if (currentItem == null) { currentItem = new FileItem[] { fileItem }; } else { FileItem[] newCurrent = new FileItem[currentItem.length + 1]; System.arraycopy(currentItem, 0, newCurrent, 0, currentItem.length); newCurrent[currentItem.length] = fileItem; currentItem = newCurrent; } params.put(fileItem.getFieldName(), currentItem); } } catch (FileUploadException fue) { } request.setAttribute(ATTR_FILEUPLOAD, params); } FileItem[] fileParam = (FileItem[]) params.get(name); if (fileParam != null) { for (int i = 0; i < fileParam.length; i++) { if (fileParam[i].isFormField()) { return fileParam[i].getString(); } } } // no valid string parameter, fail return null; }
From source file:org.apache.felix.webconsole.WebConsoleUtil.java
/** * An utility method, that is used to filter out simple parameter from file * parameter when multipart transfer encoding is used. * * This method processes the request and sets a request attribute * {@link AbstractWebConsolePlugin#ATTR_FILEUPLOAD}. The attribute value is a {@link Map} * where the key is a String specifying the field name and the value * is a {@link org.apache.commons.fileupload.FileItem}. * * @param request the HTTP request coming from the user * @param name the name of the parameter * @return if not multipart transfer encoding is used - the value is the * parameter value or <code>null</code> if not set. If multipart is used, * and the specified parameter is field - then the value of the parameter * is returned./*from www .ja va 2 s .c om*/ */ public static final String getParameter(HttpServletRequest request, String name) { // just get the parameter if not a multipart/form-data POST if (!FileUploadBase.isMultipartContent(new ServletRequestContext(request))) { return request.getParameter(name); } // check, whether we already have the parameters Map params = (Map) request.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD); if (params == null) { // parameters not read yet, read now // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(256000); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); // Parse the request params = new HashMap(); try { List items = upload.parseRequest(request); for (Iterator fiter = items.iterator(); fiter.hasNext();) { FileItem fi = (FileItem) fiter.next(); FileItem[] current = (FileItem[]) params.get(fi.getFieldName()); if (current == null) { current = new FileItem[] { fi }; } else { FileItem[] newCurrent = new FileItem[current.length + 1]; System.arraycopy(current, 0, newCurrent, 0, current.length); newCurrent[current.length] = fi; current = newCurrent; } params.put(fi.getFieldName(), current); } } catch (FileUploadException fue) { // TODO: log } request.setAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD, params); } FileItem[] param = (FileItem[]) params.get(name); if (param != null) { for (int i = 0; i < param.length; i++) { if (param[i].isFormField()) { return param[i].getString(); } } } // no valid string parameter, fail return null; }
From source file:org.apache.flink.client.web.JobsServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // check, if we are doing the right request if (!ServletFileUpload.isMultipartContent(req)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return;//from w w w . j a v a 2s . c om } // create the disk file factory, limiting the file size to 20 MB DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(20 * 1024 * 1024); // 20 MB fileItemFactory.setRepository(tmpDir); String filename = null; // parse the request ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try { Iterator<FileItem> itr = ((List<FileItem>) uploadHandler.parseRequest(req)).iterator(); // go over the form fields and look for our file while (itr.hasNext()) { FileItem item = itr.next(); if (!item.isFormField()) { if (item.getFieldName().equals("upload_jar_file")) { // found the file, store it to the specified location filename = item.getName(); File file = new File(destinationDir, filename); item.write(file); break; } } } } catch (FileUploadException ex) { resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid Fileupload."); return; } catch (Exception ex) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An unknown error occurred during the file upload."); return; } // write the okay message resp.sendRedirect(targetPage); }
From source file:org.apache.sling.osgi.obr.OSGiBundleRepositoryServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // check whether dumping the repository is requested if (req.getRequestURI().endsWith("/repository.zip")) { this.dumpRepository(req.getParameterValues("bundle"), resp); resp.sendRedirect(req.getRequestURI()); return;/* w ww .j a va 2s. c o m*/ } if (!ServletFileUpload.isMultipartContent(new ServletRequestContext(req))) { resp.sendRedirect(req.getRequestURI()); return; } // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(256000); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); // Parse the request boolean noRedirect = false; String bundleLocation = null; InputStream bundleStream = null; try { List /* FileItem */ items = upload.parseRequest(req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { bundleStream = item.getInputStream(); bundleLocation = item.getName(); } else { noRedirect |= "_noredir_".equals(item.getFieldName()); } } if (bundleStream != null && bundleLocation != null) { try { this.repository.addResource(bundleStream); } catch (IOException ioe) { resp.sendError(500, "Cannot register file " + bundleLocation + ". Reason: " + ioe.getMessage()); } } } catch (FileUploadException fue) { throw new ServletException(fue.getMessage(), fue); } finally { if (bundleStream != null) { try { bundleStream.close(); } catch (IOException ignore) { } } } // only redirect if not instructed otherwise if (noRedirect) { resp.setContentType("text/plain"); if (bundleLocation != null) { resp.getWriter().print("Bundle " + bundleLocation + " uploaded"); } else { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().print("No Bundle uploaded"); } } else { resp.sendRedirect(req.getRequestURI()); } }
From source file:org.apache.sling.tooling.support.install.impl.InstallServlet.java
private void installBasedOnUploadedJar(HttpServletRequest req, HttpServletResponse resp) throws IOException { InstallationResult result = null;//from ww w .java 2s .c om try { DiskFileItemFactory factory = new DiskFileItemFactory(); // try to hold even largish bundles in memory to potentially improve performance factory.setSizeThreshold(UPLOAD_IN_MEMORY_SIZE_THRESHOLD); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req); if (items.size() != 1) { logAndWriteError( "Found " + items.size() + " items to process, but only updating 1 bundle is supported", resp); return; } FileItem item = items.get(0); JarInputStream jar = null; InputStream rawInput = null; try { jar = new JarInputStream(item.getInputStream()); Manifest manifest = jar.getManifest(); if (manifest == null) { logAndWriteError("Uploaded jar file does not contain a manifest", resp); return; } final String symbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); if (symbolicName == null) { logAndWriteError("Manifest does not have a " + Constants.BUNDLE_SYMBOLICNAME, resp); return; } final String version = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION); // the JarInputStream is used only for validation, we need a fresh input stream for updating rawInput = item.getInputStream(); Bundle found = getBundle(symbolicName); try { installOrUpdateBundle(found, rawInput, "inputstream:" + symbolicName + "-" + version + ".jar"); result = new InstallationResult(true, null); resp.setStatus(200); result.render(resp.getWriter()); return; } catch (BundleException e) { logAndWriteError("Unable to install/update bundle " + symbolicName, e, resp); return; } } finally { IOUtils.closeQuietly(jar); IOUtils.closeQuietly(rawInput); } } catch (FileUploadException e) { logAndWriteError("Failed parsing uploaded bundle", e, resp); return; } }
From source file:org.azkfw.web.purser.HttpServletMultipartPurser.java
@Override protected Map<String, Object> doPurse(final HttpServletRequest aReq, final HttpServletResponse aRes) throws WebServiceException { Map<String, Object> parameter = new HashMap<String, Object>(); if (ServletFileUpload.isMultipartContent(aReq)) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); factory.setSizeThreshold(1024); upload.setSizeMax(-1);/*from w w w . j a va 2 s .c om*/ upload.setHeaderEncoding(encoding); try { List<FileItem> list = upload.parseRequest(aReq); Iterator<FileItem> iterator = list.iterator(); while (iterator.hasNext()) { FileItem fItem = (FileItem) iterator.next(); if (fItem.isFormField()) { parameter.put(fItem.getFieldName(), fItem.getString(encoding)); } else { String fileName = fItem.getName(); if ((fileName != null) && (!fileName.equals(""))) { fileName = (new File(fileName)).getName(); String filePath = PathUtility.cat(temporaryDirectory, fileName); File file = new File(filePath); fItem.write(file); parameter.put(fItem.getFieldName(), file); } } } } catch (FileUploadException ex) { throw new WebServiceException(ex); } catch (Exception ex) { throw new WebServiceException(ex); } } else { for (String key : (Set<String>) aReq.getParameterMap().keySet()) { String[] values = aReq.getParameterValues(key); if (1 == values.length) { parameter.put(key, values[0]); } else { parameter.put(key, values); } } } return parameter; }
From source file:org.codeartisans.proxilet.Proxilet.java
/** * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the given * {@link HttpServletRequest}./*from www . ja va2s.c om*/ * * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the mutlipart POST data to be sent via the {@link PostMethod} */ @SuppressWarnings("unchecked") private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(maxFileUploadSize); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(HEADER_CONTENT_TYPE, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java
@RequestMapping("/upload-test") public String upload(Model model, HttpServletRequest request, ServletContext context) throws Exception { logger.debug("upload-teset"); DataSetList outputDataSetList = new DataSetList(); VariableList outputVariableList = new VariableList(); try {// www. j a va 2s . co m boolean isMultipart = ServletFileUpload.isMultipartContent(request); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String mapId = (String) paramMap.get("mapId"); RepositoryType acceptedRepositoryType = repositoryType; String requestedRepositoryType = (String) paramMap.get("repositoryType"); if (StringUtils.isNotEmpty(requestedRepositoryType)) { acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType); } if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(sizeThreshold); factory.setRepository(new File(tempRepositoryPath)); factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(context)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(fileSizeMax); upload.setSizeMax(requestSizeMax); upload.setHeaderEncoding(characterEncoding); upload.setProgressListener(new FileUploadProgressListener()); List<FileItem> fileItemList = upload.parseRequest(request); Iterator<FileItem> iter = fileItemList.iterator(); while (iter.hasNext()) { FileItem fileItem = iter.next(); logger.debug("fileItem: {}", fileItem.toString()); FileDTO fileDTO = null; if (fileItem.isFormField()) { paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding)); } else { if (fileItem.getName() == null || fileItem.getName().length() == 0) continue; // set DTO fileDTO = new FileDTO(); fileDTO.setMapId(mapId); fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName())); if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) { fileDTO.setUniqueFilename(uniqueFilenameGenerationService.getNextStringId()); } fileDTO.setContentType(fileItem.getContentType()); fileDTO.setRepositoryPath(realRepositoryPath); logger.debug("fileDTO: {}", fileDTO.toString()); UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO); } if (fileDTO != null) fileManager.insertFile(fileDTO); } } else { } XplatformUtils.setSuccessMessage( messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList); logger.debug("success"); } catch (Exception e) { logger.error("fail"); e.printStackTrace(); logger.error(e.getMessage()); throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale), e); } model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList); model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList); return VIEW_NAME; }
From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java
/** * ?? .</br> ? ? ?? ? , (: ?) ? mapId . ? * ?? ? repositoryType , ?//from w w w. j a v a 2 s . c o m * org.codelabor.system.file.RepositoryType . * * @param request * * @param response * ? * @throws Exception * */ @SuppressWarnings("unchecked") protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(this.getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String mapId = (String) paramMap.get("mapId"); RepositoryType acceptedRepositoryType = repositoryType; String requestedRepositoryType = (String) paramMap.get("repositoryType"); if (StringUtils.isNotEmpty(requestedRepositoryType)) { acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType); } if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(sizeThreshold); factory.setRepository(new File(tempRepositoryPath)); factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(this.getServletContext())); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(fileSizeMax); upload.setSizeMax(requestSizeMax); upload.setHeaderEncoding(characterEncoding); upload.setProgressListener(new FileUploadProgressListener()); try { List<FileItem> fileItemList = upload.parseRequest(request); Iterator<FileItem> iter = fileItemList.iterator(); while (iter.hasNext()) { FileItem fileItem = iter.next(); logger.debug("fileItem: {}", fileItem.toString()); FileDTO fileDTO = null; if (fileItem.isFormField()) { paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding)); } else { if (fileItem.getName() == null || fileItem.getName().length() == 0) continue; // set DTO fileDTO = new FileDTO(); fileDTO.setMapId(mapId); fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName())); if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) { fileDTO.setUniqueFilename(getUniqueFilename()); } fileDTO.setContentType(fileItem.getContentType()); fileDTO.setRepositoryPath(realRepositoryPath); logger.debug("fileDTO: {}", fileDTO.toString()); UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO); } if (fileDTO != null) fileManager.insertFile(fileDTO); } } catch (FileUploadException e) { e.printStackTrace(); logger.error(e.getMessage()); throw e; } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); throw e; } } else { paramMap = RequestUtils.getParameterMap(request); } try { processParameters(paramMap); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); throw e; } dispatch(request, response, forwardPathUpload); }
From source file:org.danann.cernunnos.runtime.web.CernunnosPortlet.java
@SuppressWarnings("unchecked") private void runScript(URL u, PortletRequest req, PortletResponse res, RuntimeRequestResponse rrr) { // Choose the right Task... Task k = getTask(u);/*from www. j a v a 2 s .com*/ // Basic, guaranteed request attributes... rrr.setAttribute(WebAttributes.REQUEST, req); rrr.setAttribute(WebAttributes.RESPONSE, res); // Also let's check the request for multi-part form // data & convert to request attributes if we find any... List<InputStream> streams = new LinkedList<InputStream>(); if (req instanceof ActionRequest && PortletFileUpload.isMultipartContent((ActionRequest) req)) { if (log.isDebugEnabled()) { log.debug("Multipart form data detected (preparing to process)."); } try { final DiskFileItemFactory fac = new DiskFileItemFactory(); final PortletFileUpload pfu = new PortletFileUpload(fac); final long maxSize = pfu.getFileSizeMax(); // FixMe!! pfu.setFileSizeMax(maxSize); pfu.setSizeMax(maxSize); fac.setSizeThreshold((int) (maxSize + 1L)); List<FileItem> items = pfu.parseRequest((ActionRequest) req); for (FileItem f : items) { if (log.isDebugEnabled()) { log.debug("Processing file upload: name='" + f.getName() + "',fieldName='" + f.getFieldName() + "'"); } InputStream inpt = f.getInputStream(); rrr.setAttribute(f.getFieldName(), inpt); rrr.setAttribute(f.getFieldName() + "_FileItem", f); streams.add(inpt); } } catch (Throwable t) { String msg = "Cernunnos portlet failed to process multipart " + "form data from the request."; throw new RuntimeException(msg, t); } } else { if (log.isDebugEnabled()) { log.debug("Multipart form data was not detected."); } } // Anything that should be included from the spring_context? if (spring_context != null && spring_context.containsBean("requestAttributes")) { Map<String, Object> requestAttributes = (Map<String, Object>) spring_context .getBean("requestAttributes"); for (Map.Entry entry : requestAttributes.entrySet()) { rrr.setAttribute((String) entry.getKey(), entry.getValue()); } } runner.run(k, rrr); // Clean up resources... if (streams.size() > 0) { try { for (InputStream inpt : streams) { inpt.close(); } } catch (Throwable t) { String msg = "Cernunnos portlet failed to release resources."; throw new RuntimeException(msg, t); } } }