List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold
public void setSizeThreshold(int sizeThreshold)
From source file:org.owasp.webgoat.plugin.MaliciousFileExecution.java
/** * Constructor for the DatabaseFieldScreen object * //from w ww . ja v a2 s.co m * @param s * Description of the Parameter */ public void handleRequest(WebSession s) { if (uploads_and_target_parent_directory == null) { fill_uploads_and_target_parent_directory(s); } try { if (ServletFileUpload.isMultipartContent(s.getRequest())) { // multipart request - we have the file upload // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(500000); // files over 500k will be written to disk temporarily. // files under that size will be stored in memory until written to disk by the request handler code below // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest(s.getRequest()); // Process the uploaded items java.util.Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // ignore regular form fields } else { // not a form field, must be a file upload if (item.getName().contains("/") || item.getName().contains("\\")) { System.out.println( "Uploaded file contains a / or \\ (i.e. attempted directory traversal). Not storing file."); // TODO - is there a way to show an error to the user here? s.setMessage("Directory traversal not allowed. Nice try though."); } else { // write file to disk with original name in uploads directory String uploaded_file_path = uploads_and_target_parent_directory + UPLOADS_RELATIVE_PATH + java.io.File.separator + item.getName(); File uploadedFile = new File(uploaded_file_path); item.write(uploadedFile); System.out.println("Stored file:\n" + uploaded_file_path); // add url to database table Connection connection = DatabaseUtilities.getConnection(s); Statement statement = connection.createStatement(); // attempt an update String updateData1 = "UPDATE mfe_images SET image_relative_url='" + UPLOADS_RELATIVE_PATH + "/" + item.getName() + "' WHERE user_name = '" + s.getUserName() + "';"; System.out.println("Updating row:\n" + updateData1); if (statement.executeUpdate(updateData1) == 0) { // update failed, we need to add a row String insertData1 = "INSERT INTO mfe_images VALUES ('" + s.getUserName() + "','" + UPLOADS_RELATIVE_PATH + "/" + item.getName() + "')"; System.out.println("Inserting row:\n" + insertData1); statement.executeUpdate(insertData1); } } } } } // now handle normally (if it was a multipart request or now) //super.handleRequest(s); // needed to cut and paste and edit rather than calling super // here so that we could set the encoding type to multipart form data // call createContent first so messages will go somewhere Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("multipart/form-data"); form.addElement(createContent(s)); setContent(form); } catch (Exception e) { System.out.println("Exception caught: " + e); e.printStackTrace(System.out); } }
From source file:org.primefaces.webapp.filter.FileUploadFilter.java
protected FileItemFactory createFileItemFactory(HttpServletRequest httpServletRequest) { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); if (thresholdSize != null) { diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize)); }/* w w w .java 2 s . c om*/ if (uploadDir != null) { diskFileItemFactory.setRepository(new File(uploadDir)); } FileCleaningTracker fileCleaningTracker = FileCleanerCleanup .getFileCleaningTracker(httpServletRequest.getSession().getServletContext()); if (fileCleaningTracker != null) { diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker); } return diskFileItemFactory; }
From source file:org.restlet.example.ext.fileupload.FileUploadServerResource.java
@Post public Representation accept(Representation entity) throws Exception { Representation result = null;/*from w w w.j av a 2s. c o m*/ if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // 1/ Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(factory); // 3/ Request is parsed by the handler which generates a // list of FileItems FileItemIterator fileIterator = upload.getItemIterator(entity); // Process only the uploaded item called "fileToUpload" // and return back boolean found = false; while (fileIterator.hasNext() && !found) { FileItemStream fi = fileIterator.next(); if (fi.getFieldName().equals("fileToUpload")) { // For the matter of sample code, it filters the multo // part form according to the field name. found = true; // consume the stream immediately, otherwise the stream // will be closed. StringBuilder sb = new StringBuilder("media type: "); sb.append(fi.getContentType()).append("\n"); sb.append("file name : "); sb.append(fi.getName()).append("\n"); BufferedReader br = new BufferedReader(new InputStreamReader(fi.openStream())); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } sb.append("\n"); result = new StringRepresentation(sb.toString(), MediaType.TEXT_PLAIN); } } } else { // POST request with no entity. setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } return result; }
From source file:org.sakaiproject.myshowcase.servlet.MyShowcaseFileUploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {// w w w .ja v a 2 s .co m List fileItemsList = null; String input1 = request.getParameter("input1"); String input2 = request.getParameter("input2"); String input4 = request.getParameter("input4"); if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); fileItemsList = servletFileUpload.parseRequest(request); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */ String homeDirId = MyShowcaseConfigValues.getInstance().getFileUploadHomeDir(); File repositoryPath = null; String homeDir = ""; if (homeDirId.equals("ownerName")) { homeDir = getOwnerName(fileItemsList); } else if (homeDirId.equals("ownerId")) { homeDir = getOwnerId(fileItemsList); } repositoryPath = new File(getRepositoryPath(homeDir)); diskFileItemFactory.setRepository(repositoryPath); servletFileUpload.setSizeMax(81920); /* the unit is bytes */ Iterator it = fileItemsList.iterator(); while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { } else { String fileName = fileItem.getName(); fileName = getRepositoryPath(homeDir) + fileName; File uploadedFile = new File(fileName); fileItem.write(uploadedFile); isValidFileType(fileName); } } } else { System.out.println("Not Multipart Request"); } IMyShowcaseService myshowcaseService = getMyShowcaseService(); String ownerId = getOwnerId(fileItemsList); Owner owner = myshowcaseService.getOwnerById(new Long(ownerId)); String aType = getType(fileItemsList); String aTitle = getTitle(fileItemsList); String aDescription = getDescription(fileItemsList); String aDataValue = getDataValue(fileItemsList); // Save Artefact Artefact artefact = new Artefact(); ArtefactDetail artefactDetail = new ArtefactDetail(); ArtefactType artefactType = myshowcaseService.getArtefactTypeByName(aType); artefact.setOwner(owner); artefact.setDescription(aDescription); artefact.setName(aTitle); artefact.setShortDesc(aTitle); artefact.setType(artefactType); artefactDetail.setFileName(aDataValue); artefactDetail.setFileType(getFileType(aDataValue)); artefactDetail.setFilePath(getRepositoryPath(ownerId)); artefactDetail.setDetail(aDataValue); artefact.setArtefactDetail(artefactDetail); myshowcaseService.saveArtefact(artefact); } catch (Exception e) { System.out.println(e.toString()); } // response.setContentType("application/json"); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.write("<html>"); out.write("<head>"); out.write("<title>File Upload</title>"); out.write("</head>"); out.write("<body>"); out.write("File uploaded"); out.write("<script type=\"text/javascript\">"); out.write("parent.$.fancybox.close();"); out.write("</script>"); out.write("</body>"); out.write("</html>"); out.flush(); out.close(); }
From source file:org.sakaiproject.myshowcase.tool.MyShowcaseSaveArtefactFileController.java
protected void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//w ww . j ava 2s.c o m if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = servletFileUpload.parseRequest(request); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */ String homeDirId = MyShowcaseConfigValues.getInstance().getFileUploadHomeDir(); File repositoryPath = null; String homeDir = ""; if (homeDirId.equals("ownerName")) { // homeDir = getOwnerName(fileItemsList) ; } else if (homeDirId.equals("ownerId")) { // homeDir = getOwnerId(fileItemsList) ; } repositoryPath = new File(getRepositoryPath(homeDir)); diskFileItemFactory.setRepository(repositoryPath); servletFileUpload.setSizeMax(81920); /* the unit is bytes */ Iterator it = fileItemsList.iterator(); while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { } else { String fileName = fileItem.getName(); System.out.println("++++ A file(1) = " + fileName); fileName = getRepositoryPath(homeDir) + fileName; System.out.println("++++ A file(2) = " + fileName); File uploadedFile = new File(fileName); fileItem.write(uploadedFile); System.out.println("YES --- File (" + fileName + ") has been written."); System.out.println("==========================="); // isValidFileType(fileName); System.out.println("==========================="); } } } else { System.out.println("Not Multipart Request"); } } catch (Exception e) { System.out.println(e.toString()); } }
From source file:org.sakaiproject.util.RequestFilter.java
/** * if the filter is configured to parse file uploads, AND the request is multipart (typically a file upload), then parse the * request./*from www .j av a2s .co m*/ * * @return If there is a file upload, and the filter handles it, return the wrapped request that has the results of the parsed * file upload. Parses the files using Apache commons-fileuplaod. Exposes the results through a wrapped request. Files * are available like: fileItem = (FileItem) request.getAttribute("myHtmlFileUploadId"); */ protected HttpServletRequest handleFileUpload(HttpServletRequest req, HttpServletResponse resp, List<FileItem> tempFiles) throws ServletException, UnsupportedEncodingException { if (!m_uploadEnabled || !ServletFileUpload.isMultipartContent(req) || req.getAttribute(ATTR_UPLOADS_DONE) != null) { return req; } // mark that the uploads have been parsed, so they aren't parsed again on this request req.setAttribute(ATTR_UPLOADS_DONE, ATTR_UPLOADS_DONE); // Result - map that will be created of request parameters, // parsed parameters, and uploaded files Map map = new HashMap(); // parse using commons-fileupload // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // set the factory parameters: the temp dir and the keep-in-memory-if-smaller threshold if (m_uploadTempDir != null) factory.setRepository(new File(m_uploadTempDir)); if (m_uploadThreshold > 0) factory.setSizeThreshold(m_uploadThreshold); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // set the encoding String encoding = req.getCharacterEncoding(); if (encoding != null && encoding.length() > 0) upload.setHeaderEncoding(encoding); // set the max upload size long uploadMax = -1; if (m_uploadMaxSize > 0) uploadMax = m_uploadMaxSize; // check for request-scoped override to upload.max (value in megs) String override = req.getParameter(CONFIG_UPLOAD_MAX); if (override != null) { try { // get the max in bytes uploadMax = Long.parseLong(override) * 1024L * 1024L; } catch (NumberFormatException e) { M_log.warn(CONFIG_UPLOAD_MAX + " set to non-numeric: " + override); } } // limit to the ceiling if (uploadMax > m_uploadCeiling) { /** * KNL-602 This is the expected behaviour of the request filter honouring the globaly configured * value -DH */ M_log.debug("Upload size exceeds ceiling: " + ((uploadMax / 1024L) / 1024L) + " > " + ((m_uploadCeiling / 1024L) / 1024L) + " megs"); uploadMax = m_uploadCeiling; } // to let commons-fileupload throw the exception on over-max, and also halt full processing of input fields if (!m_uploadContinue) { // TODO: when we switch to commons-fileupload 1.2 // // either per file or overall request, as configured // if (m_uploadMaxPerFile) // { // upload.setFileSizeMax(uploadMax); // } // else // { // upload.setSizeMax(uploadMax); // } upload.setSizeMax(uploadMax); } try { // parse multipart encoded parameters boolean uploadOk = true; List list = upload.parseRequest(req); for (int i = 0; i < list.size(); i++) { FileItem item = (FileItem) list.get(i); if (item.isFormField()) { String str = item.getString(encoding); Object obj = map.get(item.getFieldName()); if (obj == null) { map.put(item.getFieldName(), new String[] { str }); } else if (obj instanceof String[]) { String[] old_vals = (String[]) obj; String[] values = new String[old_vals.length + 1]; for (int i1 = 0; i1 < old_vals.length; i1++) { values[i1] = old_vals[i1]; } values[values.length - 1] = str; map.put(item.getFieldName(), values); } else if (obj instanceof String) { String[] values = new String[2]; values[0] = (String) obj; values[1] = str; map.put(item.getFieldName(), values); } } else { // collect it for delete at the end of the request tempFiles.add(item); // check the max, unless we are letting commons-fileupload throw exception on max exceeded // Note: the continue option assumes the max is per-file, not overall. if (m_uploadContinue && (item.getSize() > uploadMax)) { uploadOk = false; M_log.info("Upload size limit exceeded: " + ((uploadMax / 1024L) / 1024L)); req.setAttribute("upload.status", "size_limit_exceeded"); // TODO: for 1.2 commons-fileupload, switch this to a FileSizeLimitExceededException req.setAttribute("upload.exception", new FileUploadBase.SizeLimitExceededException("", item.getSize(), uploadMax)); req.setAttribute("upload.limit", Long.valueOf((uploadMax / 1024L) / 1024L)); } else { req.setAttribute(item.getFieldName(), item); } } } // unless we had an upload file that exceeded max, set the upload status to "ok" if (uploadOk) { req.setAttribute("upload.status", "ok"); } } catch (FileUploadBase.SizeLimitExceededException ex) { M_log.info("Upload size limit exceeded: " + ((upload.getSizeMax() / 1024L) / 1024L)); // DON'T throw an exception, instead note the exception // so that the tool down-the-line can handle the problem req.setAttribute("upload.status", "size_limit_exceeded"); req.setAttribute("upload.exception", ex); req.setAttribute("upload.limit", Long.valueOf((upload.getSizeMax() / 1024L) / 1024L)); } // TODO: put in for commons-fileupload 1.2 // catch (FileUploadBase.FileSizeLimitExceededException ex) // { // M_log.info("Upload size limit exceeded: " + ((upload.getFileSizeMax() / 1024L) / 1024L)); // // // DON'T throw an exception, instead note the exception // // so that the tool down-the-line can handle the problem // req.setAttribute("upload.status", "size_limit_exceeded"); // req.setAttribute("upload.exception", ex); // req.setAttribute("upload.limit", new Long((upload.getFileSizeMax() / 1024L) / 1024L)); // } catch (FileUploadException ex) { M_log.info("Unexpected exception in upload parsing", ex); req.setAttribute("upload.status", "exception"); req.setAttribute("upload.exception", ex); } // add any parameters that were in the URL - make sure to get multiples for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); String[] values = req.getParameterValues(name); map.put(name, values); } // return a wrapped response that exposes the parsed parameters and files return new WrappedRequestFileUpload(req, map); }
From source file:org.sc.probro.servlets.IndexCreatorServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//www . jav a 2 s . c o m OBOParser parser = null; Map<String, String[]> params = decodedParams(request); UserCredentials creds = new UserCredentials(); String ontologyName = null; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST, "No multipart form data."); } try { File repository = new File(System.getProperty("java.io.tmpdir")); // Create a factory for disk-based file items //DiskFileItemFactory factory = new DiskFileItemFactory(); DiskFileItemFactory factory = newDiskFileItemFactory(getServletContext(), repository); // Set factory constraints factory.setSizeThreshold(10 * MB); //factory.setRepository(yourTempDirectory); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(50 * MB); // Parse the request List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { String formName = item.getFieldName(); String formValue = item.getString(); Log.info(String.format("%s=%s", formName, formValue)); if (formName.equals("ontology_name")) { ontologyName = formValue; } } else { String formName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (formName.equals("ontology_file")) { Log.info(String.format("fileName=%s, contentType=%s, size=%d", fileName, contentType, sizeInBytes)); if (fileName.length() > 0) { InputStream uploadedStream = item.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(uploadedStream)); parser = new OBOParser(); parser.parse(reader); reader.close(); } } else { Log.warn(String.format("unknown file: %s", formName)); } } } } catch (IOException e) { throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (FileUploadException e) { throw new BrokerException(e); } if (ontologyName == null) { throw new BadRequestException("No ontology_name field given."); } OBOOntology ontology = null; try { if (parser != null) { Log.info(String.format("Retrieving OBO ontology from file.")); // file was uploaded ontology = parser.getOntology(); } else { // try to get it from teh sparql endpoint Log.info(String.format("No OBO file uploaded, reading from Sparql endpoint instead.")); OBOBuilder builder = new OBOBuilder(oboSparql); ontology = builder.buildOntology(ontologyName); } } catch (IOException e) { throw new BrokerException(e); } Broker broker = getBroker(); try { Ontology ont = broker.createOntology(creds, ontologyName, ontology); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text"); response.getWriter().print(ont.id); } finally { broker.close(); } } catch (BrokerException e) { handleException(response, e); return; } }
From source file:org.seasar.teeda.extension.filter.MultipartFormDataRequestWrapper.java
/** * @param request /*from www . j a v a 2s . c om*/ * @param maxFileSize * @param thresholdSize * @param repositoryPath */ public MultipartFormDataRequestWrapper(final HttpServletRequest request, final int maxSize, final int maxFileSize, final int thresholdSize, final String repositoryPath) { super(request); final DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(thresholdSize); if (!StringUtil.isEmpty(repositoryPath)) { factory.setRepository(new File(repositoryPath)); } fileUpload = new ServletFileUpload(factory); fileUpload.setSizeMax(maxSize); fileUpload.setFileSizeMax(maxFileSize); parseRequest(request); }
From source file:org.seasar.teeda.extension.portlet.MultipartFormDataActionRequestWrapper.java
/** * @param request /* w ww . j a va 2 s .com*/ * @param maxSize * @param maxFileSize * @param thresholdSize * @param repositoryPath */ public MultipartFormDataActionRequestWrapper(final ActionRequest request, final int maxSize, final int maxFileSize, final int thresholdSize, final String repositoryPath, final String encoding) { this.request = request; final DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(thresholdSize); if (!StringUtil.isEmpty(repositoryPath)) { factory.setRepository(new File(repositoryPath)); } fileUpload = new PortletFileUpload(factory); fileUpload.setSizeMax(maxSize); fileUpload.setFileSizeMax(maxFileSize); this.encoding = encoding; parseRequest(request); }
From source file:org.signserver.web.GenericProcessServlet.java
/** * Handles http post.//from w ww . java 2 s . c o m * * @param req servlet request * @param res servlet response * * @throws IOException input/output error * @throws ServletException error */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { LOG.debug(">doPost()"); int workerId = 1; byte[] data = null; String fileName = null; String pdfPassword = null; boolean workerRequest = false; if (LOG.isDebugEnabled()) { LOG.debug("Received a request with length: " + req.getContentLength()); } final String workerNameOverride = (String) req.getAttribute(WORKERNAME_PROPERTY_OVERRIDE); if (workerNameOverride != null) { workerId = getWorkerSession().getWorkerId(workerNameOverride); workerRequest = true; } final long maxUploadSize = getMaxUploadSize(); ProcessType processType = ProcessType.signDocument; final MetaDataHolder metadataHolder = new MetaDataHolder(); if (ServletFileUpload.isMultipartContent(req)) { final DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(Integer.MAX_VALUE); // Don't write to disk final ServletFileUpload upload = new ServletFileUpload(factory); // Limit the maximum size of input upload.setSizeMax(maxUploadSize); try { final List items = upload.parseRequest(req); final Iterator iter = items.iterator(); FileItem fileItem = null; String encoding = null; while (iter.hasNext()) { final Object o = iter.next(); if (o instanceof FileItem) { final FileItem item = (FileItem) o; if (item.isFormField()) { if (!workerRequest) { if (WORKERNAME_PROPERTY_NAME.equals(item.getFieldName())) { if (LOG.isDebugEnabled()) { LOG.debug("Found a signerName in the request: " + item.getString()); } workerId = getWorkerSession().getWorkerId(item.getString()); } else if (WORKERID_PROPERTY_NAME.equals(item.getFieldName())) { if (LOG.isDebugEnabled()) { LOG.debug("Found a signerId in the request: " + item.getString()); } try { workerId = Integer.parseInt(item.getString()); } catch (NumberFormatException ignored) { } } } final String itemFieldName = item.getFieldName(); if (PDFPASSWORD_PROPERTY_NAME.equals(itemFieldName)) { if (LOG.isDebugEnabled()) { LOG.debug("Found a pdfPassword in the request."); } pdfPassword = item.getString("ISO-8859-1"); } else if (PROCESS_TYPE_PROPERTY_NAME.equals(itemFieldName)) { final String processTypeAttribute = item.getString("ISO-8859-1"); if (LOG.isDebugEnabled()) { LOG.debug("Found process type in the request: " + processTypeAttribute); } if (processTypeAttribute != null) { try { processType = ProcessType.valueOf(processTypeAttribute); } catch (IllegalArgumentException e) { sendBadRequest(res, "Illegal process type: " + processTypeAttribute); return; } } else { processType = ProcessType.signDocument; } } else if (ENCODING_PROPERTY_NAME.equals(itemFieldName)) { encoding = item.getString("ISO-8859-1"); } else if (isFieldMatchingMetaData(itemFieldName)) { try { metadataHolder.handleMetaDataProperty(itemFieldName, item.getString("ISO-8859-1")); } catch (IOException e) { sendBadRequest(res, "Malformed properties given using REQUEST_METADATA."); return; } } } else { // We only care for one upload at a time right now if (fileItem == null) { fileItem = item; } } } } if (fileItem == null) { sendBadRequest(res, "Missing file content in upload"); return; } else { fileName = fileItem.getName(); data = fileItem.get(); // Note: Reads entiry file to memory if (encoding != null && !encoding.isEmpty()) { if (ENCODING_BASE64.equalsIgnoreCase(encoding)) { if (LOG.isDebugEnabled()) { LOG.debug("Decoding base64 data"); } data = Base64.decode(data); } else { sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding); return; } } } } catch (FileUploadBase.SizeLimitExceededException ex) { LOG.error(HTTP_MAX_UPLOAD_SIZE + " exceeded: " + ex.getLocalizedMessage()); res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "Maximum content length is " + maxUploadSize + " bytes"); return; } catch (FileUploadException ex) { throw new ServletException("Upload failed", ex); } } else { if (!workerRequest) { String name = req.getParameter(WORKERNAME_PROPERTY_NAME); if (name != null) { if (LOG.isDebugEnabled()) { LOG.debug("Found a signerName in the request: " + name); } workerId = getWorkerSession().getWorkerId(name); } String id = req.getParameter(WORKERID_PROPERTY_NAME); if (id != null) { if (LOG.isDebugEnabled()) { LOG.debug("Found a signerId in the request: " + id); } workerId = Integer.parseInt(id); } } final Enumeration<String> params = req.getParameterNames(); while (params.hasMoreElements()) { final String property = params.nextElement(); if (PDFPASSWORD_PROPERTY_NAME.equals(property)) { pdfPassword = (String) req.getParameter(PDFPASSWORD_PROPERTY_NAME); if (LOG.isDebugEnabled()) { LOG.debug("Found a pdfPassword in the request."); } } else if (isFieldMatchingMetaData(property)) { try { metadataHolder.handleMetaDataProperty(property, req.getParameter(property)); } catch (IOException e) { sendBadRequest(res, "Malformed properties given using REQUEST_METADATA."); return; } } } final String processTypeAttribute = (String) req.getParameter(PROCESS_TYPE_PROPERTY_NAME); if (processTypeAttribute != null) { try { processType = ProcessType.valueOf(processTypeAttribute); if (LOG.isDebugEnabled()) { LOG.debug("Found process type in the request: " + processType.name()); } } catch (IllegalArgumentException e) { sendBadRequest(res, "Illegal process type: " + processTypeAttribute); return; } } else { processType = ProcessType.signDocument; } if (METHOD_GET.equalsIgnoreCase(req.getMethod()) || (req.getContentType() != null && req.getContentType().contains(FORM_URL_ENCODED))) { LOG.debug("Request is FORM_URL_ENCODED"); if (req.getParameter(DATA_PROPERTY_NAME) == null) { sendBadRequest(res, "Missing field 'data' in request"); return; } data = req.getParameter(DATA_PROPERTY_NAME).getBytes(); String encoding = req.getParameter(ENCODING_PROPERTY_NAME); if (encoding != null && !encoding.isEmpty()) { if (ENCODING_BASE64.equalsIgnoreCase(encoding)) { if (LOG.isDebugEnabled()) { LOG.debug("Decoding base64 data"); } data = Base64.decode(data); } else { sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding); return; } } } else { // Pass-through the content to be handled by worker if // unknown content-type if (LOG.isDebugEnabled()) { LOG.debug("Request Content-type: " + req.getContentType()); } // Get an input stream and read the bytes from the stream InputStream in = req.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { os.write(buf, 0, len); } in.close(); os.close(); data = os.toByteArray(); } } if (LOG.isDebugEnabled()) { LOG.debug("Request of type: " + processType.name()); } // Limit the maximum size of input if (data.length > maxUploadSize) { LOG.error("Content length exceeds " + maxUploadSize + ", not processed: " + req.getContentLength()); res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "Maximum content length is " + maxUploadSize + " bytes"); } else { processRequest(req, res, workerId, data, fileName, pdfPassword, processType, metadataHolder); } LOG.debug("<doPost()"); }