List of usage examples for org.apache.commons.fileupload.servlet ServletRequestContext ServletRequestContext
public ServletRequestContext(HttpServletRequest request)
From source file:com.gtwm.pb.servlets.ServletUtilMethods.java
/** * Replacement for and wrapper around//www .j a v a 2 s.c o m * HttpServletRequest.getParameter(String) which works for multi-part form * data as well as normal requests */ public static String getParameter(HttpServletRequest request, String parameterName, List<FileItem> multipartItems) { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { for (FileItem item : multipartItems) { if (item.getFieldName().equals(parameterName)) { if (item.isFormField()) { return item.getString(); } else { return item.getName(); } } } return null; } else { return request.getParameter(parameterName); } }
From source file:com.googlecode.psiprobe.controllers.deploy.UploadWarController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { File tmpWar = null;// w ww . j av a 2s .co m String contextName = null; boolean update = false; boolean compile = false; boolean discard = false; // // parse multipart request and extract the file // FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding("UTF8"); try { for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) { FileItem fi = (FileItem) it.next(); if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpWar = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpWar); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { update = true; } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { compile = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.fatal("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() })); if (tmpWar != null && tmpWar.exists()) { tmpWar.delete(); } tmpWar = null; } String errMsg = null; if (tmpWar != null) { try { if (tmpWar.getName().endsWith(".war")) { if (contextName == null || contextName.length() == 0) { String warFileName = tmpWar.getName().replaceAll("\\.war$", ""); contextName = "/" + warFileName; } contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); // // pass the name of the newly deployed context to the presentation layer // using this name the presentation layer can render a url to view compilation details // String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { logger.debug("updating " + contextName + ": removing the old copy"); getContainerWrapper().getTomcatContainer().remove(contextName); } if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) { // // move the .war to tomcat application base dir // String destWarFilename = getContainerWrapper().getTomcatContainer() .formatContextFilename(contextName); File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(), destWarFilename + ".war"); FileUtils.moveFile(tmpWar, destWar); // // let Tomcat know that the file is there // getContainerWrapper().getTomcatContainer().installWar(contextName, new URL("jar:" + destWar.toURI().toURL().toString() + "!/")); Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName); if (ctx == null) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled", new Object[] { visibleContextName }); } else { request.setAttribute("success", Boolean.TRUE); if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(ctx); } if (compile) { Summary summary = new Summary(); summary.setName(ctx.getName()); getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true); request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary); request.setAttribute("compileSuccess", Boolean.TRUE); } } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } tmpWar.delete(); } } } return new ModelAndView(new InternalResourceView(getViewName())); }
From source file:fr.aliasource.webmail.server.UploadAttachmentsImpl.java
@SuppressWarnings("rawtypes") protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestContext ctx = new ServletRequestContext(req); String enc = ctx.getCharacterEncoding(); logger.warn("received encoding is " + enc); if (enc == null) { enc = "utf-8"; }// w ww . j a v a 2 s . c o m IAccount account = (IAccount) req.getSession().getAttribute("account"); if (account == null) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } DiskFileItemFactory factory = new DiskFileItemFactory(100 * 1024, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(20 * 1024 * 1024); List items = null; try { items = upload.parseRequest(req); } catch (FileUploadException e1) { logger.error("upload exception", e1); return; } // Process the uploaded items String id = null; Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { id = item.getFieldName(); String fileName = removePathElementsFromFilename(item.getName()); logger.warn("FileItem: " + item); long size = item.getSize(); logger.warn("pushing upload of " + fileName + " to backend for " + account.getLogin() + "@" + account.getDomain() + " size: " + size + ")."); AttachmentMetadata meta = new AttachmentMetadata(); meta.setFileName(fileName); meta.setSize(size); meta.setMime(item.getContentType()); try { account.uploadAttachement(id, meta, item.getInputStream()); } catch (Exception e) { logger.error("Cannot write uploaded file to disk"); } } } }
From source file:com.gtwm.pb.model.manageData.fields.FileValueDefn.java
/** * Construct a file value reading the uploaded file name for a particlular * file field from the HTTP request//from www. j av a 2 s .c o m */ public FileValueDefn(HttpServletRequest request, FileField fileField, List<FileItem> multipartItems) throws CantDoThatException, FileUploadException, ObjectNotFoundException { if (!FileUpload.isMultipartContent(new ServletRequestContext(request))) { throw new CantDoThatException("To upload a file, the form must be posted as multi-part form data"); } String internalFieldName = fileField.getInternalFieldName(); ITEMLOOP: for (FileItem item : multipartItems) { // if item is a file if (!item.isFormField()) { if (item.getFieldName().equals(internalFieldName)) { this.filename = item.getName().replaceAll("^.*\\\\", ""); break ITEMLOOP; } } } if (this.filename == null) { throw new ObjectNotFoundException("The file field " + fileField + "wasn't found in the user input"); } }
From source file:edu.xtec.colex.utils.ParseMultipart.java
/** * Creates a new instance of ParseMultipart with a given HttpServletRequest * @param requestIn the HttpServletRequest to parse *///from w w w. j a v a 2 s . c o m public ParseMultipart(HttpServletRequest requestIn) { parameters = new Hashtable(); request = requestIn; isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request)); try { if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure the factory here, if desired. ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("ISO-8859-1"); // Configure the uploader here, if desired. Iterator fileItems = upload.parseRequest(request).iterator(); while (fileItems.hasNext()) { FileItem fi = (FileItem) fileItems.next(); if (!fi.isFormField()) { parameters.put(fi.getFieldName(), fi); } else { parameters.put(fi.getFieldName(), fi.getString("ISO-8859-1").trim()); } } } } catch (Exception e) { System.out.println(e); } }
From source file:hu.sztaki.lpds.storage.net.bes.FileUploadServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request//from w w w . j av a2 s .co m * @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 { response.setContentType("text/html;charset=UTF-8"); ServletRequestContext servletRequestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext); if (isMultipart) { File newFile; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setSizeMax(Long.MAX_VALUE); try { List<FileItem> listFileItems = servletFileUpload.parseRequest(request); String path = PropertyLoader.getInstance().getProperty("portal.prefix.dir") + "storage/" + request.getParameter("path") + "/"; String link = request.getParameter("link"); File f = new File(path); f.mkdirs(); String[] pathData = request.getParameter("path").split("/"); for (FileItem t : listFileItems) { if (!t.isFormField()) { newFile = new File(path + "/" + t.getFieldName()); t.write(newFile); QuotaService.getInstance().addPlussRtIDQuotaSize(pathData[0], pathData[1], pathData[2], pathData[5], newFile.length()); // QuotaService.getInstance().get(pathData[0], pathData[1]).g // System.out.println("STORAGE:"+newFile.getAbsolutePath()); if (link != null) if (!t.getFieldName().equals(link)) FileUtils.getInstance().createLink(path, t.getFieldName(), path + link + getGeneratorPostFix(t.getFieldName())); } } } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.gtwm.pb.servlets.ServletUtilMethods.java
/** * Provide the ability to cache multi-part items in a variable to save re-parsing *///from w w w . j a va 2 s.com public static List<FileItem> getMultipartItems(HttpServletRequest request) { List<FileItem> multipartItems = new LinkedList<FileItem>(); if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { // See http://jakarta.apache.org/commons/fileupload/using.html FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { multipartItems = upload.parseRequest(request); } catch (FileUploadException fuex) { logException(fuex, request, "Error parsing multi-part form data"); } } return multipartItems; }
From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java
/** * ???????/*w ww .ja v a 2 s . co m*/ * @param klass ???klass?Class * @param filepath ? * @param sizeThreshold ?? * @param isFileNameBaseTime ???? * @return bean */ public static <T> Object upload(HttpServletRequest request, Class<T> klass, String filepath, int sizeThreshold, boolean isFileNameBaseTime) throws Exception { FileItemFactory fileItemFactory = null; if (sizeThreshold > 0) { File repository = new File(filepath); fileItemFactory = new DiskFileItemFactory(sizeThreshold, repository); } else { fileItemFactory = new DiskFileItemFactory(); } ServletFileUpload upload = new ServletFileUpload(fileItemFactory); ServletRequestContext requestContext = new ServletRequestContext(request); T bean = null; if (klass != null) { bean = klass.newInstance(); } // if (ServletFileUpload.isMultipartContent(requestContext)) { File parentDir = new File(filepath); List<FileItem> fileItemList = upload.parseRequest(requestContext); for (int i = 0; i < fileItemList.size(); i++) { FileItem item = fileItemList.get(i); // ?? if (item.isFormField()) { String paramName = item.getFieldName(); String paramValue = item.getString("UTF-8"); log.info("?" + paramName + "=" + paramValue); request.setAttribute(paramName, paramValue); // ?bean if (klass != null) { Field field = null; try { field = klass.getDeclaredField(paramName); if (field != null) { field.setAccessible(true); Class type = field.getType(); if (type == Integer.TYPE) { field.setInt(bean, Integer.valueOf(paramValue)); } else if (type == Double.TYPE) { field.setDouble(bean, Double.valueOf(paramValue)); } else if (type == Float.TYPE) { field.setFloat(bean, Float.valueOf(paramValue)); } else if (type == Boolean.TYPE) { field.setBoolean(bean, Boolean.valueOf(paramValue)); } else if (type == Character.TYPE) { field.setChar(bean, paramValue.charAt(0)); } else if (type == Long.TYPE) { field.setLong(bean, Long.valueOf(paramValue)); } else if (type == Short.TYPE) { field.setShort(bean, Short.valueOf(paramValue)); } else { field.set(bean, paramValue); } } } catch (NoSuchFieldException e) { log.info("" + klass.getName() + "?" + paramName); } } } // else { // <input type='file' name='xxx'> xxx String paramName = item.getFieldName(); log.info("?" + item.getSize()); if (sizeThreshold > 0) { if (item.getSize() > sizeThreshold) continue; } String clientFileName = item.getName(); int index = -1; // ?IE? if ((index = clientFileName.lastIndexOf("\\")) != -1) { clientFileName = clientFileName.substring(index + 1); } if (clientFileName == null || "".equals(clientFileName)) continue; String filename = null; log.info("" + paramName + "\t??" + clientFileName); if (isFileNameBaseTime) { filename = buildFileName(clientFileName); } else filename = clientFileName; request.setAttribute(paramName, filename); // ?bean if (klass != null) { Field field = null; try { field = klass.getDeclaredField(paramName); if (field != null) { field.setAccessible(true); field.set(bean, filename); } } catch (NoSuchFieldException e) { log.info("" + klass.getName() + "? " + paramName); continue; } } if (!parentDir.exists()) { parentDir.mkdirs(); } File newfile = new File(parentDir, filename); item.write(newfile); String serverPath = newfile.getPath(); log.info("?" + serverPath); } } } return bean; }
From source file:com.tremolosecurity.proxy.ProxyRequest.java
public ProxyRequest(HttpServletRequest req, HttpSession session) throws Exception { super(req);// w w w . j a v a 2s . c om this.session = session; ServletRequestContext reqCtx = new ServletRequestContext(req); this.isMultiPart = "POST".equalsIgnoreCase(req.getMethod()) && reqCtx.getContentType() != null && reqCtx.getContentType().toLowerCase(Locale.ENGLISH).startsWith("multipart/form-data"); this.isParamsInBody = true; this.isPush = false; this.paramList = new ArrayList<String>(); this.reqParams = new HashMap<String, ArrayList<String>>(); this.queryString = new ArrayList<NVP>(); HttpServletRequest request = (HttpServletRequest) super.getRequest(); if (request.getQueryString() != null && !request.getQueryString().isEmpty()) { StringTokenizer toker = new StringTokenizer(request.getQueryString(), "&"); while (toker.hasMoreTokens()) { String qp = toker.nextToken(); int index = qp.indexOf('='); if (index > 0) { String name = qp.substring(0, qp.indexOf('=')); String val = URLDecoder.decode(qp.substring(qp.indexOf('=') + 1), "UTf-8"); this.queryString.add(new NVP(name, val)); } } } if (this.isMultiPart) { this.isPush = true; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(req); this.reqFiles = new HashMap<String, ArrayList<FileItem>>(); for (FileItem item : items) { //this.paramList.add(item.getName()); if (item.isFormField()) { ArrayList<String> vals = this.reqParams.get(item.getFieldName()); if (vals == null) { vals = new ArrayList<String>(); this.reqParams.put(item.getFieldName(), vals); } this.paramList.add(item.getFieldName()); vals.add(item.getString()); } else { ArrayList<FileItem> vals = this.reqFiles.get(item.getFieldName()); if (vals == null) { vals = new ArrayList<FileItem>(); this.reqFiles.put(item.getFieldName(), vals); } vals.add(item); } } } else { Enumeration enumer = req.getHeaderNames(); String contentType = null; while (enumer.hasMoreElements()) { String name = (String) enumer.nextElement(); if (name.equalsIgnoreCase("content-type") || name.equalsIgnoreCase("content-length")) { this.isPush = true; if (name.equalsIgnoreCase("content-type")) { contentType = req.getHeader(name); } } } if (this.isPush) { if (contentType == null || !contentType.startsWith("application/x-www-form-urlencoded")) { this.isParamsInBody = false; ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = req.getInputStream(); int len; byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } req.setAttribute(ProxySys.MSG_BODY, baos.toByteArray()); } else if (contentType.startsWith("application/x-www-form-urlencoded")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = req.getInputStream(); int len; byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } StringTokenizer toker = new StringTokenizer(new String(baos.toByteArray()), "&"); this.orderedList = new ArrayList<NVP>(); while (toker.hasMoreTokens()) { String token = toker.nextToken(); int index = token.indexOf('='); String name = token.substring(0, index); if (name.indexOf('%') != -1) { name = URLDecoder.decode(name, "UTF-8"); } String val = ""; if (index < (token.length() - 1)) { val = URLDecoder.decode(token.substring(token.indexOf('=') + 1), "UTF-8"); } this.orderedList.add(new NVP(name, val)); this.paramList.add(name); ArrayList<String> params = this.reqParams.get(name); if (params == null) { params = new ArrayList<String>(); this.reqParams.put(name, params); } params.add(val); } } } } }
From source file:hu.sztaki.lpds.storage.service.carmen.server.upload.UploadServlet.java
/** * Processes requests for <code>POST</code> methods. * * @param request/*from w ww.j a v a 2 s. co m*/ * servlet request * @param response * servlet response * @throws IOException channel handling error * @throws ServletException Servlet error */ protected void postProcessRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // System.out.println(""); // System.out.println("UploadServlet postProcessRequest begin..."); // valtozok initializalasa // stores the form parameters Map formParameters = null; // stores the file parameters Map fileParameters = null; // portal service url String portalID = new String(""); // user name String userID = new String(""); // workflow name String workflowID = new String(""); // job name String jobID = new String(""); // storage file name, "input_inp01", "binary" String sfile = new String(""); // configuration ID // doConfigure generates during its call // pl: userID + System.currentTimeMillis(); String confID = new String(""); // the number of the files to be uploaded int fileCounter = 0; // true if requestSize is more then the size of the maxRequestSize boolean sizeLimitError = false; try { // Check that we have a file upload request ServletRequestContext servletRequestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext); if (isMultipart) { // System.out.println("Is Multipart Context."); FileUtils.getInstance().createRepositoryDirectory(); // use progress begin // Create a factory for progress-disk-based file items ProgressMonitorFileItemFactory progressMonitorFileItemFactory = new ProgressMonitorFileItemFactory( request); // Set factory constraints progressMonitorFileItemFactory.setSizeThreshold(maxMemorySize); // Set repository dir File tempRepositoryDirectory = new File(repositoryDir); progressMonitorFileItemFactory.setRepository(tempRepositoryDirectory); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(); servletFileUpload.setFileItemFactory(progressMonitorFileItemFactory); // Set overall request size constraint servletFileUpload.setSizeMax(maxRequestSize); // Parse the request, List /FileItem/ List listFileItems = null; try { // System.out.println("before_parseRequest..."); listFileItems = servletFileUpload.parseRequest(request); // System.out.println("after_parseRequest..."); formParameters = new HashMap(); fileParameters = new HashMap(); for (int i = 0; i < listFileItems.size(); i++) { FileItem fileItem = (FileItem) listFileItems.get(i); if (fileItem.isFormField() == true) { formParameters.put(fileItem.getFieldName(), fileItem.getString()); } else { fileParameters.put(fileItem.getFieldName(), fileItem); request.setAttribute(fileItem.getFieldName(), fileItem); } } } catch (Exception e) { // e.printStackTrace(); } // System.out.println("formParameters: " + formParameters); // System.out.println("fileParameters: " + fileParameters); // use progress end if ((listFileItems != null) && (listFileItems.size() > 0)) { // Process the hidden items Iterator iterator = listFileItems.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); // System.out.println("getFieldname : " + fileItem.getFieldName()); // System.out.println("getString : " + fileItem.getString()); if (fileItem.isFormField()) { // parameterek ertelmezese if (fileItem.getFieldName().equals("portalID")) { portalID = FileUtils.getInstance().convertPortalIDtoDirName(fileItem.getString()); } if (fileItem.getFieldName().equals("userID")) { userID = fileItem.getString(); } if (fileItem.getFieldName().equals("workflowID")) { workflowID = fileItem.getString(); } if (fileItem.getFieldName().equals("jobID")) { jobID = fileItem.getString(); } if (fileItem.getFieldName().equals("sfile")) { sfile = fileItem.getString(); } if (fileItem.getFieldName().equals("confID")) { confID = fileItem.getString(); } } else { if ((fileItem.getName() != null) && (!fileItem.getName().equals(""))) { fileCounter++; } } } // System.out.println("FileCounter : " + fileCounter); // Process the uploaded items if ((portalID != null) && (userID != null) && (workflowID != null) && (jobID != null) && (sfile != null) && (confID != null) && (fileCounter > 0)) { if ((!portalID.equals("")) && (!userID.equals("")) && (!workflowID.equals("")) && (!jobID.equals("")) && (!sfile.equals("")) && (!confID.equals(""))) { iterator = listFileItems.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); if (!fileItem.isFormField()) { processUploadedFiles(response, fileItem, portalID, userID, workflowID, jobID, sfile, confID); } } } } } } else { // System.out.println("Is NOT Multipart Context !!!"); } } catch (Exception e) { // e.printStackTrace(); throw new ServletException(e); } if (sizeLimitError) { // System.out.println("SizeLimitError: Upload file size (ReqestSize) // > " + this.maxRequestSize + " !"); } // System.out.println("UploadServlet postProcessRequest end..."); }