List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax
public void setSizeMax(long sizeMax)
From source file:org.elissa.server.AMLSupport.java
/** * The POST request.EPCUpload.java// w w w. j ava 2 s .com */ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException { PrintWriter out = null; FileItem fileItem = null; try { String oryxBaseUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/"; // Get the PrintWriter res.setContentType("text/plain"); res.setCharacterEncoding("utf-8"); out = res.getWriter(); // No isMultipartContent => Error final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req); if (!isMultipartContent) { printError(out, "No Multipart Content transmitted."); return; } // Get the uploaded file final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setSizeMax(-1); final List<?> items; items = servletFileUpload.parseRequest(req); if (items.size() != 1) { printError(out, "Not exactly one File."); return; } fileItem = (FileItem) items.get(0); // replace dtd reference by existing reference /oryx/lib/ARIS-Export.dtd String amlStr = fileItem.getString("UTF-8"); amlStr = amlStr.replaceFirst("\"ARIS-Export.dtd\"", "\"" + oryxBaseUrl + "lib/ARIS-Export.dtd\""); FileOutputStream fileout = null; OutputStreamWriter outwriter = null; try { fileout = new FileOutputStream(((DiskFileItem) fileItem).getStoreLocation()); outwriter = new OutputStreamWriter(fileout, "UTF-8"); outwriter.write(amlStr); outwriter.flush(); } finally { if (outwriter != null) outwriter.close(); if (fileout != null) fileout.close(); } //parse AML file AMLParser parser = new AMLParser(((DiskFileItem) fileItem).getStoreLocation().getAbsolutePath()); parser.parse(); Collection<EPC> epcs = new HashSet<EPC>(); Iterator<String> ids = parser.getModelIds().iterator(); while (ids.hasNext()) { String modelId = ids.next(); epcs.add(parser.getEPC(modelId)); } // serialize epcs to eRDF oryx format OryxSerializer oryxSerializer = new OryxSerializer(epcs, oryxBaseUrl); oryxSerializer.parse(); Document outputDocument = oryxSerializer.getDocument(); // get document as string String docAsString = ""; Source source = new DOMSource(outputDocument); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transformer = tfactory.newTransformer(); transformer.transform(source, result); docAsString = stringWriter.getBuffer().toString(); // write response out.print("" + docAsString + ""); } catch (Exception e) { handleException(out, e); } finally { if (fileItem != null) { fileItem.delete(); } } }
From source file:org.elissa.server.EPCUpload.java
/** * The POST request.//from w w w .jav a 2s .co m */ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException { // No isMultipartContent => Error final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req); if (!isMultipartContent) { printError(res, "No Multipart Content transmitted."); return; } // Get the uploaded file final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setSizeMax(-1); final List<?> items; try { items = servletFileUpload.parseRequest(req); if (items.size() != 1) { printError(res, "Not exactly one File."); return; } } catch (FileUploadException e) { handleException(res, e); return; } final FileItem fileItem = (FileItem) items.get(0); // Get filename and content (needed to distinguish between EPML and AML) final String fileName = fileItem.getName(); String content = fileItem.getString(); // Get the input stream final InputStream inputStream; try { inputStream = fileItem.getInputStream(); } catch (IOException e) { handleException(res, e); return; } // epml2eRDF XSLT source final String xsltFilename = getServletContext().getRealPath("/xslt/EPML2eRDF.xslt"); // final String xsltFilename = System.getProperty("catalina.home") + "/webapps/oryx/xslt/EPML2eRDF.xslt"; final File epml2eRDFxsltFile = new File(xsltFilename); final Source epml2eRDFxsltSource = new StreamSource(epml2eRDFxsltFile); // Transformer Factory final TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Get the epml source final Source epmlSource; if (fileName.endsWith(".epml") || content.contains("http://www.epml.de")) { epmlSource = new StreamSource(inputStream); } else { printError(res, "No EPML or AML file uploaded."); return; } // Get the result string String resultString = null; try { Transformer transformer = transformerFactory.newTransformer(epml2eRDFxsltSource); StringWriter writer = new StringWriter(); transformer.transform(epmlSource, new StreamResult(writer)); resultString = writer.toString(); } catch (Exception e) { handleException(res, e); return; } if (resultString != null) { try { printResponse(res, resultString); } catch (Exception e) { handleException(res, e); return; } } }
From source file:org.entermedia.upload.FileUpload.java
/** * @param inContext//from w w w . ja va 2 s .com * @return */ public UploadRequest parseArguments(WebPageRequest inContext) throws OpenEditException { final UploadRequest upload = new UploadRequest(); upload.setPageManager(getPageManager()); upload.setRoot(getRoot()); //upload.setProperties(inContext.getParameterMap()); if (inContext.getRequest() == null) //used in unit tests { return upload; } String type = inContext.getRequest().getContentType(); if (type == null || !type.startsWith("multipart")) { addAlreadyUploaded(inContext, upload); return upload; } String uploadid = inContext.getRequestParameter("uploadid"); String catalogid = inContext.findValue("catalogid"); if (uploadid != null && catalogid != null) { upload.setUploadId(uploadid); upload.setCatalogId(catalogid); upload.setUserName(inContext.getUserName()); upload.setUploadQueueSearcher(loadQueueSearcher(catalogid)); } //Our factory will track these items as they are made. Each time some data comes in look over all the files and update the size FileItemFactory factory = (FileItemFactory) inContext.getPageValue("uploadfilefactory"); if (factory == null) { DiskFileItemFactory dfactory = new DiskFileItemFactory(); // { // public org.apache.commons.fileupload.FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) // { // if( !isFormField ) // { // upload.track(fieldName, contentType, isFormField, fileName); // } // return super.createItem(fieldName, contentType, isFormField, fileName); // }; // } factory = dfactory; } ServletFileUpload uploadreader = new ServletFileUpload(factory); //upload.setSizeThreshold(BUFFER_SIZE); if (uploadid != null) { uploadreader.setProgressListener(upload); } HttpServletRequest req = inContext.getRequest(); String encode = req.getCharacterEncoding(); if (encode == null) { //log.info("Encoding not set."); encode = "UTF-8"; } //log.info("Encoding is set to " + encode); uploadreader.setHeaderEncoding(encode); //upload.setHeaderEncoding() //Content-Transfer-Encoding: binary //upload.setRepositoryPath(repository.pathToFile("admin uploadreader.setSizeMax(-1); try { readParameters(inContext, uploadreader, upload, encode); } catch (UnsupportedEncodingException e) { throw new OpenEditException(e); } if (uploadid != null) { expireOldUploads(catalogid); } return upload; }
From source file:org.exoplatform.document.upload.handle.UploadMultipartHandler.java
@Override public List<Document> parseHttpRequest(HttpServletRequest request) throws SizeLimitExceededException, FileUploadException { if (logger.isDebugEnabled()) { logger.info("Parse file item form HTTP servlet request."); }/*w ww. ja v a 2 s . com*/ Document document = null; List<Document> documents = new ArrayList<Document>(); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) return documents; File repository = FileUtils.forceMkdir(FilePathUtils.REPOSITORY_PATH); if (repository != null) logger.info("The" + FilePathUtils.REPOSITORY_PATH + " Directory is created"); if (FileUtils.forceMkdir(FilePathUtils.RESOURCE_PATH) != null) logger.info("To create specified sub-folder under " + FilePathUtils.ROOT_PATH + " top-level folder"); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MEMORY_CACHE_SIZE); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAXIMUM_FILE_SIZE); try { List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iterator = items.iterator(); while (iterator.hasNext()) { FileItem fileItem = iterator.next(); if (!fileItem.isFormField()) { // Write file items to disk-based String absolutePath = writeFiles(fileItem, fileItem.getName()); document = Document.getInstance(); document.setFilename(fileItem.getName()); document.setContentType(fileItem.getContentType()); document.setSize(fileItem.getSize()); document.setUrl(absolutePath); document.setReadOnly(false); document.setArchive(false); document.setDirectory(false); document.setHidden(false); document.setSystem(false); document.setOther(false); document.setRegularFile(false); Date time = Calendar.getInstance().getTime(); document.setCreationTime(time); document.setLastAccessTime(time); document.setLastModifiedTime(time); documents.add(document); logger.info("File(s) " + document.getFilename() + " was/were uploaded successfully"); } } } catch (SizeLimitExceededException slee) { throw new SizeLimitExceededException( "The request was rejected because its size exceeds (" + slee.getActualSize() + "bytes) the configured maximum (" + slee.getPermittedSize() + "bytes)"); } catch (FileUploadException fue) { throw new FileUploadException("Upload file stream was been cancelled", fue.getCause()); } finally { try { FileUtils.cleanDirectory(factory.getRepository()); logger.info("Cleans a directory without deleting it"); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } } return documents; }
From source file:org.geowe.server.upload.FileUploadServlet.java
@Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final ServletFileUpload upload = new ServletFileUpload(); response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_FILE_SIZE); try {// w w w.ja v a2 s . c o m final FileItemIterator iter = upload.getItemIterator(request); final StringWriter writer = new StringWriter(); while (iter.hasNext()) { final FileItemStream item = iter.next(); IOUtils.copy(item.openStream(), writer, "UTF-8"); final String content = writer.toString(); response.setStatus(HttpStatus.SC_OK); response.getWriter().printf(content); } } catch (SizeLimitExceededException e) { response.setStatus(HttpStatus.SC_REQUEST_TOO_LONG); response.getWriter().printf(HttpStatus.SC_REQUEST_TOO_LONG + ":" + e.getMessage()); LOG.error(e.getMessage()); } catch (Exception e) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); response.getWriter().printf(HttpStatus.SC_INTERNAL_SERVER_ERROR + ": ups! something went wrong."); LOG.error(e.getMessage()); } }
From source file:org.geowe.server.upload.FileUploadZipServlet.java
@Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final ServletFileUpload upload = new ServletFileUpload(); response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_FILE_SIZE); try {//from w ww . j a v a2 s . co m final FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); ZipFile zipFile = createZipFile(item); final String content = readZipFile(zipFile); if (EMPTY.equals(content)) { response.setStatus(HttpStatus.SC_NO_CONTENT); response.getWriter().printf(HttpStatus.SC_NO_CONTENT + ":" + content); } else if (BAD_FORMAT.equals(content)) { response.setStatus(HttpStatus.SC_NOT_ACCEPTABLE); response.getWriter().printf(HttpStatus.SC_NOT_ACCEPTABLE + ":" + content); } else { response.setStatus(HttpStatus.SC_OK); response.getWriter().printf(content); } } } catch (SizeLimitExceededException e) { response.setStatus(HttpStatus.SC_REQUEST_TOO_LONG); response.getWriter().printf(HttpStatus.SC_REQUEST_TOO_LONG + ":" + e.getMessage()); LOG.error(e.getMessage()); } catch (Exception e) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); response.getWriter().printf(HttpStatus.SC_INTERNAL_SERVER_ERROR + ": ups! something went wrong."); LOG.error(e.getMessage()); } }
From source file:org.getobjects.servlets.WOServletRequest.java
/** * Initialize the WORequest object with the data contained in the * HttpServletRequest.//from w w w .j a v a 2 s . c o m * This will load the HTTP headers from the servlet request into the * WORequest, * it will decode cookies, * it will decode query parameters and form values * and it will process the content. * * @param _rq - the HttpServletRequest * @param _r - the HttpServletResponse */ @SuppressWarnings("unchecked") protected void init(final HttpServletRequest _rq, final HttpServletResponse _r) { this.init(_rq.getMethod(), _rq.getRequestURI(), _rq.getProtocol(), null /* headers */, null /* contents */, null /* userInfo */); this.sRequest = _rq; this.sResponse = _r; this.loadHeadersFromServletRequest(_rq); this.loadCookies(); // Note: ServletFileUpload.isMultipartContent() is deprecated String contentType = this.headerForKey("content-type"); if (contentType != null) contentType = contentType.toLowerCase(); if (contentType != null && contentType.startsWith("multipart/form-data")) { final FileItemFactory factory = // Apache stuff new DiskFileItemFactory(maxRAMFileSize, tmpFileLocation); final ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxRequestSize); List<FileItem> items = null; try { items = upload.parseRequest(_rq); } catch (FileUploadException e) { items = null; log.error("failed to parse upload request", e); } /* load regular form values (query parameters) */ this.loadFormValuesFromRequest(_rq); /* next load form values from file items */ this.loadFormValuesFromFileItems(items); } else if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")) { /* Note: we need to load form values first, because when we load the * content, we need to process them on our own. */ this.loadFormValuesFromRequest(_rq); /* Note: since we made the Servlet container process the form content, * we can't load any content ... */ } else { /* Note: we need to load form values first, because when we load the * content, we need to process them on our own. */ this.loadFormValuesFromRequest(_rq); // TODO: make this smarter, eg transfer large PUTs to disk this.loadContentFromRequest(_rq); } }
From source file:org.infoglue.deliver.taglib.common.ParseMultipartTag.java
/** * Process the end tag. Sets a cookie. * /*from ww w . j a v a 2s . c o m*/ * @return indication of whether to continue evaluating the JSP page. * @throws JspException if an error occurred while processing this tag. */ public int doEndTag() throws JspException { Map parameters = new HashMap(); try { //Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); //Set factory constraints factory.setSizeThreshold(maxSize.intValue()); //factory.setRepository(new File(CmsPropertyHandler.getDigitalAssetPath())); //Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //Set overall request size constraint upload.setSizeMax(this.maxSize.intValue()); if (upload.isMultipartContent(this.getController().getHttpServletRequest())) { //Parse the request List items = upload.parseRequest(this.getController().getHttpServletRequest()); List files = new ArrayList(); //Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (isValidContentType(contentType)) { files.add(item); } else { if ((item.getName() == null || item.getName().equals("")) && this.ignoreEmpty) { logger.warn("Empty file but that was ok.."); } else { pageContext.setAttribute("status", "nok"); pageContext.setAttribute("upload_error", "A field did not have a valid content type"); pageContext.setAttribute(fieldName + "_error", "Not a valid content type"); //throw new JspException("Not a valid content type"); } } } else { String name = item.getFieldName(); String value = item.getString(); String oldValue = (String) parameters.get(name); if (oldValue != null) value = oldValue + "," + value; if (value != null) { try { String fromEncoding = "iso-8859-1"; String toEncoding = "utf-8"; String testValue = new String(value.getBytes(fromEncoding), toEncoding); if (testValue.indexOf((char) 65533) == -1) value = testValue; } catch (Exception e) { e.printStackTrace(); } } parameters.put(name, value); } } parameters.put("files", files); setResultAttribute(parameters); } else { setResultAttribute(null); } } catch (Exception e) { logger.warn("Error doing an upload" + e.getMessage(), e); //pageContext.setAttribute("fieldName_exception", "contentType_MAX"); //throw new JspException("File upload failed: " + e.getMessage()); pageContext.setAttribute("status", "nok"); pageContext.setAttribute("upload_error", "" + e.getMessage()); } return EVAL_PAGE; }
From source file:org.infoscoop.admin.web.UploadGadgetServlet.java
private UploadFileInfo extractUploadFileInfo(HttpServletRequest req) { UploadFileInfo info = new UploadFileInfo(); try {//from w w w. j ava2 s .c o m DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //set the standard value that needs when it upload. factory.setSizeThreshold(1024); upload.setSizeMax(-1); List<FileItem> items = upload.parseRequest(req); //get the FileItem object for (FileItem fItem : items) { if ("data".equals(fItem.getFieldName())) { info.fileItem = fItem; } else if ("type".equals(fItem.getFieldName())) { info.type = fItem.getString(); } else if ("mode".equals(fItem.getFieldName())) { info.mode = fItem.getString(); } else if ("path".equals(fItem.getFieldName())) { info.path = fItem.getString(); } else if ("name".equals(fItem.getFieldName())) { info.name = fItem.getString(); } else if ("create".equals(fItem.getFieldName())) { try { info.create = Boolean.valueOf(fItem.getString()); } catch (Exception ex) { // ignore } } } } catch (FileUploadException ex) { throw new GadgetResourceException("Unexpected error occurred while getting uplaod file.", "ams_gadgetResourceUnexceptedUploadFailed", ex); } catch (Exception ex) { throw new GadgetResourceException(ex); } // check the file(for FireFox) if (info.fileItem == null || info.fileItem.getName().length() == 0) throw new GadgetResourceException("Upload file not found.", "ams_gadgetResourceUploadFileNotFound"); // check the file(for IE) if (info.fileItem.getSize() == 0) throw new GadgetResourceException("The upload file is not found or the file is empty.", "ams_gadgetResourceUploadFileNotFoundOrEmpty"); if (!info.isModuleMode()) { if (info.type == null || info.path == null || info.name == null) throw new GadgetResourceException(); } return info; }
From source file:org.j2eeframework.commons.struts2.multipart.JakartaMultiPartRequest.java
/** * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's * multipart classes (see class description). * * @param saveDir the directory to save off the file * @param servletRequest the request containing the multipart * @throws java.io.IOException is thrown if encoding fails. *//*from w w w . j ava 2s. c o m*/ public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { DiskFileItemFactory fac = new DiskFileItemFactory(); // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } // Parse the request try { ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(createRequestContext(servletRequest)); for (Object item1 : items) { FileItem item = (FileItem) item1; if (LOG.isDebugEnabled()) LOG.debug("Found item " + item.getFieldName()); if (item.isFormField()) { LOG.debug("Item is a normal form field"); List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } // note: see http://jira.opensymphony.com/browse/WW-633 // basically, in some cases the charset may be null, so // we're just going to try to "other" method (no idea if this // will work) String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { LOG.debug("Item is a file upload"); // Skip file uploads that don't have a file name - meaning that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) { LOG.debug("No file has been uploaded for the field: " + item.getFieldName()); continue; } List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (SizeLimitExceededException e) { ArrayList<String> values = new ArrayList<String>(); values.add("SizeLimitExceededException"); params.put("exception", values);//? } catch (FileUploadException e) { LOG.error("Unable to parse request", e); ArrayList<String> values = new ArrayList<String>(); values.add("FileUploadException"); params.put("exception", values); errors.add(e.getMessage()); } }