List of usage examples for javax.servlet.http HttpServletRequest setCharacterEncoding
public void setCharacterEncoding(String env) throws UnsupportedEncodingException;
From source file:com.glaf.jbpm.web.springmvc.MxJbpmStartProcessController.java
@RequestMapping public ModelAndView startProcess(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug(paramMap);//from www. ja va2s . co m String json = RequestUtils.getStringValue(request, "json"); String rowId = RequestUtils.getStringValue(request, "rowId"); String processName = RequestUtils.getStringValue(request, "processName"); String actorId = RequestUtils.getActorId(request); ProcessContainer container = ProcessContainer.getContainer(); Long processInstanceId = null; if (StringUtils.isNotEmpty(rowId) && StringUtils.isNotEmpty(processName) && StringUtils.isNotEmpty(actorId)) { ProcessContext ctx = new ProcessContext(); ctx.setRowId(rowId); ctx.setActorId(actorId); ctx.setTitle("???" + rowId); ctx.setProcessName(processName); /** * ??json?.<br> * {money:100000,day:5,pass:true,deptId:"123", roleId:"R001"} */ if (StringUtils.isNotEmpty(json)) { Map<String, Object> jsonMap = JsonUtils.decode(json); if (jsonMap != null && jsonMap.size() > 0) { Set<Entry<String, Object>> entrySet = jsonMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); Object value = entry.getValue(); if (name != null && value != null) { if (name != null && value != null) { DataField dataField = new DataField(); dataField.setName(name); dataField.setValue(value); ctx.addDataField(dataField); } } } } } try { processInstanceId = container.startProcess(ctx); if (processInstanceId != null) { request.setAttribute("processInstanceId", processInstanceId); request.setAttribute("statusCode", 200); request.setAttribute("message", ViewProperties.getString("res_submit_ok")); } else { request.setAttribute("statusCode", 500); request.setAttribute("message", ViewProperties.getString("res_submit_error")); } logger.debug("processInstanceId:" + processInstanceId); } catch (Exception ex) { request.setAttribute("statusCode", 500); request.setAttribute("message", ViewProperties.getString("res_submit_error")); if (LogUtils.isDebug()) { ex.printStackTrace(); logger.debug(ex); } } } /** * ??jsonxml???<br> * 200-? <br> * 500-<br> */ String responseDataType = RequestUtils.getStringValue(request, "responseDataType"); if (StringUtils.equals(responseDataType, "json")) { String encoding = request.getParameter("encoding"); if (encoding == null) { encoding = "UTF-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); response.setContentType("text/plain;charset=" + encoding); Map<String, Object> jsonMap = new java.util.HashMap<String, Object>(); if (processInstanceId != null) { jsonMap.put("statusCode", 200); jsonMap.put("success", "true"); jsonMap.put("data", ViewProperties.getString("res_submit_ok")); jsonMap.put("message", ViewProperties.getString("res_submit_ok")); } else { jsonMap.put("statusCode", 500); jsonMap.put("success", "false"); jsonMap.put("data", ViewProperties.getString("res_submit_error")); jsonMap.put("message", ViewProperties.getString("res_submit_error")); } JSONObject object = new JSONObject(jsonMap); response.getWriter().write(object.toString()); return null; } else if (StringUtils.equals(responseDataType, "xml")) { String encoding = request.getParameter("encoding"); if (encoding == null) { encoding = "UTF-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); response.setContentType("text/xml;charset=" + encoding); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); if (processInstanceId != null) { buffer.append("\n <statusCode>200</statusCode>"); buffer.append("\n <message>").append(ViewProperties.getString("res_submit_ok")) .append("</message>"); } else { buffer.append("\n <statusCode>500</statusCode>"); buffer.append("\n <message>").append(ViewProperties.getString("res_submit_error")) .append("</message>"); } buffer.append("\n</response>"); response.getWriter().write(buffer.toString()); return null; } /** * ?????<br> * ?????_start_template??jbpm_start_template * WEB-INF\conf\extension?? */ String templateId = RequestUtils.getStringValue(request, "x_templateId"); if (StringUtils.isEmpty(templateId)) { templateId = CustomProperties.getString(processName + "_start_template"); } if (StringUtils.isEmpty(templateId)) { templateId = CustomProperties.getString("jbpm_start_template"); } if (StringUtils.isNotEmpty(templateId)) { Map<String, Object> context = new java.util.HashMap<String, Object>(); context.putAll(paramMap); context.put("actorId", actorId); context.put("processInstanceId", processInstanceId); context.put("contextPath", request.getContextPath()); if (processInstanceId != null) { context.put("statusCode", 200); context.put("message", ViewProperties.getString("res_submit_ok")); } else { context.put("statusCode", 500); context.put("message", ViewProperties.getString("res_submit_error")); } try { logger.debug(context); Writer writer = new StringWriter(); TemplateUtils.evaluate(templateId, context, writer); request.setAttribute("templateScript", writer.toString()); String encoding = request.getParameter("encoding"); if (encoding == null) { encoding = "UTF-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); response.setContentType("text/html;charset=" + encoding); response.getWriter().write(writer.toString()); return null; } catch (Exception ex) { if (LogUtils.isDebug()) { ex.printStackTrace(); logger.debug(ex); } } } String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view); } String x_view = ViewProperties.getString("jbpm_start.startProcess"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view); } return new ModelAndView("/jbpm/start"); }
From source file:egovframework.example.sample.web.EgovSampleController.java
@RequestMapping("/fileUploadX.do") public void fileUploadX(HttpServletRequest request, HttpServletResponse response, SessionStatus status) throws Exception { //System.out.println(" ? uuid--"+request.getParameter("uuid")); String chkType = request.getHeader("Content-Type"); if (chkType == null) { return;//from w ww . j a v a 2 s .c o m } request.setCharacterEncoding("utf-8"); String contextRealPath = request.getSession().getServletContext().getRealPath("/"); String PATH = request.getParameter("PATH"); String savePath = contextRealPath + PATH; // System.out.println("savePath------@@-----"+savePath); // int maxSize = 500 * 1024 * 1024; // ? ? 500MB() PlatformData resData = new PlatformData(); VariableList resVarList = resData.getVariableList(); String sMsg = " A "; try { MultipartHttpServletRequest msReq = (MultipartHttpServletRequest) request; Iterator<String> filesd = msReq.getFileNames(); String dir = request.getRealPath("images/egovframework/board_img"); while (filesd.hasNext()) { sMsg += "D "; //String name = (String)files.nextElement(); String name = filesd.next(); // System.out.println("? ^^-----"+name); MultipartFile mfile = msReq.getFile(name); //? String genId = UUID.randomUUID().toString(); //? String originalFileName = mfile.getOriginalFilename(); //? String saveFileName = genId; // System.out.println("???="+ originalFileName); System.out.println("??=" + saveFileName); String savePathh = dir + "/" + saveFileName; mfile.transferTo(new File(savePathh)); System.out.println(name + "??"); System.out.println("? ?-" + genId); //?? SampleVO vo = new SampleVO(); vo.setiOriName(originalFileName); vo.setiFileName(saveFileName); vo.setiSize((int) mfile.getSize()); vo.setiUrl(savePathh); vo.setiUuid(request.getParameter("uuid")); sampleService.uploadImg(vo); status.setComplete(); } resVarList.add("ErrorCode", 200); resVarList.add("ErrorMsg", "SUCC"); } catch (Exception e) { resVarList.add("ErrorCode", 500); resVarList.add("ErrorMsg", sMsg + " " + e); } HttpPlatformResponse res = new HttpPlatformResponse(response); res.setData(resData); res.sendData(); }
From source file:egovframework.example.sample.web.EgovSampleController.java
@RequestMapping("/fileUploadX2.do") public void fileUploadX2(HttpServletRequest request, HttpServletResponse response, SessionStatus status) throws Exception { //System.out.println(" ? uuid--"+request.getParameter("uuid")); String chkType = request.getHeader("Content-Type"); if (chkType == null) { return;/*from www . j av a2s. c om*/ } request.setCharacterEncoding("utf-8"); String contextRealPath = request.getSession().getServletContext().getRealPath("/"); String PATH = request.getParameter("PATH"); String savePath = contextRealPath + PATH; // System.out.println("savePath------@@-----"+savePath); // int maxSize = 500 * 1024 * 1024; // ? ? 500MB() PlatformData resData = new PlatformData(); VariableList resVarList = resData.getVariableList(); String sMsg = " A "; try { MultipartHttpServletRequest msReq = (MultipartHttpServletRequest) request; Iterator<String> filesd = msReq.getFileNames(); String dir = request.getRealPath("images/egovframework/board_img"); while (filesd.hasNext()) { sMsg += "D "; //String name = (String)files.nextElement(); String name = filesd.next(); // System.out.println("? ^^-----"+name); MultipartFile mfile = msReq.getFile(name); //? String genId = UUID.randomUUID().toString(); //? String originalFileName = mfile.getOriginalFilename(); //? String saveFileName = genId; // System.out.println("???="+ originalFileName); System.out.println("??=" + saveFileName); String savePathh = dir + "/" + saveFileName; mfile.transferTo(new File(savePathh)); System.out.println(name + "??"); System.out.println("? ?-" + genId); //?? SampleVO vo = new SampleVO(); vo.setiOriName(originalFileName); vo.setiFileName(saveFileName); vo.setiSize((int) mfile.getSize()); vo.setiUrl(savePathh); vo.setiUuid("thumbnail"); sampleService.uploadImg(vo); //? ? //updateThumbnail Product pVO = new Product(); pVO.setP_uuid(request.getParameter("uuid")); System.out.println(" uuid-" + request.getParameter("uuid")); String thumbnail = "http://localhost:8778/sample/images/egovframework/board_img/" + saveFileName; pVO.setP_thumbnail(thumbnail); sampleService.updateThumbnail(pVO); status.setComplete(); } resVarList.add("ErrorCode", 200); resVarList.add("ErrorMsg", "SUCC"); } catch (Exception e) { resVarList.add("ErrorCode", 500); resVarList.add("ErrorMsg", sMsg + " " + e); } HttpPlatformResponse res = new HttpPlatformResponse(response); res.setData(resData); res.sendData(); }
From source file:com.glaf.jbpm.web.springmvc.MxJbpmTakeTaskController.java
@RequestMapping public ModelAndView takeTask(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> paramMap = RequestUtils.getParameterMap(request); Long processInstanceId = ParamUtils.getLong(paramMap, "processInstanceId"); Long taskInstanceId = ParamUtils.getLong(paramMap, "taskInstanceId"); String actorId = RequestUtils.getActorId(request); ProcessContainer container = ProcessContainer.getContainer(); boolean canSubmit = false; TaskItem taskItem = null;/* ww w .j a v a2 s . c o m*/ String processName = null; if (taskInstanceId != null && StringUtils.isNotEmpty(actorId)) { /** * ???? */ taskItem = container.getTaskItem(taskInstanceId, actorId); if (taskItem != null) { if (processInstanceId != null) { canSubmit = true; processInstanceId = taskItem.getProcessInstanceId(); processName = taskItem.getProcessName(); } } } else if (processInstanceId != null && StringUtils.isNotEmpty(actorId)) { /** * ????? */ taskItem = container.getMinTaskItem(actorId, processInstanceId); if (taskItem != null) { canSubmit = true; taskInstanceId = taskItem.getTaskInstanceId(); processName = taskItem.getProcessName(); } } /** * ??? */ if (canSubmit && taskInstanceId != null) { String routeMode = CustomProperties.getString(processName + "_routeMode"); logger.debug("routeMode:" + routeMode); if (StringUtils.equals(routeMode, "MANUAL")) { if (taskInstanceId != null) { Collection<String> transitionNames = container.getTransitionNames(taskInstanceId); request.setAttribute("transitionNames", transitionNames); } } else if (StringUtils.equals(routeMode, "FREE")) { int signal = container.getSignal(taskInstanceId); if (signal != TaskNode.SIGNAL_LAST) { Collection<String> nodeNames = container.getNodeNames(processInstanceId); request.setAttribute("nodeNames", nodeNames); } } request.setAttribute("taskItem", taskItem); } /** * ??? */ if (processInstanceId != null) { List<ActivityInstance> ActivityInstances = container.getActivityInstances(processInstanceId); request.setAttribute("ActivityInstances", ActivityInstances); } /** * ?????<br> * ?????_take_template??jbpm_take_template * WEB-INF\conf\extension?? */ String templateId = ParamUtils.getString(paramMap, "z_templateId"); if (taskItem != null) { templateId = CustomProperties.getString(processName + "_" + taskItem.getTaskName() + "_take_template"); } if (StringUtils.isEmpty(templateId)) { templateId = CustomProperties.getString(processName + "_take_template"); } if (StringUtils.isEmpty(templateId)) { templateId = CustomProperties.getString("jbpm_take_template"); } logger.info("templateId=" + templateId); if (StringUtils.isNotEmpty(templateId)) { Map<String, Object> context = new java.util.HashMap<String, Object>(); context.putAll(paramMap); context.put("actorId", actorId); context.put("contextPath", request.getContextPath()); context.put("taskItem", taskItem); context.put("nodeNames", request.getAttribute("nodeNames")); context.put("ActivityInstances", request.getAttribute("ActivityInstances")); context.put("transitionNames", request.getAttribute("transitionNames")); try { logger.debug(context); Writer writer = new StringWriter(); TemplateUtils.evaluate(templateId, context, writer); request.setAttribute("templateScript", writer.toString()); String encoding = request.getParameter("encoding"); if (encoding == null) { encoding = "UTF-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); response.setContentType("text/html;charset=" + encoding); response.getWriter().write(writer.toString()); return null; } catch (Exception ex) { if (LogUtils.isDebug()) { ex.printStackTrace(); logger.debug(ex); } } } String jx_view = request.getParameter("jx_view"); if (StringUtils.isNotEmpty(jx_view)) { return new ModelAndView(jx_view); } String x_view = ViewProperties.getString("jbpm_take.takeTask"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view); } return new ModelAndView("/jbpm/take"); }
From source file:com.liferay.portal.servlet.MainServlet.java
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (!PortalInstances.matches()) { String html = ContentUtil.get("messages/en_US/init.html"); res.getOutputStream().print(html); return;/*from w w w.j a va 2s .co m*/ } if (ShutdownUtil.isShutdown()) { String html = ContentUtil.get("messages/en_US/shutdown.html"); res.getOutputStream().print(html); return; } req.setAttribute("dotcache", "no"); // Shared session HttpSession ses = req.getSession(); if (!GetterUtil.getBoolean(PropsUtil.get(PropsUtil.TCK_URL))) { String sharedSessionId = CookieUtil.get(req.getCookies(), CookieKeys.SHARED_SESSION_ID); _log.debug("Shared session id is " + sharedSessionId); if (sharedSessionId == null) { sharedSessionId = PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12); Cookie sharedSessionIdCookie = new Cookie(CookieKeys.SHARED_SESSION_ID, sharedSessionId); sharedSessionIdCookie.setPath("/"); sharedSessionIdCookie.setMaxAge(86400); res.addCookie(sharedSessionIdCookie); _log.debug("Shared session id is " + sharedSessionId); } // if (ses.getAttribute(WebKeys.SHARED_SESSION_ID) == null) { ses.setAttribute(WebKeys.SHARED_SESSION_ID, sharedSessionId); // } HttpSession portalSes = (HttpSession) SharedSessionPool.get(sharedSessionId); if ((portalSes == null) || (ses != portalSes)) { if (portalSes == null) { _log.debug("No session exists in pool"); } else { _log.debug("Session " + portalSes.getId() + " in pool is old"); } _log.debug("Inserting current session " + ses.getId() + " in pool"); SharedSessionPool.put(sharedSessionId, ses); } } // Test CAS auto login /* * ses.setAttribute( * com.liferay.portal.auth.CASAutoLogin.CAS_FILTER_USER, * "liferay.com.1"); */ // CTX ServletContext ctx = getServletContext(); ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX)); if (portalCtx == null) { portalCtx = ctx; } req.setAttribute(WebKeys.CTX, portalCtx); // CTX_PATH variable String ctxPath = (String) ctx.getAttribute(WebKeys.CTX_PATH); if (portalCtx.getAttribute(WebKeys.CTX_PATH) == null) { portalCtx.setAttribute(WebKeys.CTX_PATH, ctxPath); } if (ses.getAttribute(WebKeys.CTX_PATH) == null) { ses.setAttribute(WebKeys.CTX_PATH, ctxPath); } req.setAttribute(WebKeys.CTX_PATH, ctxPath); // CAPTCHA_PATH variable String captchaPath = (String) ctx.getAttribute(WebKeys.CAPTCHA_PATH); if (portalCtx.getAttribute(WebKeys.CAPTCHA_PATH) == null) { portalCtx.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); } if (ses.getAttribute(WebKeys.CAPTCHA_PATH) == null) { ses.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); } req.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); // IMAGE_PATH variable String imagePath = (String) ctx.getAttribute(WebKeys.IMAGE_PATH); if (portalCtx.getAttribute(WebKeys.IMAGE_PATH) == null) { portalCtx.setAttribute(WebKeys.IMAGE_PATH, imagePath); } if (ses.getAttribute(WebKeys.IMAGE_PATH) == null) { ses.setAttribute(WebKeys.IMAGE_PATH, imagePath); } req.setAttribute(WebKeys.IMAGE_PATH, imagePath); // WebKeys.COMPANY_ID variable String companyId = (String) ctx.getAttribute(WebKeys.COMPANY_ID); if (portalCtx.getAttribute(WebKeys.COMPANY_ID) == null) { portalCtx.setAttribute(WebKeys.COMPANY_ID, companyId); } if (ses.getAttribute(WebKeys.COMPANY_ID) == null) { ses.setAttribute(WebKeys.COMPANY_ID, companyId); } req.setAttribute(WebKeys.COMPANY_ID, companyId); // Portlet Request Processor PortletRequestProcessor portletReqProcessor = (PortletRequestProcessor) portalCtx .getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR); if (portletReqProcessor == null) { portletReqProcessor = new PortletRequestProcessor(this, getModuleConfig(req)); portalCtx.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor); } // Tiles definitions factory if (portalCtx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) == null) { portalCtx.setAttribute(TilesUtilImpl.DEFINITIONS_FACTORY, ctx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY)); } // Set character encoding String strutsCharEncoding = PropsUtil.get(PropsUtil.STRUTS_CHAR_ENCODING); req.setCharacterEncoding(strutsCharEncoding); /* * if (!BrowserSniffer.is_wml(req)) { res.setContentType( * Constants.TEXT_HTML + "; charset=" + strutsCharEncoding); } */ // Determine content type String contentType = req.getHeader("Content-Type"); if ((contentType != null) && (contentType.startsWith("multipart/form-data"))) { req = new UploadServletRequest(req); } else if (ParamUtil.get(req, WebKeys.ENCRYPT, false)) { try { Company company = CompanyLocalManagerUtil.getCompany(companyId); req = new EncryptedServletRequest(req, company.getKeyObj()); } catch (Exception e) { } } // Current URL String completeURL = Http.getCompleteURL(req); if (completeURL.indexOf("j_security_check") != -1) { completeURL = ctxPath; } else { completeURL = completeURL.substring(completeURL.indexOf("://") + 3, completeURL.length()); completeURL = completeURL.substring(completeURL.indexOf("/"), completeURL.length()); } req.setAttribute(WebKeys.CURRENT_URL, completeURL); // Chat server // Login String userId = PortalUtil.getUserId(req); if ((userId != null)) { PrincipalThreadLocal.setName(userId); } if (userId == null) { try { User user = UserManagerUtil.getDefaultUser(companyId); if (ses.getAttribute(Globals.LOCALE_KEY) == null) ses.setAttribute(Globals.LOCALE_KEY, user.getLocale()); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } } // Process pre service events try { EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_PRE), req, res); } catch (Exception e) { Logger.error(this, e.getMessage(), e); req.setAttribute(PageContext.EXCEPTION, e); StrutsUtil.forward(PropsUtil.get(PropsUtil.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE), portalCtx, req, res); } // Struts service callParentService(req, res); // Process post service events try { EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_POST), req, res); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } // Clear the principal associated with this thread PrincipalThreadLocal.setName(null); }
From source file:com.glaf.jbpm.web.springmvc.MxJbpmCompleteTaskController.java
@RequestMapping public ModelAndView completeTask(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug(paramMap);/* w ww. j a va2 s . c om*/ String json = RequestUtils.getStringValue(request, "json"); Long processInstanceId = ParamUtils.getLong(paramMap, "processInstanceId"); Long taskInstanceId = ParamUtils.getLong(paramMap, "taskInstanceId"); String transitionName = RequestUtils.getStringValue(request, "transitionName"); String jumpToNode = RequestUtils.getStringValue(request, "jumpToNode"); String isAgree = RequestUtils.getStringValue(request, "isAgree"); String opinion = RequestUtils.getStringValue(request, "opinion"); logger.debug("json:" + json); logger.debug("processInstanceId:" + processInstanceId); logger.debug("taskInstanceId:" + taskInstanceId); logger.debug("transitionName:" + transitionName); logger.debug("jumpToNode:" + jumpToNode); logger.debug("isAgree:" + isAgree); logger.debug("opinion:" + opinion); String actorId = RequestUtils.getActorId(request); ProcessContainer container = ProcessContainer.getContainer(); String processName = null; boolean canSubmit = false; boolean isOK = false; TaskItem taskItem = null; if ("0".equals(isAgree)) { isAgree = "false"; } else if ("1".equals(isAgree)) { isAgree = "true"; } if (taskInstanceId != null && StringUtils.isNotEmpty(actorId)) { /** * ???? */ taskItem = container.getTaskItem(taskInstanceId, actorId); if (taskItem != null) { if (processInstanceId != null) { canSubmit = true; processInstanceId = taskItem.getProcessInstanceId(); processName = taskItem.getProcessName(); } } } else if (processInstanceId != null && StringUtils.isNotEmpty(actorId)) { /** * ????? */ taskItem = container.getMinTaskItem(actorId, processInstanceId); if (taskItem != null) { canSubmit = true; processName = taskItem.getProcessName(); } } /** * ??? */ if (canSubmit && taskItem != null) { ProcessContext ctx = new ProcessContext(); /** * ??json?.<br> * {money:100000,day:5,pass:true,deptId:"123", roleId:"R001"} */ if (StringUtils.isNotEmpty(json)) { Map<String, Object> jsonMap = JsonUtils.decode(json); if (jsonMap != null && jsonMap.size() > 0) { Set<Entry<String, Object>> entrySet = jsonMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); Object value = entry.getValue(); if (name != null && value != null) { DataField dataField = new DataField(); dataField.setName(name); dataField.setValue(value); ctx.addDataField(dataField); } } } } DataField dataField = new DataField(); dataField.setName("isAgree"); dataField.setValue(isAgree); ctx.addDataField(dataField); ctx.setActorId(actorId); ctx.setOpinion(opinion); ctx.setProcessInstanceId(taskItem.getProcessInstanceId()); ctx.setTaskInstanceId(taskItem.getTaskInstanceId()); ctx.setJumpToNode(jumpToNode); ctx.setTransitionName(transitionName); try { isOK = container.completeTask(ctx); request.setAttribute("isOK", Boolean.valueOf(isOK)); if (isOK) { request.setAttribute("statusCode", 200); request.setAttribute("message", ViewProperties.getString("res_submit_ok")); } else { request.setAttribute("statusCode", 500); request.setAttribute("message", ViewProperties.getString("res_submit_error")); } } catch (Exception ex) { request.setAttribute("statusCode", 500); request.setAttribute("message", ViewProperties.getString("res_submit_error")); if (LogUtils.isDebug()) { ex.printStackTrace(); logger.debug(ex); } } } String responseDataType = RequestUtils.getStringValue(request, "responseDataType"); /** * ??jsonxml???<br> * 200-? <br> * 500-<br> */ if (StringUtils.equals(responseDataType, "json")) { String encoding = request.getParameter("encoding"); if (encoding == null) { encoding = "UTF-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); response.setContentType("text/plain;charset=" + encoding); Map<String, Object> jsonMap = new java.util.HashMap<String, Object>(); if (isOK) { jsonMap.put("statusCode", 200); jsonMap.put("success", "true"); jsonMap.put("data", ViewProperties.getString("res_submit_ok")); jsonMap.put("message", ViewProperties.getString("res_submit_ok")); } else { jsonMap.put("statusCode", 500); jsonMap.put("success", "false"); jsonMap.put("data", ViewProperties.getString("res_submit_error")); jsonMap.put("message", ViewProperties.getString("res_submit_error")); } JSONObject object = new JSONObject(jsonMap); Writer writer = response.getWriter(); writer.write(object.toString()); writer.flush(); writer.close(); writer = null; return null; } else if (StringUtils.equals(responseDataType, "xml")) { String encoding = request.getParameter("encoding"); if (encoding == null) { encoding = "UTF-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); response.setContentType("text/xml;charset=" + encoding); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); if (isOK) { buffer.append("\n <statusCode>200</statusCode>"); buffer.append("\n <message>").append(ViewProperties.getString("res_submit_ok")) .append("</message>"); } else { buffer.append("\n <statusCode>500</statusCode>"); buffer.append("\n <message>").append(ViewProperties.getString("res_submit_error")) .append("</message>"); } buffer.append("\n</response>"); Writer writer = response.getWriter(); writer.write(buffer.toString()); writer.flush(); writer.close(); writer = null; return null; } /** * ?????<br> * ?????_complete_template??jbpm_complete_template * WEB-INF\conf\extension?? */ String templateId = RequestUtils.getStringValue(request, "y_templateId"); if (StringUtils.isEmpty(templateId)) { templateId = CustomProperties.getString(processName + "_complete_template"); } if (StringUtils.isEmpty(templateId)) { templateId = CustomProperties.getString("jbpm_complete_template"); } if (StringUtils.isNotEmpty(templateId)) { Map<String, Object> context = new java.util.HashMap<String, Object>(); context.putAll(paramMap); context.put("actorId", actorId); context.put("canSubmit", canSubmit); context.put("isOK", isOK); context.put("taskItem", taskItem); context.put("processInstanceId", processInstanceId); context.put("contextPath", request.getContextPath()); if (isOK) { context.put("statusCode", 200); context.put("message", ViewProperties.getString("res_submit_ok")); } else { context.put("statusCode", 500); context.put("message", ViewProperties.getString("res_submit_error")); } try { logger.debug(context); Writer writer = new StringWriter(); TemplateUtils.evaluate(templateId, context, writer); request.setAttribute("templateScript", writer.toString()); String encoding = request.getParameter("encoding"); if (encoding == null) { encoding = "UTF-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); response.setContentType("text/html;charset=" + encoding); response.getWriter().write(writer.toString()); return null; } catch (Exception ex) { if (LogUtils.isDebug()) { ex.printStackTrace(); logger.debug(ex); } } } String jx_view = request.getParameter("jx_view"); if (StringUtils.isNotEmpty(jx_view)) { return new ModelAndView(jx_view); } String x_view = ViewProperties.getString("jbpm_complete.complateTask"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view); } return new ModelAndView("/jbpm/complete"); }
From source file:com.founder.fix.fixflow.FlowManager.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CurrentThread.init();// w w w .jav a 2 s .c om 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:org.apache.tapestry.engine.AbstractEngine.java
/** * Invoked from {@link #service(RequestContext)} to ensure that the engine's * instance variables are setup. This allows the application a chance to * restore transient variables that will not have survived deserialization. * * Determines the servlet prefix: this is the base URL used by * {@link IEngineService services} to build URLs. It consists * of two parts: the context path and the servlet path. * * <p>The servlet path is retrieved from {@link HttpServletRequest#getServletPath()}. * * <p>The context path is retrieved from {@link HttpServletRequest#getContextPath()}. * * <p>The global object is retrieved from {@link IEngine#getGlobal()} method. * * <p>The final path is available via the {@link #getServletPath()} method. * * <p>In addition, this method locates and/or creates the: * <ul>/*from www . jav a2 s . c om*/ * <li>{@link IComponentClassEnhancer} * <li>{@link Pool} * <li>{@link ITemplateSource} * <li>{@link ISpecificationSource} * <li>{@link IPageSource} * <li>{@link IEngineService} {@link Map} * <ll>{@link IScriptSource} * <li>{@link IComponentMessagesSource} * <li>{@link IPropertySource} * </ul> * * <p>This order is important, because some of the later shared objects * depend on some of the earlier shared objects already having * been located or created * (especially {@link #getPool() pool}). * * <p>Subclasses should invoke this implementation first, then perform their * own setup. * **/ protected void setupForRequest(RequestContext context) { HttpServlet servlet = context.getServlet(); ServletContext servletContext = servlet.getServletContext(); HttpServletRequest request = context.getRequest(); HttpSession session = context.getSession(); if (session != null) _sessionId = context.getSession().getId(); else _sessionId = null; // Previously, this used getRemoteHost(), but that requires an // expensive reverse DNS lookup. Possibly, the host name lookup // should occur ... but only if there's an actual error message // to display. if (_clientAddress == null) _clientAddress = request.getRemoteAddr(); // servletPath is null, so this means either we're doing the // first request in this session, or we're handling a subsequent // request in another JVM (i.e. another server in the cluster). // In any case, we have to do some late (re-)initialization. if (_servletPath == null) { // Get the path *within* the servlet context // In rare cases related to the tagsupport service, getServletPath() is wrong // (its a JSP, which invokes Tapestry as an include, thus muddling what // the real servlet and servlet path is). In those cases, the JSP tag // will inform us. String path = (String) request.getAttribute(Tapestry.TAG_SUPPORT_SERVLET_PATH_ATTRIBUTE); if (path == null) path = request.getServletPath(); // Get the context path, which may be the empty string // (but won't be null). _contextPath = request.getContextPath(); _servletPath = _contextPath + path; } String servletName = context.getServlet().getServletName(); if (_propertySource == null) { String name = PROPERTY_SOURCE_NAME + ":" + servletName; _propertySource = (IPropertySource) servletContext.getAttribute(name); if (_propertySource == null) { _propertySource = createPropertySource(context); servletContext.setAttribute(name, _propertySource); } } if (_enhancer == null) { String name = ENHANCER_NAME + ":" + servletName; _enhancer = (IComponentClassEnhancer) servletContext.getAttribute(name); if (_enhancer == null) { _enhancer = createComponentClassEnhancer(context); servletContext.setAttribute(name, _enhancer); } } if (_pool == null) { String name = POOL_NAME + ":" + servletName; _pool = (Pool) servletContext.getAttribute(name); if (_pool == null) { _pool = createPool(context); servletContext.setAttribute(name, _pool); } } if (_templateSource == null) { String name = TEMPLATE_SOURCE_NAME + ":" + servletName; _templateSource = (ITemplateSource) servletContext.getAttribute(name); if (_templateSource == null) { _templateSource = createTemplateSource(context); servletContext.setAttribute(name, _templateSource); } } if (_specificationSource == null) { String name = SPECIFICATION_SOURCE_NAME + ":" + servletName; _specificationSource = (ISpecificationSource) servletContext.getAttribute(name); if (_specificationSource == null) { _specificationSource = createSpecificationSource(context); servletContext.setAttribute(name, _specificationSource); } } if (_pageSource == null) { String name = PAGE_SOURCE_NAME + ":" + servletName; _pageSource = (IPageSource) servletContext.getAttribute(name); if (_pageSource == null) { _pageSource = createPageSource(context); servletContext.setAttribute(name, _pageSource); } } if (_scriptSource == null) { String name = SCRIPT_SOURCE_NAME + ":" + servletName; _scriptSource = (IScriptSource) servletContext.getAttribute(name); if (_scriptSource == null) { _scriptSource = createScriptSource(context); servletContext.setAttribute(name, _scriptSource); } } if (_serviceMap == null) { String name = SERVICE_MAP_NAME + ":" + servletName; _serviceMap = (Map) servletContext.getAttribute(name); if (_serviceMap == null) { _serviceMap = createServiceMap(); servletContext.setAttribute(name, _serviceMap); } } if (_stringsSource == null) { String name = STRINGS_SOURCE_NAME + ":" + servletName; _stringsSource = (IComponentMessagesSource) servletContext.getAttribute(name); if (_stringsSource == null) { _stringsSource = createComponentStringsSource(context); servletContext.setAttribute(name, _stringsSource); } } if (_dataSqueezer == null) { String name = DATA_SQUEEZER_NAME + ":" + servletName; _dataSqueezer = (DataSqueezer) servletContext.getAttribute(name); if (_dataSqueezer == null) { _dataSqueezer = createDataSqueezer(); servletContext.setAttribute(name, _dataSqueezer); } } if (_global == null) { String name = GLOBAL_NAME + ":" + servletName; _global = servletContext.getAttribute(name); if (_global == null) { _global = createGlobal(context); servletContext.setAttribute(name, _global); } } if (_resourceChecksumSource == null) { String name = RESOURCE_CHECKSUM_SOURCE_NAME + ":" + servletName; _resourceChecksumSource = (ResourceChecksumSource) servletContext.getAttribute(name); if (_resourceChecksumSource == null) { _resourceChecksumSource = createResourceChecksumSource(); servletContext.setAttribute(name, _resourceChecksumSource); } } String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = getOutputEncoding(); try { request.setCharacterEncoding(encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(Tapestry.format("illegal-encoding", encoding)); } catch (NoSuchMethodError e) { // Servlet API 2.2 compatibility // Behave okay if the setCharacterEncoding() method is unavailable } catch (AbstractMethodError e) { // Servlet API 2.2 compatibility // Behave okay if the setCharacterEncoding() method is unavailable } } }
From source file:com.stratelia.silverpeas.versioningPeas.servlets.VersioningRequestRouter.java
@Override public String getDestination(String function, VersioningSessionController versioningSC, HttpServletRequest request) { String destination = ""; SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "User=" + versioningSC.getUserId() + " Function=" + function); String rootDestination = "/versioningPeas/jsp/"; ResourceLocator messages = new ResourceLocator( "com.stratelia.silverpeas.versioningPeas.multilang.versioning", versioningSC.getLanguage()); try {/*from w w w. j a va 2s.c o m*/ String flag = versioningSC.getProfile(); request.setAttribute("Profile", flag); if (function.startsWith("ViewReadersList")) { List<Group> groups = new ArrayList<Group>(); List<String> users = new ArrayList<String>(); ProfileInst profile = versioningSC.getCurrentProfile(VersioningSessionController.READER); if (profile != null) { groups = versioningSC.groupIds2Groups(profile.getAllGroups()); users = versioningSC.userIds2Users(profile.getAllUsers()); } request.setAttribute("Groups", groups); request.setAttribute("Users", users); destination = rootDestination + "ReadList.jsp"; } else if (function.startsWith("ViewWritersList")) { Document document = versioningSC.getEditingDocument(); ProfileInst profile = versioningSC.getCurrentProfile(VersioningSessionController.WRITER); ArrayList<Worker> workers = new ArrayList<Worker>(); if (profile != null) { workers = document.getWorkList(); if (document.getCurrentWorkListOrder() == Integer .parseInt(VersioningSessionController.WRITERS_LIST_ORDERED) && !versioningSC.isAlreadyMerged() && !profile.getAllGroups().isEmpty()) { // Need to merge users from groups with other users workers = versioningSC.mergeUsersFromGroupsWithWorkers(profile.getAllGroups(), workers); } } request.setAttribute("Workers", workers); destination = rootDestination + "WorkList.jsp"; } else if (function.startsWith("ChangeOrder")) { String lines = request.getParameter("lines"); Document document = versioningSC.getEditingDocument(); ArrayList<Worker> users = document.getWorkList(); if (lines != null) { int users_count = Integer.parseInt(lines); if (users_count == users.size()) { ArrayList<Worker> new_users = new ArrayList<Worker>(users_count); for (int i = 0; i < users_count; i++) { Worker user = users.get(i); boolean v_value = false; // Validator String chvi = request.getParameter("chv" + i); if (chvi != null) { v_value = true; } user.setApproval(v_value); new_users.add(user); } // Sorting begin int upIndex = Integer.parseInt(request.getParameter("up")); int downIndex = Integer.parseInt(request.getParameter("down")); int addIndex = Integer.parseInt(request.getParameter("add")); // Remove user to change order if (upIndex > 0 && upIndex < users_count) { Worker user = new_users.remove(upIndex); new_users.add(upIndex - 1, user); } if (downIndex >= 0 && downIndex < users_count - 1) { Worker user = new_users.remove(downIndex); new_users.add(downIndex + 1, user); } if (addIndex >= 0 && addIndex < users_count) { Worker user = new_users.get(addIndex); Worker new_user = new Worker(user.getUserId(), Integer.parseInt(versioningSC.getEditingDocument().getPk().getId()), 0, user.isApproval(), true, versioningSC.getComponentId(), user.getType(), user.isSaved(), user.isUsed(), user.getListType()); new_users.add(addIndex + 1, new_user); users_count++; } for (int i = 0; i < users_count; i++) { new_users.get(i).setOrder(i); } document.setWorkList(new_users); } } destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("ChangeListType")) { Document document = versioningSC.getEditingDocument(); String listType = request.getParameter("ListType"); if (!StringUtil.isDefined(listType)) { listType = VersioningSessionController.WRITERS_LIST_SIMPLE; } document.setCurrentWorkListOrder(Integer.parseInt(listType)); ProfileInst profile = versioningSC.getProfile(VersioningSessionController.WRITER); ArrayList<Worker> workers = new ArrayList<Worker>(); if (profile != null) { if (listType.equals(VersioningSessionController.WRITERS_LIST_ORDERED)) { // Need to merge users from groups with other users workers = document.getWorkList(); workers = versioningSC.mergeUsersFromGroupsWithWorkers(profile.getAllGroups(), workers); versioningSC.setAlreadyMerged(true); } else { ArrayList<Worker> workersUsers = new ArrayList<Worker>(); ArrayList<Worker> workersGroups = new ArrayList<Worker>(); workersGroups = versioningSC.convertGroupsToWorkers(workers, profile.getAllGroups()); workers.addAll(workersGroups); workersUsers = versioningSC.convertUsersToWorkers(workers, profile.getAllUsers()); workers.addAll(workersUsers); } } document.setWorkList(workers); versioningSC.updateWorkList(document); versioningSC.updateDocument(document); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("SaveListType")) { Document document = versioningSC.getEditingDocument(); ArrayList<Worker> users = document.getWorkList(); ArrayList<Worker> updateUsers = new ArrayList<Worker>(); for (int i = 0; i < users.size(); i++) { Worker user = users.get(i); // Set approval rights to users String chvi = request.getParameter("chv" + i); boolean v_value = false; if (chvi != null) { v_value = true; } user.setApproval(v_value); updateUsers.add(user); } versioningSC.updateWorkList(document); versioningSC.updateDocument(document); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("ViewVersions")) { request.setAttribute("Document", versioningSC.getEditingDocument()); destination = rootDestination + "versions.jsp"; } else if (function.equals("SelectUsersGroupsProfileInstance")) { String role = request.getParameter("Role"); String listType = request.getParameter("ListType"); if (StringUtil.isDefined(listType)) { versioningSC.getEditingDocument().setCurrentWorkListOrder(Integer.parseInt(listType)); } versioningSC.initUserPanelInstanceForGroupsUsers(role); destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.startsWith("DocumentProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); ProfileInst profile = versioningSC.getProfile(role); versioningSC.updateDocumentProfile(profile); if (role.equals(VersioningSessionController.WRITER)) { ArrayList<Worker> oldWorkers = versioningSC.getEditingDocument().getWorkList(); ArrayList<Worker> workers = new ArrayList<Worker>(); ArrayList<Worker> workersUsers = new ArrayList<Worker>(); ArrayList<Worker> workersGroups = new ArrayList<Worker>(); workersGroups = versioningSC.convertGroupsToWorkers(oldWorkers, profile.getAllGroups()); workers.addAll(workersGroups); workersUsers = versioningSC.convertUsersToWorkers(oldWorkers, profile.getAllUsers()); workers.addAll(workersUsers); ArrayList<Worker> sortedWorkers = new ArrayList<Worker>(); if (workers != null) { for (int i = 0; i < workers.size(); i++) { Worker sortedWorker = workers.get(i); sortedWorker.setOrder(i); sortedWorkers.add(sortedWorker); } workers = sortedWorkers; } versioningSC.getEditingDocument().setWorkList(workers); versioningSC.updateWorkList(versioningSC.getEditingDocument()); request.setAttribute("urlToReload", "ViewWritersList"); } else { request.setAttribute("urlToReload", "ViewReadersList"); } destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("SaveList")) { String role = request.getParameter("Role"); String fromFunction = request.getParameter("From"); if (versioningSC.isAccessListExist(role)) { versioningSC.removeAccessList(role); } versioningSC.saveAccessList(role); request.setAttribute("Message", messages.getString("versioning.ListSaved", "")); destination = getDestination(fromFunction, versioningSC, request); } else if (function.startsWith("DeleteReaderProfile")) { ProfileInst profile = versioningSC.getDocumentProfile(VersioningSessionController.READER); if (profile != null) { profile.removeAllGroups(); profile.removeAllUsers(); versioningSC.updateProfileInst(profile); } destination = getDestination("ViewReadersList", versioningSC, request); } else if (function.startsWith("DeleteWriterProfile")) { ProfileInst profile = versioningSC.getDocumentProfile(VersioningSessionController.WRITER); if (profile != null) { profile.removeAllGroups(); profile.removeAllUsers(); versioningSC.updateProfileInst(profile); } versioningSC.deleteWorkers(true); versioningSC.setAlreadyMerged(false); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("Update")) { String docId = request.getParameter("DocId"); String name = request.getParameter("name"); String description = request.getParameter("description"); String comments = request.getParameter("comments"); Document document = versioningSC .getDocument(new DocumentPK(Integer.parseInt(docId), versioningSC.getComponentId())); document.setDescription(description); document.setName(name); document.setAdditionalInfo(comments); versioningSC.updateDocument(document); versioningSC.setEditingDocument(document); destination = getDestination("ViewVersions", versioningSC, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("AddNewVersion")) { // Display xmlForm if used if (StringUtil.isDefined(versioningSC.getXmlForm())) { setXMLFormIntoRequest(request.getParameter("documentId"), versioningSC, request); } destination = rootDestination + "newVersion.jsp"; } else if (function.equals("AddNewOnlineVersion")) { String documentId = request.getParameter("documentId"); request.setAttribute("DocumentId", documentId); // Display xmlForm if used if (StringUtil.isDefined(versioningSC.getXmlForm())) { setXMLFormIntoRequest(documentId, versioningSC, request); } destination = rootDestination + "newOnlineVersion.jsp"; } else if (function.equals("ChangeValidator")) { String setTypeId = request.getParameter("VV"); String setType = request.getParameter("SetType"); // 'U'for users or 'G' // for groups versioningSC.setWorkerValidator(versioningSC.getEditingDocument().getWorkList(), Integer.parseInt(setTypeId), setType); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.equals("ListPublicVersionsOfDocument")) { String documentId = request.getParameter("DocId"); String isAlias = request.getParameter("Alias"); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); Document document = versioningSC.getDocument(documentPK); List<DocumentVersion> publicVersions = versioningSC.getPublicDocumentVersions(documentPK); request.setAttribute("Document", document); request.setAttribute("PublicVersions", publicVersions); request.setAttribute("Alias", isAlias); destination = "/versioningPeas/jsp/publicVersions.jsp"; } else if ("ViewAllVersions".equals(function)) { return viewVersions(request, versioningSC); } else if ("saveOnline".equals(function)) { if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); String documentId = FileUploadUtil.getParameter(items, "documentId", "-1", encoding); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); Document document = versioningSC.getDocument(documentPK); String userId = versioningSC.getUserId(); String radio = FileUploadUtil.getParameter(items, "radio", "", encoding); String comments = FileUploadUtil.getParameter(items, "comments", "", encoding); boolean force = "true".equalsIgnoreCase(request.getParameter("force_release")); String callback = FileUploadUtil.getParameter(items, "Callback"); request.setAttribute("Callback", callback); destination = "/versioningPeas/jsp/documentSaved.jsp"; boolean addXmlForm = !isXMLFormEmpty(versioningSC, items); DocumentVersionPK newVersionPK = versioningSC.saveOnline(document, comments, radio, Integer.parseInt(userId), force, addXmlForm); if (newVersionPK != null) { request.setAttribute("DocumentId", documentId); DocumentVersion version = versioningSC.getLastVersion(documentPK); request.setAttribute("Version", version); if (addXmlForm) { saveXMLData(versioningSC, newVersionPK, items); } } else { if ("admin".equals(versioningSC.getUserRoleLevel())) { // TODO MANU ecrire la page pour ressoumettre en forcant destination = "/versioningPeas/jsp/forceDocumentLocked.jsp"; } else { destination = "/versioningPeas/jsp/documentLocked.jsp"; } } } else if ("Checkout".equals(function)) { String documentId = request.getParameter("DocId"); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); Document document = versioningSC.getDocument(documentPK); document.setStatus(1); document.setLastCheckOutDate(new Date()); versioningSC.checkDocumentOut(documentPK, Integer.parseInt(versioningSC.getUserId()), new Date()); document = versioningSC.getDocument(documentPK); versioningSC.setEditingDocument(document); request.setAttribute("Document", document); destination = rootDestination + "versions.jsp"; } else if ("DeleteDocumentRequest".equals(function)) { String documentId = request.getParameter("DocId"); String url = request.getParameter("Url"); request.setAttribute("DocId", documentId); request.setAttribute("Url", url); destination = rootDestination + "deleteDocument.jsp"; } else if (function.equals("DeleteDocument")) { String documentId = request.getParameter("DocId"); String url = request.getParameter("Url"); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); versioningSC.deleteDocument(documentPK); SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "url=" + url); request.setAttribute("urlToReload", url); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("AddNewDocument")) { String pubId = request.getParameter("PubId"); request.setAttribute("PubId", pubId); if (StringUtil.isDefined(versioningSC.getXmlForm())) { setXMLFormIntoRequest(null, versioningSC, request); } destination = rootDestination + "newDocument.jsp"; } else if (function.equals("SaveNewDocument")) { saveNewDocument(request, versioningSC); destination = getDestination("ViewVersions", versioningSC, request); } else if (function.equals("SaveNewVersion")) { if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); String type = FileUploadUtil.getParameter(items, "type", "", encoding); String comments = FileUploadUtil.getParameter(items, "comments", "", encoding); String radio = FileUploadUtil.getParameter(items, "radio", "", encoding); String documentId = FileUploadUtil.getParameter(items, "documentId", "-1", encoding); // Save file on disk FileItem fileItem = FileUploadUtil.getFile(items, "file_upload"); boolean runOnUnix = !FileUtil.isWindows(); String logicalName = fileItem.getName(); String physicalName = "dummy"; String mimeType = "dummy"; File dir = null; int size = 0; if (logicalName != null) { if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = new Long(new Date().getTime()).toString() + "." + type; mimeType = FileUtil.getMimeType(logicalName); if (!StringUtil.isDefined(mimeType)) { mimeType = "unknown"; } dir = new File(versioningSC.createPath(versioningSC.getComponentId(), null) + physicalName); size = new Long(fileItem.getSize()).intValue(); fileItem.write(dir); } // create DocumentVersion String componentId = versioningSC.getComponentId(); DocumentPK docPK = new DocumentPK(Integer.parseInt(documentId), "useless", componentId); int userId = Integer.parseInt(versioningSC.getUserId()); DocumentVersion documentVersion = null; DocumentVersion lastVersion = versioningSC.getLastVersion(docPK); if (com.stratelia.silverpeas.versioning.ejb.RepositoryHelper.getJcrDocumentService() .isNodeLocked(lastVersion)) { destination = rootDestination + "documentLocked.jsp"; } else { List<DocumentVersion> versions = versioningSC.getDocumentVersions(docPK); int majorNumber = 0; int minorNumber = 1; if (versions != null && versions.size() > 0) { documentVersion = versions.get(0); majorNumber = documentVersion.getMajorNumber(); minorNumber = documentVersion.getMinorNumber(); DocumentVersion newVersion = new DocumentVersion(null, docPK, majorNumber, minorNumber, userId, new Date(), comments, Integer.parseInt(radio), documentVersion.getStatus(), physicalName, logicalName, mimeType, size, componentId); boolean addXmlForm = !isXMLFormEmpty(versioningSC, items); if (addXmlForm) { newVersion.setXmlForm(versioningSC.getXmlForm()); } newVersion = versioningSC.addNewDocumentVersion(newVersion); ResourceLocator settings = new ResourceLocator( "com.stratelia.webactiv.util.attachment.Attachment", ""); boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false); // Specific case: 3d file to convert by Actify Publisher if (actifyPublisherEnable) { String extensions = settings.getString("Actify3dFiles"); StringTokenizer tokenizer = new StringTokenizer(extensions, ","); // 3d native file ? boolean fileForActify = false; SilverTrace.info("versioningPeas", "saveFile.jsp", "root.MSG_GEN_PARAM_VALUE", "nb tokenizer =" + tokenizer.countTokens()); while (tokenizer.hasMoreTokens() && !fileForActify) { String extension = tokenizer.nextToken(); if (type.equalsIgnoreCase(extension)) { fileForActify = true; } } if (fileForActify) { String dirDestName = "v_" + componentId + "_" + documentId; String actifyWorkingPath = settings.getString("ActifyPathSource") + File.separator + dirDestName; String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath; if (!new File(destPath).exists()) { FileRepositoryManager.createGlobalTempPath(actifyWorkingPath); } String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath + File.separator + logicalName; FileRepositoryManager.copyFile( versioningSC.createPath(componentId, null) + File.separator + physicalName, destFile); } } if (addXmlForm) { saveXMLData(versioningSC, newVersion.getPk(), items); } } String returnURL = FileUploadUtil.getParameter(items, "ReturnURL"); if (!StringUtil.isDefined(returnURL)) { destination = getDestination("ViewVersions", versioningSC, request); } else { request.setAttribute("urlToReload", returnURL); destination = rootDestination + "closeWindow.jsp"; } } } else { destination = rootDestination + function; } } catch (Exception e) { SilverTrace.error("versioning", "VersioningRequestRouter.getDestination", "root.EX_CANT_GET_REQUEST_DESTINATION", e); request.setAttribute("javax.servlet.jsp.jspException", e); destination = "/admin/jsp/errorpageMain.jsp"; } SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Destination=" + destination); return destination; }
From source file:twity.TwityServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html;charset=UTF-8"); if (!YAPOAuth.verifySignature(req, YAP_CK, YAP_CKS)) { return;// w ww .ja v a 2s . co m } String guid = req.getParameter("yap_viewer_guid"); if (StringUtils.isBlank(guid)) { return; } OAuthConsumer consumer = new DefaultOAuthConsumer(TWIT_CK, TWIT_CKS, SignatureMethod.HMAC_SHA1); OAuthProvider provider = new DefaultOAuthProvider(consumer, TWIT_RT_URL, TWIT_AT_URL, TWIT_AUTH_URL); provider.setOAuth10a(true); try { if (cache.contains(guid + ":RT")) { JSONObject token = new JSONObject(((String) cache.get(guid + ":RT"))); cache.delete(guid + ":RT"); consumer.setTokenWithSecret(token.getString("token"), token.getString("secret")); String verifier = req.getParameter("verifier"); if (null != verifier) { provider.retrieveAccessToken(verifier); persistUser(guid, consumer); } } User u = fetchUser(guid); if (null != u) { consumer.setTokenWithSecret(u.getAccessToken(), u.getAccessTokenSecret()); Twitter t = new Twitter(consumer, guid); String status = req.getParameter("status"); String rCrumb = req.getParameter("crumb"); if (null != status && !"".equals(status)) { String storedCrumb = (String) cache.get(guid + ":CRUMB"); cache.delete(guid + ":CRUMB"); if (storedCrumb.equals(rCrumb)) { status = status.trim(); t.updateStatus(status); } } String id = req.getParameter("id"); if (null != id && "insertTweets".equals(id)) { req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); resp.getWriter().print(generateMarkup(t.fetchUserFriendTweets())); return; } JSONObject data = t.fetchUserData(); req.setAttribute("screen_name", data.optString("screen_name")); req.setAttribute("profile_text_color", data.optString("profile_text_color")); req.setAttribute("profile_background_color", data.optString("profile_background_color")); req.setAttribute("profile_background_image_url", data.optString("profile_background_image_url")); String tweetMarkup = generateMarkup(t.fetchUserFriendTweets()); req.setAttribute("tweets", tweetMarkup); // Generate session crumb String sessionCrumb = Integer.toString(new Random().nextInt()); req.setAttribute("crumb", sessionCrumb); cache.put(guid + ":CRUMB", sessionCrumb); getServletContext().getRequestDispatcher("/index.jsp").forward(req, resp); return; } //The callback is a proxy that simply rewrites the oauth_verifier to verifier (YAP Hack) String authUrl = provider.retrieveRequestToken("http://chiarg.com/redirect.php"); cache.put(guid + ":RT", new JSONObject().put("token", consumer.getToken()) .put("secret", consumer.getTokenSecret()).toString()); req.setAttribute("authUrl", authUrl); getServletContext().getRequestDispatcher("/auth.jsp").forward(req, resp); } catch (Exception e) { e.printStackTrace(); System.err.println("Error: " + e.getMessage()); } }