List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setHeaderEncoding
public void setHeaderEncoding(String encoding)
From source file:com.lecheng.cms.servlet.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from w w w .j av a 2s. c om*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); // logger.debug("Parameter Command: {}", commandStr); // logger.debug("Parameter Type: {}", typeStr); // logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // FileOperate fo = new FileOperate();//liwei // (+ ) upload.setHeaderEncoding("UTF-8");// liwei try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String oldName = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); // filename = fo.generateRandomFilename() + // extension;//liwei // (+ ) filename = UUID.randomUUID().toString() + "." + extension;// liwei // (UUID) // logger.warn(""+oldName+""+filename+""); if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); // logger.debug("Exiting Connector#doPost"); }
From source file:mml.handler.post.MMLPostHTMLHandler.java
void parseRequest(HttpServletRequest request) throws FileUploadException, Exception { if (ServletFileUpload.isMultipartContent(request)) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); List<FileItem> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString(encoding); if (fieldName.equals(Params.DOCID)) this.docid = contents; else if (fieldName.equals(Params.DIALECT)) { JSONObject jv = (JSONObject) JSONValue.parse(contents); if (jv.get("language") != null) this.langCode = (String) jv.get("language"); this.dialect = jv; } else if (fieldName.equals(Params.HTML)) { html = contents; } else if (fieldName.equals(Params.ENCODING)) encoding = contents; else if (fieldName.equals(Params.AUTHOR)) author = contents; else if (fieldName.equals(Params.TITLE)) title = contents; else if (fieldName.equals(Params.STYLE)) style = contents; else if (fieldName.equals(Params.FORMAT)) format = contents; else if (fieldName.equals(Params.SECTION)) section = contents; else if (fieldName.equals(Params.VERSION1)) version1 = contents; else if (fieldName.equals(Params.DESCRIPTION)) description = contents; }//from w w w .jav a 2 s .com } // we're not uploading files } if (encoding == null) encoding = "UTF-8"; if (author == null) author = "Anon"; if (style == null) style = "TEI/default"; if (format == null) format = "MVD/TEXT"; if (section == null) section = ""; if (version1 == null) version1 = "/Base/first"; if (description == null) description = "Version " + version1; if (docid == null) throw new Exception("missing docid"); if (html == null) throw new Exception("Missing html"); if (dialect == null) throw new Exception("Missing dialect"); } }
From source file:com.founder.fix.fixflow.FlowManager.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CurrentThread.init();//from www . j a v a 2 s . c o m String userId = StringUtil.getString(request.getSession().getAttribute(FlowCenterService.LOGIN_USER_ID)); if (StringUtil.isEmpty(userId)) { String context = request.getContextPath(); response.sendRedirect(context + "/"); return; } ServletOutputStream out = null; String action = StringUtil.getString(request.getParameter("action")); if (StringUtil.isEmpty(action)) { action = StringUtil.getString(request.getAttribute("action")); } RequestDispatcher rd = null; try { Map<String, Object> filter = new HashMap<String, Object>(); if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload Uploader = new ServletFileUpload(new DiskFileItemFactory()); // Uploader.setSizeMax("); // Uploader.setHeaderEncoding("utf-8"); List<FileItem> fileItems = Uploader.parseRequest(request); for (FileItem item : fileItems) { filter.put(item.getFieldName(), item); if (item.getFieldName().equals("action")) action = item.getString(); if (item.getFieldName().equals("deploymentId")) { filter.put("deploymentId", item.getString()); } } } else { Enumeration enu = request.getParameterNames(); while (enu.hasMoreElements()) { Object tmp = enu.nextElement(); Object obj = request.getParameter(StringUtil.getString(tmp)); // if (request.getAttribute("ISGET") != null) obj = new String(obj.toString().getBytes("ISO8859-1"), "utf-8"); filter.put(StringUtil.getString(tmp), obj); } } Enumeration attenums = request.getAttributeNames(); while (attenums.hasMoreElements()) { String paramName = (String) attenums.nextElement(); Object paramValue = request.getAttribute(paramName); // ?map filter.put(paramName, paramValue); } filter.put("userId", userId); request.setAttribute("nowAction", action); if ("processDefinitionList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/processDefinitionList.jsp"); Map<String, Object> result = getProcessDefinitionService().getProcessDefitionList(filter); filter.putAll(result); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("processManageList")) { rd = request.getRequestDispatcher("/fixflow/manager/processInstanceList.jsp"); Map<String, Object> result = getFlowManager().getProcessInstances(filter); filter.putAll(result); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("suspendProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().suspendProcessInstance(filter); } else if (action.equals("continueProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().continueProcessInstance(filter); } else if (action.equals("terminatProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().terminatProcessInstance(filter); } else if (action.equals("deleteProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().deleteProcessInstance(filter); } else if (action.equals("toProcessVariable")) { rd = request.getRequestDispatcher("/fixflow/manager/processVariableList.jsp"); Map<String, Object> result = getFlowManager().getProcessVariables(filter); filter.putAll(result); request.setAttribute("result", filter); } else if (action.equals("saveProcessVariables")) { String tmp = (String) filter.get("insertAndUpdate"); if (StringUtil.isNotEmpty(tmp)) { Map<String, Object> tMap = JSONUtil.parseJSON2Map(tmp); filter.put("insertAndUpdate", tMap); } getFlowManager().saveProcessVariables(filter); rd = request.getRequestDispatcher("/FlowManager?action=toProcessVariable"); } else if (action.equals("processTokenList")) { Map<String, Object> result = getFlowManager().getProcessTokens(filter); filter.putAll(result); request.setAttribute("result", filter); rd = request.getRequestDispatcher("/fixflow/manager/processTokenList.jsp"); } else if (action.equals("taskInstanceList")) { rd = request.getRequestDispatcher("/fixflow/manager/taskInstanceList.jsp"); filter.put("path", request.getSession().getServletContext().getRealPath("/")); Map<String, Object> pageResult = getTaskManager().getTaskList(filter); filter.putAll(pageResult); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("doTaskSuspend")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().suspendTask(filter); } else if (action.equals("doTaskResume")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().resumeTask(filter); } else if (action.equals("doTaskTransfer")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().transferTask(filter); } else if (action.equals("doTaskRollBackNode")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().rollBackNode(filter); } else if (action.equals("doTaskRollBackTask")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().rollBackStep(filter); } else if (action.equals("flowLibrary")) { rd = request.getRequestDispatcher("/fixflow-explorer/flowLibrary.jsp"); } //???deploymentId if ("deploy".equals(action)) { rd = request.getRequestDispatcher("/FlowManager?action=processDefinitionList"); response.setContentType("text/html;charset=utf-8"); getProcessDefinitionService().deployByZip(filter); } else if ("deleteDeploy".equals(action)) { rd = request.getRequestDispatcher("/FlowManager?action=processDefinitionList"); getProcessDefinitionService().deleteDeploy(filter); } else if ("download".equals(action)) { String processDefinitionId = StringUtil.getString(filter.get("processDefinitionId")); response.reset(); request.setCharacterEncoding("gbk"); response.setContentType("applcation/octet-stream"); response.setHeader("Content-disposition", "attachment; filename=" + processDefinitionId + ".zip"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0,private, max-age=0"); response.setHeader("Content-Type", "application/octet-stream"); response.setHeader("Content-Type", "application/force-download"); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); ZipOutputStream outZip = new ZipOutputStream(response.getOutputStream()); List<Map<String, Object>> fileList = getProcessDefinitionService().getResources(filter); for (Map<String, Object> file : fileList) { ZipEntry entry = new ZipEntry(file.get("FILENAME").toString()); entry.setSize(((byte[]) file.get("BYTES")).length); outZip.putNextEntry(entry); outZip.write((byte[]) file.get("BYTES")); outZip.closeEntry(); } outZip.close(); outZip.flush(); outZip.close(); } else if ("getUserList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/userList.jsp"); request.setAttribute("nowAction", "UserGroup"); Map<String, Object> result = getUserGroupService().getAllUsers(filter); filter.putAll(result); request.setAttribute("result", filter); List<Map<String, Object>> groupList = getUserGroupService().getAllGroupDefinition(filter); request.setAttribute("groupList", groupList); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if ("getGroupList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/groupList.jsp"); request.setAttribute("nowAction", "UserGroup"); Map<String, Object> result = getUserGroupService().getAllGroup(filter); filter.putAll(result); request.setAttribute("result", filter); List<Map<String, Object>> groupList = getUserGroupService().getAllGroupDefinition(filter); request.setAttribute("groupList", groupList); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if ("getUserInfo".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/userInfo.jsp"); Map<String, Object> pageResult = getUserGroupService().getUserInfo(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if ("getGroupInfo".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/groupInfo.jsp"); Map<String, Object> pageResult = getUserGroupService().getGroupInfo(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if ("getJobList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp"); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobList(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("viewJobInfo".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp"); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobTrigger(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("suspendJob".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp"); request.setAttribute("nowAction", "jobManager"); getJobService().suspendJob(filter); Map<String, Object> result = getJobService().getJobList(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("continueJob".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp"); getJobService().continueJob(filter); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobList(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("suspendTrigger".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp"); getJobService().suspendTrigger(filter); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobTrigger(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("continueTrigger".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp"); getJobService().continueTrigger(filter); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobTrigger(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("setHis".equals(action)) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().setHistory(filter); } else if ("updateCache".equals(action)) { ProcessEngineManagement.getDefaultProcessEngine().cleanCache(true, true); response.getWriter().write("update success!"); } } catch (Exception e) { e.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); try { CurrentThread.rollBack(); } catch (SQLException e1) { e1.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); } } finally { if (out != null) { out.flush(); out.close(); } try { CurrentThread.clear(); } catch (SQLException e) { e.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); } } if (rd != null) rd.forward(request, response); }
From source file:com.webpagebytes.cms.controllers.FileController.java
public void uploadFolder(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { try {//from w w w . j a v a 2 s . c om ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); FileItemIterator iterator = upload.getItemIterator(request); WPBFile ownerFile = null; Map<String, WPBFile> subfolderFiles = new HashMap<String, WPBFile>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField() && item.getFieldName().equals("ownerExtKey")) { String ownerExtKey = Streams.asString(item.openStream()); ownerFile = getDirectory(ownerExtKey, adminStorage); } else if (!item.isFormField() && item.getFieldName().equals("file")) { String fullName = item.getName(); String directoryPath = getDirectoryFromLongName(fullName); String fileName = getFileNameFromLongName(fullName); Map<String, WPBFile> tempSubFolders = checkAndCreateSubDirectory(directoryPath, ownerFile); subfolderFiles.putAll(tempSubFolders); // delete the existing file WPBFile existingFile = getFileFromDirectory(subfolderFiles.get(directoryPath), fileName); if (existingFile != null) { deleteFile(existingFile, 0); } // create the file WPBFile file = new WPBFile(); file.setExternalKey(adminStorage.getUniqueId()); file.setFileName(fileName); file.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime()); file.setDirectoryFlag(0); addFileToDirectory(subfolderFiles.get(directoryPath), file, item.openStream()); } } org.json.JSONObject returnJson = new org.json.JSONObject(); returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null)); httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null); } catch (Exception e) { Map<String, String> errors = new HashMap<String, String>(); errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD); httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors); } }
From source file:com.webpagebytes.cms.controllers.FileController.java
public void upload(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { try {/*from w w w . j a v a 2 s . c o m*/ ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); FileItemIterator iterator = upload.getItemIterator(request); WPBFile ownerFile = null; while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField() && item.getFieldName().equals("ownerExtKey")) { String ownerExtKey = Streams.asString(item.openStream()); ownerFile = getDirectory(ownerExtKey, adminStorage); } else if (!item.isFormField() && item.getFieldName().equals("file")) { InputStream stream = item.openStream(); WPBFile wbFile = null; String fileName = getFileNameFromLongName(item.getName()); if (request.getAttribute("key") != null) { // this is an upload as update for an existing file Long key = Long.valueOf((String) request.getAttribute("key")); wbFile = adminStorage.get(key, WPBFile.class); ownerFile = getDirectory(wbFile.getOwnerExtKey(), adminStorage); //old file need to be deleted from cloud String oldFilePath = wbFile.getBlobKey(); if (oldFilePath != null && oldFilePath.length() > 0) { // delete only if the blob key is set WPBFilePath oldCloudFile = new WPBFilePath(PUBLIC_BUCKET, oldFilePath); cloudFileStorage.deleteFile(oldCloudFile); } } else { // this is a new upload wbFile = new WPBFile(); wbFile.setExternalKey(adminStorage.getUniqueId()); } wbFile.setFileName(fileName); wbFile.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime()); wbFile.setDirectoryFlag(0); addFileToDirectory(ownerFile, wbFile, stream); } } org.json.JSONObject returnJson = new org.json.JSONObject(); returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null)); httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null); } catch (Exception e) { Map<String, String> errors = new HashMap<String, String>(); errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD); httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors); } }
From source file:com.glaf.mail.web.rest.MailTaskResource.java
@POST @Path("/uploadMails") @ResponseBody//from ww w . j a v a 2 s. c om public void uploadMails(@Context HttpServletRequest request, @Context UriInfo uriInfo) { Map<String, Object> params = RequestUtils.getParameterMap(request); logger.debug(params); String taskId = request.getParameter("taskId"); if (StringUtils.isEmpty(taskId)) { taskId = request.getParameter("id"); } MailTask mailTask = null; if (StringUtils.isNotEmpty(taskId)) { mailTask = mailTaskService.getMailTask(taskId); } if (mailTask != null && StringUtils.equals(RequestUtils.getActorId(request), mailTask.getCreateBy())) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); // factory.setRepository(new File(SystemProperties.getConfigRootPath() + "/temp/")); ServletFileUpload upload = new ServletFileUpload(factory); // ? // // upload.setSizeMax(4194304); upload.setHeaderEncoding("UTF-8"); List<?> fileItems = null; try { fileItems = upload.parseRequest(request); Iterator<?> i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); logger.debug(fi.getName()); if (fi.getName().endsWith(".txt")) { byte[] bytes = fi.get(); String rowIds = new String(bytes); List<String> addresses = StringTools.split(rowIds); if (addresses.size() <= 100000) { mailDataFacede.saveMails(taskId, addresses); taskId = mailTask.getId(); if (mailTask.getLocked() == 0) { QuartzUtils.stop(taskId); QuartzUtils.restart(taskId); } else { QuartzUtils.stop(taskId); } } else { throw new RuntimeException("mail addresses too many"); } break; } } } catch (FileUploadException ex) {// ? ex.printStackTrace(); throw new RuntimeException(ex.getMessage()); } } }
From source file:com.ecyrd.jspwiki.attachment.AttachmentServlet.java
/** * Uploads a specific mime multipart input set, intercepts exceptions. * * @param req The servlet request//from w ww . j a v a 2 s .com * @return The page to which we should go next. * @throws RedirectException If there's an error and a redirection is needed * @throws IOException If upload fails * @throws FileUploadException */ @SuppressWarnings("unchecked") protected String upload(HttpServletRequest req) throws RedirectException, IOException { String msg = ""; String attName = "(unknown)"; String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad happened, Upload should be able to take care of most stuff String nextPage = errorPage; String progressId = req.getParameter("progressid"); // Check that we have a file upload request if (!ServletFileUpload.isMultipartContent(req)) { throw new RedirectException("Not a file upload", errorPage); } try { FileItemFactory factory = new DiskFileItemFactory(); // Create the context _before_ Multipart operations, otherwise // strict servlet containers may fail when setting encoding. WikiContext context = m_engine.createContext(req, WikiContext.ATTACH); UploadListener pl = new UploadListener(); m_engine.getProgressManager().startProgress(pl, progressId); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); if (!context.hasAdminPermissions()) { upload.setFileSizeMax(m_maxSize); } upload.setProgressListener(pl); List<FileItem> items = upload.parseRequest(req); String wikipage = null; String changeNote = null; FileItem actualFile = null; for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("page")) { // // FIXME: Kludge alert. We must end up with the parent page name, // if this is an upload of a new revision // wikipage = item.getString("UTF-8"); int x = wikipage.indexOf("/"); if (x != -1) wikipage = wikipage.substring(0, x); } else if (item.getFieldName().equals("changenote")) { changeNote = item.getString("UTF-8"); if (changeNote != null) { changeNote = TextUtil.replaceEntities(changeNote); } } else if (item.getFieldName().equals("nextpage")) { nextPage = validateNextPage(item.getString("UTF-8"), errorPage); } } else { actualFile = item; } } if (actualFile == null) throw new RedirectException("Broken file upload", errorPage); // // FIXME: Unfortunately, with Apache fileupload we will get the form fields in // order. This means that we have to gather all the metadata from the // request prior to actually touching the uploaded file itself. This // is because the changenote appears after the file upload box, and we // would not have this information when uploading. This also means // that with current structure we can only support a single file upload // at a time. // String filename = actualFile.getName(); long fileSize = actualFile.getSize(); InputStream in = actualFile.getInputStream(); try { executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize); } finally { in.close(); } } catch (ProviderException e) { msg = "Upload failed because the provider failed: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw new IOException(msg); } catch (IOException e) { // Show the submit page again, but with a bit more // intimidating output. msg = "Upload failure: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw e; } catch (FileUploadException e) { // Show the submit page again, but with a bit more // intimidating output. msg = "Upload failure: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw new IOException(msg); } finally { m_engine.getProgressManager().stopProgress(progressId); // FIXME: In case of exceptions should absolutely // remove the uploaded file. } return nextPage; }
From source file:net.dkahn.web.controller.ExtendedMultiPartRequestHandler.java
/** * Parses the input stream and partitions the parsed items into a set of * form fields and a set of file items. In the process, the parsed items * are translated from Commons FileUpload <code>FileItem</code> instances * to Struts <code>FormFile</code> instances. * * @param request The multipart request to be processed. * * @throws ServletException if an unrecoverable error occurs. */// www . j a v a2 s .co m public void handleRequest(HttpServletRequest request) throws ServletException { // Get the app config for the current request. ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY); //---------------------------------------------------------- // Changed this section of code, that is it. //----------------------------------------------------------- log.debug("Handling the request.."); UploadListener listener = new UploadListener(request, 1); log.debug("uploading file with optional monitoring.."); // Create a factory for disk-based file items FileItemFactory factory = new MonitoredDiskFileItemFactory(listener); log.debug("got the factory now get the ServletFileUpload"); ServletFileUpload upload = new ServletFileUpload(factory); log.debug("Should have the ServletFileUpload by now."); // The following line is to support an "EncodingFilter" // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255 upload.setHeaderEncoding(request.getCharacterEncoding()); // Set the maximum size before a FileUploadException will be thrown. upload.setSizeMax(getSizeMax(ac)); //---------------------------------------------------------------- // Create the hash tables to be populated. elementsText = new Hashtable(); elementsFile = new Hashtable(); elementsAll = new Hashtable(); // Parse the request into file items. List items = null; try { items = upload.parseRequest(request); } catch (DiskFileUpload.SizeLimitExceededException e) { // Special handling for uploads that are too big. request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE); return; } catch (FileUploadException e) { log.error("Failed to parse multipart request", e); throw new ServletException(e); } // Partition the items into form fields and files. Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { addTextParameter(request, item); } else { addFileParameter(item); } } }
From source file:com.jdon.jivejdon.presentation.servlet.upload.ExtendedMultiPartRequestHandler.java
/** * Parses the input stream and partitions the parsed items into a set of * form fields and a set of file items. In the process, the parsed items are * translated from Commons FileUpload <code>FileItem</code> instances to * Struts <code>FormFile</code> instances. * /* w ww . j a va 2 s .c o m*/ * @param request * The multipart request to be processed. * * @throws ServletException * if an unrecoverable error occurs. */ public void handleRequest(HttpServletRequest request) throws ServletException { // Get the app config for the current request. ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY); // ---------------------------------------------------------- // Changed this section of code, that is it. // ----------------------------------------------------------- log.debug("Handling the request.."); UploadListener listener = new UploadListener(request, 1); log.debug("uploading file with optional monitoring.."); // Create a factory for disk-based file items FileItemFactory factory = new MonitoredDiskFileItemFactory(listener); log.debug("got the factory now get the ServletFileUpload"); ServletFileUpload upload = new ServletFileUpload(factory); log.debug("Should have the ServletFileUpload by now."); // The following line is to support an "EncodingFilter" // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255 upload.setHeaderEncoding(request.getCharacterEncoding()); // Set the maximum size before a FileUploadException will be thrown. upload.setSizeMax(getSizeMax(ac)); // ---------------------------------------------------------------- // Create the hash tables to be populated. elementsText = new Hashtable(); elementsFile = new Hashtable(); elementsAll = new Hashtable(); // Parse the request into file items. List items = null; try { items = upload.parseRequest(request); } catch (DiskFileUpload.SizeLimitExceededException e) { // Special handling for uploads that are too big. request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE); return; } catch (FileUploadException e) { log.error("Failed to parse multipart request", e); throw new ServletException(e); } // Partition the items into form fields and files. Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { addTextParameter(request, item); } else { addFileParameter(item); } } }
From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java
/** * Uploads a specific mime multipart input set, intercepts exceptions. * @param req The servlet request/* ww w . j ava 2s.com*/ * @return The page to which we should go next. * @throws RedirectException If there's an error and a redirection is needed * @throws IOException If upload fails * @throws FileUploadException */ @SuppressWarnings("unchecked") protected String upload(HttpServletRequest req) throws RedirectException, IOException { String msg = ""; String attName = "(unknown)"; String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad // happened, Upload // should be able to // take care of most // stuff String nextPage = errorPage; String progressId = req.getParameter("progressid"); // Check that we have a file upload request if (!ServletFileUpload.isMultipartContent(req)) { throw new RedirectException("Not a file upload", errorPage); } try { FileItemFactory factory = new DiskFileItemFactory(); // Create the context _before_ Multipart operations, otherwise // strict servlet containers may fail when setting encoding. WikiContext context = m_engine.createContext(req, WikiContext.ATTACH); UploadListener pl = new UploadListener(); m_engine.getProgressManager().startProgress(pl, progressId); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); upload.setFileSizeMax(m_maxSize); upload.setProgressListener(pl); List<FileItem> items = upload.parseRequest(req); String wikipage = null; String changeNote = null; FileItem actualFile = null; for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("page")) { // // FIXME: Kludge alert. We must end up with the parent page name, // if this is an upload of a new revision // wikipage = item.getString("UTF-8"); int x = wikipage.indexOf("/"); if (x != -1) { wikipage = wikipage.substring(0, x); } } else if (item.getFieldName().equals("changenote")) { changeNote = item.getString("UTF-8"); } else if (item.getFieldName().equals("nextpage")) { nextPage = validateNextPage(item.getString("UTF-8"), errorPage); } } else { actualFile = item; } } if (actualFile == null) { throw new RedirectException("Broken file upload", errorPage); } // // FIXME: Unfortunately, with Apache fileupload we will get the form fields in // order. This means that we have to gather all the metadata from the // request prior to actually touching the uploaded file itself. This // is because the changenote appears after the file upload box, and we // would not have this information when uploading. This also means // that with current structure we can only support a single file upload // at a time. // String filename = actualFile.getName(); long fileSize = actualFile.getSize(); InputStream in = actualFile.getInputStream(); try { executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize); } finally { in.close(); } } catch (ProviderException e) { msg = "Upload failed because the provider failed: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw new IOException(msg); } catch (IOException e) { // Show the submit page again, but with a bit more // intimidating output. msg = "Upload failure: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw e; } catch (FileUploadException e) { // Show the submit page again, but with a bit more // intimidating output. msg = "Upload failure: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw new IOException(msg); } finally { m_engine.getProgressManager().stopProgress(progressId); // FIXME: In case of exceptions should absolutely // remove the uploaded file. } return nextPage; }