List of usage examples for org.apache.commons.fileupload FileUpload parseRequest
public List parseRequest(HttpServletRequest req) throws FileUploadException
From source file:net.ontopia.topicmaps.classify.ClassifyUtils.java
public static ClassifiableContentIF getFileUploadContent(HttpServletRequest request) { // Handle file upload String contentType = request.getHeader("content-type"); // out.write("CT: " + contentType + " " + tm + " " + id); if (contentType != null && contentType.startsWith("multipart/form-data")) { try {/*from ww w.j av a 2 s. co m*/ FileUpload upload = new FileUpload(new DefaultFileItemFactory()); for (FileItem item : upload.parseRequest(request)) { if (item.getSize() > 0) { // ISSUE: could make use of content type if known byte[] content = item.get(); ClassifiableContent cc = new ClassifiableContent(); String name = item.getName(); if (name != null) cc.setIdentifier("fileupload:name:" + name); else cc.setIdentifier("fileupload:field:" + item.getFieldName()); cc.setContent(content); return cc; } } } catch (Exception e) { throw new OntopiaRuntimeException(e); } } return null; }
From source file:net.ontopia.topicmaps.webed.impl.utils.ReqParamUtils.java
/** * INTERNAL: Builds the Parameters object from an HttpServletRequest * object./* w w w .ja v a 2 s . c om*/ * @since 2.0 */ public static Parameters decodeParameters(HttpServletRequest request, String charenc) throws ServletException, IOException { String ctype = request.getHeader("content-type"); log.debug("Content-type: " + ctype); Parameters params = new Parameters(); if (ctype != null && ctype.startsWith("multipart/form-data")) { // special file upload request, so use FileUpload to decode log.debug("Decoding with FileUpload; charenc=" + charenc); try { FileUpload upload = new FileUpload(new DefaultFileItemFactory()); Iterator iterator = upload.parseRequest(request).iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); log.debug("Reading: " + item); if (item.isFormField()) { if (charenc != null) params.addParameter(item.getFieldName(), item.getString(charenc)); else params.addParameter(item.getFieldName(), item.getString()); } else params.addParameter(item.getFieldName(), new FileParameter(item)); } } catch (FileUploadException e) { throw new ServletException(e); } } else { // ordinary web request, so retrieve info and stuff into Parameters object log.debug("Normal parameter decode, charenc=" + charenc); if (charenc != null) request.setCharacterEncoding(charenc); Enumeration enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String param = (String) enumeration.nextElement(); params.addParameter(param, request.getParameterValues(param)); } } return params; }
From source file:ccc.plugins.multipart.apache.MultipartForm.java
/** * Parse an HTTP request, extracting the file items. * * @param context The JAXRS context to parse. * * @return A list of file items./* w ww . jav a 2s .co m*/ */ @SuppressWarnings("unchecked") private static List<FileItem> parseFileItems(final JaxrsRequestContext context) { DBC.require().notNull(context); // Check that we have a file upload request final boolean isMultipart = FileUploadBase.isMultipartContent(context); if (!isMultipart) { throw new RuntimeException("Not a multipart."); } // Create a factory for disk-based file items final DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(maxInMemorySize()); // Create a new file upload handler final FileUpload upload = new FileUpload(factory); // Set overall request size constraint upload.setFileSizeMax(maxFileSize()); try { return upload.parseRequest(context); } catch (final FileSizeLimitExceededException e) { throw handleTooBig(e, e.getPermittedSize()); } catch (final SizeLimitExceededException e) { throw handleTooBig(e, e.getPermittedSize()); } catch (final FileUploadException e) { throw new RuntimeException("Failed to parse multipart request.", e); } }
From source file:juzu.plugin.upload.FileUploadUnmarshaller.java
@Override public void unmarshall(String mediaType, final ClientContext context, Iterable<Map.Entry<ContextualParameter, Object>> contextualArguments, Map<String, RequestParameter> parameterArguments) throws IOException { org.apache.commons.fileupload.RequestContext ctx = new org.apache.commons.fileupload.RequestContext() { public String getCharacterEncoding() { return context.getCharacterEncoding(); }/*from www .j ava2s. com*/ public String getContentType() { return context.getContentType(); } public int getContentLength() { return context.getContentLenth(); } public InputStream getInputStream() throws IOException { return context.getInputStream(); } }; // FileUpload upload = new FileUpload(new DiskFileItemFactory()); try { List<FileItem> list = (List<FileItem>) upload.parseRequest(ctx); HashMap<String, FileItem> files = new HashMap<String, FileItem>(); for (FileItem file : list) { String name = file.getFieldName(); if (file.isFormField()) { RequestParameter parameterArg = parameterArguments.get(name); if (parameterArg == null) { parameterArguments.put(name, RequestParameter.create(name, file.getString())); } else { parameterArguments.put(name, parameterArg.append(new String[] { file.getString() })); } } else { files.put(name, file); } } for (Map.Entry<ContextualParameter, Object> argument : contextualArguments) { ContextualParameter contextualParam = argument.getKey(); FileItem file = files.get(contextualParam.getName()); if (file != null && FileItem.class.isAssignableFrom(contextualParam.getType())) { argument.setValue(file); } } } catch (FileUploadException e) { throw new IOException(e); } }
From source file:juzu.plugin.upload.impl.UploadPlugin.java
public void invoke(Request request) { ///*from w ww .ja v a 2s . c o m*/ final ClientContext clientContext = request.getClientContext(); // if (clientContext != null) { String contentType = clientContext.getContentType(); if (contentType != null) { if (contentType.startsWith("multipart/")) { // org.apache.commons.fileupload.RequestContext ctx = new org.apache.commons.fileupload.RequestContext() { public String getCharacterEncoding() { return clientContext.getCharacterEncoding(); } public String getContentType() { return clientContext.getContentType(); } public int getContentLength() { return clientContext.getContentLenth(); } public InputStream getInputStream() throws IOException { return clientContext.getInputStream(); } }; // FileUpload upload = new FileUpload(new DiskFileItemFactory()); // try { List<FileItem> list = (List<FileItem>) upload.parseRequest(ctx); HashMap<String, RequestParameter> parameters = new HashMap<String, RequestParameter>(); for (FileItem file : list) { String name = file.getFieldName(); if (file.isFormField()) { RequestParameter parameter = parameters.get(name); if (parameter != null) { parameter = parameter.append(new String[] { file.getString() }); } else { parameter = RequestParameter.create(name, file.getString()); } parameter.appendTo(parameters); } else { ControlParameter parameter = request.getMethod().getParameter(name); if (parameter instanceof ContextualParameter && FileItem.class.isAssignableFrom(parameter.getType())) { request.setArgument(parameter, file); } } } // Keep original parameters that may come from the request path for (RequestParameter parameter : request.getParameters().values()) { if (!parameters.containsKey(parameter.getName())) { parameter.appendTo(parameters); } } // Redecode phase arguments from updated request Method<?> method = request.getMethod(); Map<ControlParameter, Object> arguments = method.getArguments(parameters); // Update with existing contextual arguments for (Map.Entry<ControlParameter, Object> argument : request.getArguments().entrySet()) { if (argument.getKey() instanceof ContextualParameter) { arguments.put(argument.getKey(), argument.getValue()); } } // Replace all arguments request.setArguments(arguments); } catch (FileUploadException e) { throw new UndeclaredThrowableException(e); } } } } // request.invoke(); }
From source file:com.github.tomakehurst.wiremock.servlet.HttpServletRequestAdapter.java
public Map<String, Request.BodyPart> getMultipart() { if (!isMultipartRequest()) return null; if (cachedMultipart == null) { DiskFileItemFactory factory = new DiskFileItemFactory(); File repository = new File(System.getProperty("java.io.tmpdir")); factory.setRepository(repository); FileUpload fileUpload = new ServletFileUpload(factory); List<FileItem> items; try {//from w w w . j a v a 2 s . c o m items = fileUpload.parseRequest(request); } catch (FileUploadException ex) { throw new RuntimeException(ex); } cachedMultipart = new HashMap<String, Request.BodyPart>(items.size()); for (FileItem item : items) { cachedMultipart.put(item.getFieldName(), new HttpServletRequestBodyPart(item)); } } return cachedMultipart; }
From source file:com.slamd.admin.RequestInfo.java
/** * Creates a new set of request state information using the provided request * and response./*from w ww. j a v a 2 s .c o m*/ * * @param request Information about the HTTP request issued by the client. * @param response Information about the HTTP response that will be returned * to the client. */ public RequestInfo(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; generateHTML = true; debugInfo = new StringBuilder(); htmlBody = new StringBuilder(); infoMessage = new StringBuilder(); if (request != null) { servletBaseURI = request.getRequestURI(); userIdentifier = request.getRemoteUser(); if (FileUpload.isMultipartContent(request)) { try { FileUpload fileUpload = new FileUpload(new DefaultFileItemFactory()); multipartFieldList = fileUpload.parseRequest(request); Iterator iterator = multipartFieldList.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); String name = fileItem.getFieldName(); if (name.equals(Constants.SERVLET_PARAM_SECTION)) { section = new String(fileItem.get()); } else if (name.equals(Constants.SERVLET_PARAM_SUBSECTION)) { subsection = new String(fileItem.get()); } } } catch (FileUploadException fue) { fue.printStackTrace(); } } else { section = request.getParameter(Constants.SERVLET_PARAM_SECTION); subsection = request.getParameter(Constants.SERVLET_PARAM_SUBSECTION); } } if (section == null) { section = ""; } if (subsection == null) { subsection = ""; } }
From source file:cltestgrid.Upload2.java
private List<MyFileItem> parseRequest(HttpServletRequest req) throws RuntimeException { try {//from w w w .j a v a 2 s .c o m if (isMultipartContent(req)) { FileItemFactory factory = new MyFileItemFactory(); FileUpload upload = new FileUpload(factory); return (List<MyFileItem>) upload.parseRequest(req); } else { log.warning("Non multipart request"); return Collections.<MyFileItem>emptyList(); } } catch (FileUploadException e) { throw new RuntimeException("Error parsing multipart request body", e); } }
From source file:com.xpn.xwiki.plugin.fileupload.FileUploadPlugin.java
/** * Loads the list of uploaded files in the context if there are any uploaded files. * /*w ww . jav a 2s. c o m*/ * @param uploadMaxSize Maximum size of the uploaded files. * @param uploadSizeThreashold Threashold over which the file data should be stored on disk, and not in memory. * @param tempdir Temporary directory to store the uploaded files that are not kept in memory. * @param context Context of the request. * @throws XWikiException if the request could not be parsed, or the maximum file size was reached. * @see FileUploadPluginApi#loadFileList(long, int, String) */ public void loadFileList(long uploadMaxSize, int uploadSizeThreashold, String tempdir, XWikiContext context) throws XWikiException { LOGGER.debug("Loading uploaded files"); // If we already have a file list then loadFileList was already called // Continuing would empty the list.. We need to stop. if (context.get(FILE_LIST_KEY) != null) { LOGGER.debug("Called loadFileList twice"); return; } // Get the FileUpload Data // Make sure the factory only ever creates file items which will be deleted when the jvm is stopped. DiskFileItemFactory factory = new DiskFileItemFactory() { public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) { try { final DiskFileItem item = (DiskFileItem) super.createItem(fieldName, contentType, isFormField, fileName); // Needed to make sure the File object is created. item.getOutputStream(); item.getStoreLocation().deleteOnExit(); return item; } catch (IOException e) { String path = System.getProperty("java.io.tmpdir"); if (super.getRepository() != null) { path = super.getRepository().getPath(); } throw new RuntimeException("Unable to create a temporary file for saving the attachment. " + "Do you have write access on " + path + "?"); } } }; factory.setSizeThreshold(uploadSizeThreashold); if (tempdir != null) { File tempdirFile = new File(tempdir); if (tempdirFile.mkdirs() && tempdirFile.canWrite()) { factory.setRepository(tempdirFile); } } // TODO: Does this work in portlet mode, or we must use PortletFileUpload? FileUpload fileupload = new ServletFileUpload(factory); RequestContext reqContext = new ServletRequestContext(context.getRequest().getHttpServletRequest()); fileupload.setSizeMax(uploadMaxSize); // context.put("fileupload", fileupload); try { @SuppressWarnings("unchecked") List<FileItem> list = fileupload.parseRequest(reqContext); if (list.size() > 0) { LOGGER.info("Loaded " + list.size() + " uploaded files"); } // We store the file list in the context context.put(FILE_LIST_KEY, list); } catch (FileUploadBase.SizeLimitExceededException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE, "Exception uploaded file"); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_UPLOAD_PARSE_EXCEPTION, "Exception while parsing uploaded file", e); } }
From source file:helma.servlet.AbstractServletClient.java
protected List parseUploads(ServletRequestContext reqcx, RequestTrans reqtrans, final UploadStatus uploadStatus, String encoding) throws FileUploadException, UnsupportedEncodingException { // handle file upload DiskFileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); // use upload limit for individual file size, but also set a limit on overall size upload.setFileSizeMax(uploadLimit * 1024); upload.setSizeMax(totalUploadLimit * 1024); // register upload tracker with user's session if (uploadStatus != null) { upload.setProgressListener(new ProgressListener() { public void update(long bytesRead, long contentLength, int itemsRead) { uploadStatus.update(bytesRead, contentLength, itemsRead); }//from www . j a v a 2s. c om }); } List uploads = upload.parseRequest(reqcx); Iterator it = uploads.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); String name = item.getFieldName(); Object value; // check if this is an ordinary HTML form element or a file upload if (item.isFormField()) { value = item.getString(encoding); } else { value = new MimePart(item); } // if multiple values exist for this name, append to _array reqtrans.addPostParam(name, value); } return uploads; }