protected ExtendedMap parseForm(HttpServletRequest request, boolean keepEmpty) throws FileUploadException, IOException { if (FileUpload.isMultipartContent(request)) { return parseMultiPartRequest(request); } else { return parseSimpleRequest(request, keepEmpty); } }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { chain.doFilter(request, response); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest); if (!isMultipartContent) { chain.doFilter(request, response); return; } DiskFileUpload upload = new DiskFileUpload(); if (repositoryPath != null) upload.setRepositoryPath(repositoryPath); try { List list = upload.parseRequest(httpRequest); final Map map = new HashMap(); for (int i = 0; i < list.size(); i++) { FileItem item = (FileItem) list.get(i); String str = item.getString(); if (item.isFormField()) map.put(item.getFieldName(), new String[] {str}); else httpRequest.setAttribute(item.getFieldName(), item); } chain.doFilter( new HttpServletRequestWrapper(httpRequest) { public Map getParameterMap() { return map; } public String[] getParameterValues(String name) { Map map = getParameterMap(); return (String[]) map.get(name); } public String getParameter(String name) { String[] params = getParameterValues(name); if (params == null) return null; return params[0]; } public Enumeration getParameterNames() { Map map = getParameterMap(); return Collections.enumeration(map.keySet()); } }, response); } catch (FileUploadException ex) { ServletException servletEx = new ServletException(); servletEx.initCause(ex); throw servletEx; } }
/** * Parse the given servlet request, resolving its multipart elements. * @param request the request to parse * @return the parsing result * @throws MultipartException if multipart resolution failed. */ protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException { String[] encoding = determineEncoding(request); String contentType = request.getContentType(); if(contentType != null && !contentType.equals(MultipartResolver.mimetype_application_octet_stream)) { FileUpload fileUpload = prepareFileUpload(encoding[1] == null?encoding[0]:encoding[1]); try { List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request); return parseFileItems(fileItems, encoding,request); } catch (FileUploadBase.SizeLimitExceededException ex) { throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex); } catch (FileUploadException ex) { throw new MultipartException("Could not parse multipart servlet request", ex); } } else { return parseOctetFileItems(request); } }
/** * Determine an appropriate FileUpload instance for the given encoding. * * <p>Default implementation returns the shared FileUpload instance if the encoding matches, else * creates a new FileUpload instance with the same configuration other than the desired encoding. * * @param encoding the character encoding to use * @return an appropriate FileUpload instance. */ protected FileUpload prepareFileUpload(String encoding) { FileUpload fileUpload = getFileUpload(); FileUpload actualFileUpload = fileUpload; // Use new temporary FileUpload instance if the request specifies // its own encoding that does not match the default encoding. if (encoding != null && !encoding.equals(fileUpload.getHeaderEncoding())) { actualFileUpload = newFileUpload(getFileItemFactory()); actualFileUpload.setSizeMax(fileUpload.getSizeMax()); actualFileUpload.setHeaderEncoding(encoding); } return actualFileUpload; }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { boolean isMultipart = FileUpload.isMultipartContent(req); Hashtable dv = new Hashtable(); String user = null; String password = null; String sql = null; String dfo = null; String enc = null; if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(mU); try { FileItemIterator iter = upload.getItemIterator(req); // List<FileItem> items = upload.parseRequest(req); while (iter.hasNext()) { FileItemStream item = iter.next(); // for (int ct = 0;ct < items.size();ct++){ // FileItem item = (FileItem)items.get(ct); String name = item.getName(); // (name + " jiql UREEAD 1aay " + item.isFormField() + ":" + name.equals("directValues")); InputStream stream = item.openStream(); // InputStream stream = item.getInputStream(); //// (name + " jiql UREEAD 1 " + stream.available()); // byte[] b = StreamUtil.readBytes(stream); if (name.equals("directValues")) { // (stream.available() + " jiql UREEAD " ); // ByteArrayInputStream bout = new ByteArrayInputStream(b); ObjectInputStream dout = new ObjectInputStream(stream); // ObjectInputStream dout = new ObjectInputStream(bout); dv = (Hashtable) dout.readObject(); } } } catch (Exception e) { tools.util.LogMgr.err("JS.readDV " + e.toString()); e.printStackTrace(); } // ("$$$ DV " + dv); Hashtable pars = (Hashtable) dv.get("parameters"); if (pars != null) { Enumeration en = pars.keys(); while (en.hasMoreElements()) { String n = en.nextElement().toString(); // ("PARSMS " + n); if (n.equals("query")) sql = pars.get(n).toString(); else if (n.equals("password")) password = pars.get(n).toString(); else if (n.equals("user")) user = pars.get(n).toString(); else if (n.equals("date.format")) dfo = pars.get(n).toString(); else if (n.equals("encoding")) enc = pars.get(n).toString(); } } } if (user == null) user = req.getParameter("user"); if (password == null) password = req.getParameter("password"); if (!StringUtil.isRealString(user) || !StringUtil.isRealString(password)) { resp.sendError(403, "Invalid User or Password"); return; } if (!StringUtil.isRealString(theUser) || !StringUtil.isRealString(thePassword)) { resp.sendError(403, "Invalid User OR Password"); return; } Connection Conn = null; Hashtable h = new Hashtable(); h.put("remote", "true"); try { // NameValuePairs p = new NameValuePairs(ps); if (!user.equals(theUser) || !password.equals(thePassword)) { resp.sendError(403, "Invalid User OR Invalid Password"); return; } // throw new ServletException("Invalid User OR Password"); if (sql == null) sql = req.getParameter("query"); // ( "THE SQL " + sql); NameValuePairs nvp = new NameValuePairs(); if (dfo == null) dfo = req.getParameter("date.format"); if (dfo != null) nvp.put("date.format", dfo); if (enc == null) enc = req.getParameter("encoding"); if (enc != null) nvp.put("encoding", enc); Conn = get(nvp); org.jiql.jdbc.Statement Stmt = (org.jiql.jdbc.Statement) Conn.createStatement(); Stmt.setDirectValues(dv); Stmt.execute(sql); org.jiql.jdbc.ResultSet res = (org.jiql.jdbc.ResultSet) Stmt.getResultSet(); if (res != null) { if (res.getResults() != null) h.put("results", res.getResults()); if (res.getSQLParser() != null) h.put("sqlparser", res.getSQLParser()); } else h.put("sqlparser", Stmt.getSQLParser()); // h.put("remote","true"); resp.setContentType("binary/object"); // if (enc != null) // resp.setCharacterEncoding(enc); OutputStream fos = resp.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(h); // resp.getWriter(). ("result" + h); } catch (Exception ex) { org.jiql.util.JGUtil.olog(ex); ex.printStackTrace(); tools.util.LogMgr.err("JIQLServlet " + ex.toString()); JGException je = null; if (ex instanceof JGException) je = (JGException) ex; else je = new JGException(ex.toString()); h.put("error", je); resp.setContentType("binary/object"); OutputStream fos = resp.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(h); // throw new ServletException(ex.toString()); } finally { if (Conn != null) try { Conn.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
/** * This method will upload files and store them under the dest_path. * * <p>File names are formed by <thread_name>_<counter>_originalFileName * * <p>The returned hashmap contains a list of name value pairs, where a value * * <p>can either be normal form input parameter or the uploaded file path. * * @param HttpServletRequest request * @param String dest_path upload destination path * @return HashMap */ public static HashMap parseMultipartRequest(HttpServletRequest request, String dest_path) { HashMap hmfield = new HashMap(); String threadname = Thread.currentThread().getName(); RequestContext requestContext = new ServletRequestContext(request); int filemaxsize = LPropertyManager.getInt("file.upload.maxsize", 2000000); if (FileUpload.isMultipartContent(requestContext)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(dest_path)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(filemaxsize); List items = new ArrayList(); try { items = upload.parseRequest(request); } catch (FileUploadException e1) { gLogger.fatalize("LUploadUtil", e1.getMessage()); } Iterator it = items.iterator(); while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { hmfield.put(fileItem.getFieldName(), fileItem.getString()); } else { if (fileItem.getName() != null && fileItem.getSize() != 0) { File fullFile = new File(fileItem.getName()); String tempfile = dest_path + File.separator + threadname + "_" + tick() + "_" + fullFile.getName(); hmfield.put(fileItem.getFieldName(), tempfile); hmfield.put("originalfilename", fullFile.getName()); File newFile = new File(tempfile); try { fileItem.write(newFile); } catch (Exception e) { gLogger.fatalize("LUploadUtil", e.getMessage()); } } else { gLogger.errorLog("No file is selected or the file is empty!"); } } } } return hmfield; }
/** * A Helper method which assert whether the HTTP content received in the HTTP monitor is a * multi-part form data, with basic-auth and well-formed partnership operation request. */ private void assertHttpRequestReceived() throws Exception { // Debug print information. Map headers = monitor.getHeaders(); // #0 Assertion assertFalse("No HTTP header found in the captured data.", headers.isEmpty()); Map.Entry tmp = null; Iterator itr = null; itr = headers.entrySet().iterator(); logger.info("Header information"); while (itr.hasNext()) { tmp = (Map.Entry) itr.next(); logger.info(tmp.getKey() + " : " + tmp.getValue()); } // #1 Check BASIC authentication value. String basicAuth = (String) headers.get("Authorization"); // #1 Assertion assertNotNull("No Basic Authentication found in the HTTP Header.", basicAuth); String[] authToken = basicAuth.split(" "); // There are 2 token, one is the "Basic" and another is the base64 auth value. assertTrue(authToken.length == 2); assertTrue("Missing basic auth prefix 'Basic'", authToken[0].equalsIgnoreCase("Basic")); // #1 Decode the base64 authentication value to see whether it is "corvus:corvus". String decodedCredential = new String(new BASE64Decoder().decodeBuffer(authToken[1]), "UTF-8"); assertEquals("Invalid basic auth content", USER_NAME + ":" + PASSWORD, decodedCredential); // #2 Check content Type String contentType = monitor.getContentType(); String mediaType = contentType.split(";")[0]; assertEquals("Invalid content type", "multipart/form-data", mediaType); // #3 Check the multi-part content. // Make a request context that bridge the content from our monitor to FileUpload library. RequestContext rc = new RequestContext() { public String getCharacterEncoding() { return "charset=ISO-8859-1"; } public int getContentLength() { return monitor.getContentLength(); } public String getContentType() { return monitor.getContentType(); } public InputStream getInputStream() { return monitor.getInputStream(); } }; FileUpload multipartParser = new FileUpload(); FileItemIterator item = multipartParser.getItemIterator(rc); FileItemStream fstream = null; /* * For each field in the partnership, we have to check the existence of the * associated field in the HTTP request. Also we check whether the content * of that web form field has same data to the field in the partnership. */ itr = this.target.getPartnershipMapping().entrySet().iterator(); Map data = ((KVPairData) this.target.properties).getProperties(); Map.Entry e; // an entry representing the partnership data to web form name mapping. String formParamName; // a temporary pointer pointing to the value in the entry. Object dataValue; // a temporary pointer pointing to the value in the partnership data. while (itr.hasNext()) { e = (Map.Entry) itr.next(); formParamName = (String) e.getValue(); // Add new part if the mapped key is not null. if (formParamName != null) { assertTrue("Insufficient number of web form parameter hit.", item.hasNext()); // Get the next multi-part element. fstream = item.next(); // Assert field name assertEquals("Missed web form parameter ?", formParamName, fstream.getFieldName()); // Assert field content dataValue = data.get(e.getKey()); if (dataValue instanceof String) { // Assert content equal. assertEquals((String) dataValue, IOHandler.readString(fstream.openStream(), null)); } else if (dataValue instanceof byte[]) { byte[] expectedBytes = (byte[]) dataValue; byte[] actualBytes = IOHandler.readBytes(fstream.openStream()); // Assert byte length equal assertEquals(expectedBytes.length, actualBytes.length); for (int j = 0; j < expectedBytes.length; j++) assertEquals(expectedBytes[j], actualBytes[j]); } else { throw new IllegalArgumentException("Invalid content found in multipart."); } // Log information. logger.info( "Field name found and verifed: " + fstream.getFieldName() + " content type:" + fstream.getContentType()); } } /* Check whether the partnership operation in the HTTP request is expected as i thought */ assertTrue("Missing request_action ?!", item.hasNext()); fstream = item.next(); assertEquals("request_action", fstream.getFieldName()); // Assert the request_action has same content the operation name. Map partnershipOpMap = this.target.getPartnershipOperationMapping(); assertEquals( partnershipOpMap.get(new Integer(this.target.getExecuteOperation())), IOHandler.readString(fstream.openStream(), null)); }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // not connected if (request.getSession().getAttribute("user") == null) { request.getSession().setAttribute("backTo", "post_application"); request.setAttribute("errorMessage", "error_not_logged_applications"); URLHelper.redirectTo(Page.connection, request, response); } // form is ok else if (FileUpload.isMultipartContent(request)) { String msg = "application_posted"; Connection connection = null; MessageProducer messageProducer = null; try { connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); messageProducer = session.createProducer(queue); ObjectMessage message = session.createObjectMessage(); // here we create NewsEntity, that will be sent in JMS message Application e = new Application(); // upload File and Icon on the server UploadFileHelper.uploadApplication(request, e, getServletContext().getRealPath("/")); // create the new app appFacade.create(e); // link app to User LinuxStoreUser user = (LinuxStoreUser) request.getSession().getAttribute("user"); e = appFacade.findByName(e.getName()); e.setOwner(user); appFacade.edit(e); List<Application> applist = new LinkedList<Application>(); applist.add(e); user.addToMyApplications(applist); userFacade.edit(user); // message.setObject(new UserAndApp(user,e)); // messageProducer.send(message); } catch (Exception ex) { msg = ex.getMessage(); // msg = "application_not_posted"; } finally { try { messageProducer.close(); connection.close(); } catch (JMSException ex) { // do nothing } } if (msg.equals("application_posted")) { request.setAttribute("confirmationMessage", msg); URLHelper.redirectTo(Page.confirmation, request, response); } else { request.setAttribute("errorMessage", msg); request.setAttribute("categories", Category.values()); URLHelper.redirectTo(Page.post_application, request, response); } } // access to form else { request.setAttribute("fileTypes", UploadFileHelper.listOfAppExtensions); request.setAttribute("imgTypes", UploadFileHelper.listOfImgExtensions); request.setAttribute("categories", Category.values()); URLHelper.redirectTo(Page.post_application, request, response); } }