List of usage examples for org.apache.commons.fileupload.servlet ServletRequestContext ServletRequestContext
public ServletRequestContext(HttpServletRequest request)
From source file:net.cbtltd.server.UploadFileService.java
/** * Handles upload file requests is in a page submitted by a HTTP POST method. * Form field values are extracted into a parameter list to set an associated Text instance. * 'File' type merely saves file and creates associated db record having code = file name. * Files may be rendered by reference in a browser if the browser is capable of the file type. * 'Image' type creates and saves thumbnail and full size jpg images and creates associated * text record having code = full size file name. The images may be viewed by reference in a browser. * 'Blob' type saves file and creates associated text instance having code = full size file name * and a byte array data value equal to the binary contents of the file. * * @param request the HTTP upload request. * @param response the HTTP response.//from w ww. j a va 2 s . c o m * @throws ServletException signals that an HTTP exception has occurred. * @throws IOException signals that an I/O exception has occurred. */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletRequestContext ctx = new ServletRequestContext(request); if (ServletFileUpload.isMultipartContent(ctx) == false) { sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The servlet can only handle multipart requests.")); return; } LOG.debug("UploadFileService doPost request " + request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); LOG.debug("\n doPost upload " + upload); SqlSession sqlSession = RazorServer.openSession(); try { HashMap<String, String> params = new HashMap<String, String>(); for (FileItem item : (List<FileItem>) upload.parseRequest(request)) { if (item.isFormField()) { // add for field value to parameter list String param = item.getFieldName(); String value = item.getString(); params.put(param, value); } else if (item.getSize() > 0) { // process uploaded file // String fn = RazorServer.ROOT_DIRECTORY + item.getFieldName(); // input file path String fn = RazorConfig.getImageURL() + item.getFieldName(); // input file path LOG.debug("doPost fn " + fn); byte[] data = item.get(); String mimeType = item.getContentType(); String productId = item.getFieldName(); Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(productId); while (m.find()) { productId = m.group(); LOG.debug("Image uploaded for Product ID: " + productId); break; } // TO DO - convert content type to mime..also check if uploaded type is image // getMagicMatch accepts Files or byte[], // which is nice if you want to test streams MagicMatch match = null; try { match = parser.getMagicMatch(data, false); LOG.debug("Mime type of image: " + match.getMimeType()); } catch (MagicParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MagicMatchNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MagicException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (match != null) { mimeType = match.getMimeType(); } // image processor logic needs to know about the format of the image String contentType = RazorConfig.getMimeExtension(mimeType); if (StringUtils.isNotEmpty(contentType)) { ImageService.uploadImages(sqlSession, productId, item.getFieldName(), params.get(Text.FILE_NOTES), data, contentType); LOG.debug("doPost commit params " + params); sqlSession.commit(); } else { // unknown content/mime type...do not upload the file sendResponse(response, new FormResponse(HttpServletResponse.SC_BAD_REQUEST, "File type - " + contentType + " is not supported")); } // File file = new File(fn); // output file name // File tempf = File.createTempFile(Text.TEMP_FILE, ""); // item.write(tempf); // file.delete(); // tempf.renameTo(file); // int fullsizepixels = Integer.valueOf(params.get(Text.FULLSIZE_PIXELS)); // if (fullsizepixels <= 0) {fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;} // int thumbnailpixels = Integer.valueOf(params.get(Text.THUMBNAIL_PIXELS)); // if (thumbnailpixels <= 0) {thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;} // // setText(sqlSession, file, fn, params.get(Text.FILE_NAME), params.get(Text.FILE_TYPE), params.get(Text.FILE_NOTES), Language.EN, fullsizepixels, thumbnailpixels); } } sendResponse(response, new FormResponse(HttpServletResponse.SC_ACCEPTED, "OK")); } catch (Throwable x) { sqlSession.rollback(); sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage())); LOG.error("doPost error " + x.getMessage()); } finally { sqlSession.close(); } }
From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java
private FileItemIterator parseUpload(int pLength, InputStream pStream) throws FileUploadException, IOException { String contentType = "multipart/form-data; boundary=---1234"; FileUploadBase upload = new ServletFileUpload(); upload.setFileItemFactory(new EncryptedFileItemFactory()); HttpServletRequest request = new MockHttpServletRequest(pStream, pLength, contentType); return upload.getItemIterator(new ServletRequestContext(request)); }
From source file:lucee.runtime.type.scope.FormImpl.java
private void initializeMultiPart(PageContext pc, boolean scriptProteced) { // get temp directory Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory(); Resource tempFile;/*from w w w . j a va 2 s .c om*/ // Create a new file upload handler final String encoding = getEncoding(); FileItemFactory factory = tempDir instanceof File ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir) : new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest()); HttpServletRequest req = pc.getHttpServletRequest(); ServletRequestContext context = new ServletRequestContext(req) { public String getCharacterEncoding() { return encoding; } }; // Parse the request try { FileItemIterator iter = upload.getItemIterator(context); //byte[] value; InputStream is; ArrayList<URLItem> list = new ArrayList<URLItem>(); while (iter.hasNext()) { FileItemStream item = iter.next(); is = IOUtil.toBufferedInputStream(item.openStream()); if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) { list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false)); } else { tempFile = tempDir.getRealResource(getFileName()); fileItems.put(item.getFieldName().toLowerCase(), new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName())); String value = tempFile.toString(); IOUtil.copy(is, tempFile, true); list.add(new URLItem(item.getFieldName(), value, false)); } } raw = list.toArray(new URLItem[list.size()]); fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); } catch (Exception e) { //throw new PageRuntimeException(Caster.toPageException(e)); fillDecodedEL(new URLItem[0], encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); initException = e; } }
From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java
private List<FileItem> parseUpload(InputStream pStream, int pLength) throws FileUploadException { String contentType = "multipart/form-data; boundary=---1234"; FileUploadBase upload = new ServletFileUpload(); upload.setFileItemFactory(new EncryptedFileItemFactory()); HttpServletRequest request = new MockHttpServletRequest(pStream, pLength, contentType); List<FileItem> fileItems = upload.parseRequest(new ServletRequestContext(request)); return fileItems; }
From source file:com.gtwm.pb.servlets.ServletUtilMethods.java
/** * Like HttpServlet#getRequestQuery(request) but works for POST as well as * GET: In the case of POST requests, constructs a query string from * parameter names & values/*from ww w . j a v a 2s . co m*/ * * @see HttpServletRequest#getQueryString() */ public static String getRequestQuery(HttpServletRequest request) { String requestQuery = request.getQueryString(); if (requestQuery != null) { return "GET: " + requestQuery; } if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { return "POST: file upload"; } requestQuery = "POST: "; Map<String, String[]> parameterMap = request.getParameterMap(); for (Map.Entry<String, String[]> parameterEntry : parameterMap.entrySet()) { requestQuery += "&" + parameterEntry.getKey() + "=" + parameterEntry.getValue()[0]; } return requestQuery; }
From source file:ea.ejb.AbstractFacade.java
/** * Provide the ability to cache multi-part items in a variable to save * re-parsing//from ww w. ja v a2 s .co m */ public static List<FileItem> getMultipartItems(HttpServletRequest request) { List<FileItem> multipartItems = new LinkedList<FileItem>(); if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { multipartItems = upload.parseRequest(request); } catch (FileUploadException fuex) { System.out.println("Error parsing multi-part form data: " + fuex.getMessage()); } } return multipartItems; }
From source file:ba.nwt.ministarstvo.server.fileUpload.FileUploadServlet.java
@SuppressWarnings("unchecked") @Override//from www. jav a2s .co m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletRequestContext ctx = new ServletRequestContext(request); if (ServletFileUpload.isMultipartContent(ctx) == false) { sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The servlet can only handle multipart requests." + " This is probably a software bug.")); return; } // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> i = items.iterator(); HashMap<String, String> params = new HashMap<String, String>(); HashMap<String, File> files = new HashMap<String, File>(); while (i.hasNext() == true) { FileItem item = i.next(); if (item.isFormField() == true) { String param = item.getFieldName(); String value = item.getString(); // System.out.println(getClass().getName() + ": param=" // + param + ", value=" + value); params.put(param, value); } else { if (item.getSize() == 0) { continue; // ignore zero-length files } File tempf = File.createTempFile(request.getRemoteAddr() + "-" + item.getFieldName() + "-", ""); item.write(tempf); files.put(item.getFieldName(), tempf); // System.out.println("Creating temporary file " // + tempf.getAbsolutePath()); } } // populate, invoke the listener, delete files if needed, // send response FileUploadAction action = (FileUploadAction) actionClass.newInstance(); BeanUtils.populate(action, params); // populate the object action.setFileList(files); FormResponse resp = action.onSubmit(this, request); if (resp.isDeleteFiles()) { Iterator<Map.Entry<String, File>> j = files.entrySet().iterator(); while (j.hasNext()) { Map.Entry<String, File> entry = j.next(); File f = entry.getValue(); f.delete(); } } sendResponse(response, resp); return; } catch (Exception e) { e.printStackTrace(); sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getClass().getName() + ": " + e.getMessage())); } }
From source file:com.aliasi.demo.framework.DemoServlet.java
void generateOutput(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { InputStream in = null;/* w w w . j a v a 2 s . co m*/ OutputStream out = null; try { response.setContentType(mDemo.responseType()); out = response.getOutputStream(); @SuppressWarnings("unchecked") // bad inherited API from commons Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap()); String reqContentType = request.getContentType(); if (reqContentType == null || reqContentType.startsWith("text/plain")) { properties.setProperty("inputType", "text/plain"); String reqCharset = request.getCharacterEncoding(); if (reqCharset != null) properties.setProperty("inputCharset", reqCharset); in = request.getInputStream(); } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) { String codedText = request.getParameter("inputText"); byte[] bytes = codedText.getBytes("ISO-8859-1"); in = new ByteArrayInputStream(bytes); } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload uploader = new ServletFileUpload(factory); @SuppressWarnings("unchecked") // bad commons API List<FileItem> items = (List<FileItem>) uploader.parseRequest(request); Iterator<FileItem> it = items.iterator(); while (it.hasNext()) { log("found item"); FileItem item = it.next(); if (item.isFormField()) { String key = item.getFieldName(); String val = item.getString(); properties.setProperty(key, val); } else { byte[] bytes = item.get(); in = new ByteArrayInputStream(bytes); } } } else { System.out.println("unexpected content type"); String msg = "Unexpected request content" + reqContentType; throw new ServletException(msg); } mDemo.process(in, out, properties); } catch (FileUploadException e) { throw new ServletException(e); } finally { Streams.closeQuietly(in); Streams.closeQuietly(out); } }
From source file:de.betterform.agent.web.servlet.HttpRequestHandler.java
/** * Parses a HTTP request. Returns an array containing maps for upload * controls, other controls, repeat indices, and trigger. The individual * maps may be null in case no corresponding parameters appear in the * request.//from w w w. j a v a2 s . c om * * @param request a HTTP request. * @return an array of maps containing the parsed request parameters. * @throws FileUploadException if an error occurred during file upload. * @throws UnsupportedEncodingException if an error occurred during * parameter value decoding. */ protected Map[] parseRequest(HttpServletRequest request) throws FileUploadException, UnsupportedEncodingException { Map[] parameters = new Map[4]; if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { UploadListener uploadListener = new UploadListener(request, this.sessionKey); DiskFileItemFactory factory = new MonitoredDiskFileItemFactory(uploadListener); factory.setRepository(new File(this.uploadRoot)); ServletFileUpload upload = new ServletFileUpload(factory); String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } Iterator iterator = upload.parseRequest(request).iterator(); FileItem item; while (iterator.hasNext()) { item = (FileItem) iterator.next(); if (LOGGER.isDebugEnabled()) { if (item.isFormField()) { LOGGER.debug( "request param: " + item.getFieldName() + " - value='" + item.getString() + "'"); } else { LOGGER.debug("file in request: " + item.getName()); } } parseMultiPartParameter(item, encoding, parameters); } } else { Enumeration enumeration = request.getParameterNames(); String name; String[] values; while (enumeration.hasMoreElements()) { name = (String) enumeration.nextElement(); values = request.getParameterValues(name); parseURLEncodedParameter(name, values, parameters); } } return parameters; }
From source file:axiom.servlet.AbstractServletClient.java
/** * Handle a request./* w w w. ja va2 s .c o m*/ * * @param request ... * @param response ... * * @throws ServletException ... * @throws IOException ... */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String httpMethod = request.getMethod(); if (!"POST".equalsIgnoreCase(httpMethod) && !"GET".equalsIgnoreCase(httpMethod)) { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "HTTP Method " + httpMethod + " not supported."); return; } RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request)); try { // get the character encoding String encoding = request.getCharacterEncoding(); if (encoding == null) { // no encoding from request, use the application's charset encoding = getApplication().getCharset(); } // read and set http parameters parseParameters(request, reqtrans, encoding); List uploads = null; ServletRequestContext reqcx = new ServletRequestContext(request); if (ServletFileUpload.isMultipartContent(reqcx)) { // get session for upload progress monitoring UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans); try { uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding); } catch (Exception upx) { System.err.println("Error in file upload: " + upx); if (uploadSoftfail) { String msg = upx.getMessage(); if (msg == null || msg.length() == 0) { msg = upx.toString(); } reqtrans.set("axiom_upload_error", msg); } else if (upx instanceof FileUploadBase.SizeLimitExceededException) { sendError(response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "File upload size exceeds limit of " + uploadLimit + "kB"); return; } else { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error in file upload: " + upx); return; } } } parseCookies(request, reqtrans, encoding); // do standard HTTP variables String host = request.getHeader("Host"); if (host != null) { host = host.toLowerCase(); reqtrans.set("http_host", host); } String referer = request.getHeader("Referer"); if (referer != null) { reqtrans.set("http_referer", referer); } try { long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince > -1) { reqtrans.setIfModifiedSince(ifModifiedSince); } } catch (IllegalArgumentException ignore) { } String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null) { reqtrans.setETags(ifNoneMatch); } String remotehost = request.getRemoteAddr(); if (remotehost != null) { reqtrans.set("http_remotehost", remotehost); } // get the cookie domain to use for this response, if any. String resCookieDomain = cookieDomain; if (resCookieDomain != null) { // check if cookieDomain is valid for this response. // (note: cookieDomain is guaranteed to be lower case) // check for x-forwarded-for header, fix for bug 443 String proxiedHost = request.getHeader("x-forwarded-host"); if (proxiedHost != null) { if (proxiedHost.toLowerCase().indexOf(cookieDomain) == -1) { resCookieDomain = null; } } else if ((host != null) && host.toLowerCase().indexOf(cookieDomain) == -1) { resCookieDomain = null; } } // check if session cookie is present and valid, creating it if not. checkSessionCookie(request, response, reqtrans, resCookieDomain); String browser = request.getHeader("User-Agent"); if (browser != null) { reqtrans.set("http_browser", browser); } String language = request.getHeader("Accept-Language"); if (language != null) { reqtrans.set("http_language", language); } String authorization = request.getHeader("authorization"); if (authorization != null) { reqtrans.set("authorization", authorization); } ResponseTrans restrans = getApplication().execute(reqtrans); // if the response was already written and committed by the application // we can skip this part and return if (response.isCommitted()) { return; } // set cookies if (restrans.countCookies() > 0) { CookieTrans[] resCookies = restrans.getCookies(); for (int i = 0; i < resCookies.length; i++) try { Cookie c = resCookies[i].getCookie("/", resCookieDomain); response.addCookie(c); } catch (Exception ignore) { ignore.printStackTrace(); } } // write response writeResponse(request, response, reqtrans, restrans); } catch (Exception x) { try { if (debug) { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x); x.printStackTrace(); } else { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The server encountered an error while processing your request. " + "Please check back later."); } log("Exception in execute: " + x); } catch (IOException io_e) { log("Exception in sendError: " + io_e); } } }