public ActionForward save( ActionMapping mapping, ActionForm aform, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(false); UserCredential credential = (UserCredential) session.getAttribute("Credential"); StudAffairManager sam = (StudAffairManager) getBean("studAffairManager"); ScoreManager sm = (ScoreManager) getBean("scoreManager"); DynaActionForm form = (DynaActionForm) aform; String classInCharge = credential.getClassInChargeSqlFilterSAF(); ActionMessages messages = validateInput(form); if (!messages.isEmpty()) { saveErrors(request, messages); session.setAttribute("ScoreSetDateEdit", form.getMap()); return mapping.findForward("Main"); } else { try { String level = form.getString("level"); String levelSel = form.getString("levelSel"); String depart = form.getString("depart"); String departSel = form.getString("departSel"); String beginDate = form.getString("beginDate"); String beginTime = form.getString("beginTime"); String endDate = form.getString("endDate"); String endTime = form.getString("endTime"); messages = sm.createUploadDateByForm(form); if (!messages.isEmpty()) { messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Message.CreateFailure")); saveErrors(request, messages); session.setAttribute("ScoreSetDateEdit", form.getMap()); return mapping.findForward("Main"); } messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Message.CreateSuccessful")); saveMessages(request, messages); session.removeAttribute("ScoreSetDateEdit"); return mapping.findForward("Main"); } catch (Exception e) { ActionMessages errors = new ActionMessages(); e.printStackTrace(); errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Exception.generic", e.getMessage())); saveErrors(request, errors); session.setAttribute("ScoreSetDateEdit", form.getMap()); return mapping.findForward("Main"); } } }
/** * 删除会议主题 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ protected ActionForward doDelete( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SubjectForm sub = (SubjectForm) form; ActionMessages msgs = new ActionMessages(); // 判断用户是否登录 UserBean loginUser = super.getLoginUser(request, response); if (loginUser == null) msgs.add("err", new ActionMessage("error.need_login")); else if (loginUser.getIsAdmin() != UserBean.TRUE) msgs.add("err", new ActionMessage("error.can_not_access")); else { try { // 完成数据操作 if (SubjectDAO.isDelete(sub.getId())) SubjectDAO.delete(sub.getId()); else msgs.add("err", new ActionMessage("error.subject.used")); } catch (Exception e) { msgs.add("err", new ActionMessage("error.db")); log.error("database error when delete subject", e); } } if (!msgs.isEmpty()) { saveMessages(request, msgs); return mapping.findForward("error"); } return mapping.getInputForward(); }
/** * 處理確定更新學生選課內容之方法 * * @param mapping org.apache.struts.action.ActionMapping object * @param form org.apache.struts.action.ActionForm object * @param request javax.servlet.http.HttpServletRequest object * @param response javax.servlet.http.HttpServletResponse object * @return org.apache.struts.action.ActionForward object * @exception java.lang.Exception */ public ActionForward update( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm aForm = (DynaActionForm) form; ActionMessages messages = validateInputForUpdate(aForm, Toolket.getBundle(request)); if (!messages.isEmpty()) { saveErrors(request, messages); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } else { try { Short selectLimit = (Short) aForm.get("selectLimit"); CourseManager cm = (CourseManager) getBean(COURSE_MANAGER_BEAN_NAME); cm.txUpdateDtimeSelLimit(aForm.getString("dtimeOid"), selectLimit); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Message.ModifySuccessful")); saveMessages(request, messages); Toolket.resetCheckboxCookie(response, SELD_LIST_NAME); return mapping.findForward(IConstants.ACTION_SUCCESS_NAME); } catch (Exception e) { ActionMessages errors = new ActionMessages(); errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Exception.generic", e.getMessage())); saveErrors(request, errors); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } } }
/** * 處理選擇修改學生選課內容之方法 * * @param mapping org.apache.struts.action.ActionMapping object * @param form org.apache.struts.action.ActionForm object * @param request javax.servlet.http.HttpServletRequest object * @param response javax.servlet.http.HttpServletResponse object * @return org.apache.struts.action.ActionForward object * @exception java.lang.Exception */ public ActionForward modify( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm aForm = (DynaActionForm) form; ActionMessages messages = validateInputForUpdate(aForm, Toolket.getBundle(request)); if (!messages.isEmpty()) { saveErrors(request, messages); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } else { String studentNo = aForm.getString("stdNo"); ScoreManager sm = (ScoreManager) getBean(SCORE_MANAGER_BEAN_NAME); Student student = sm.findStudentByStudentNo(studentNo); aForm.set("stdName", student.getStudentName()); aForm.set("stdClassName", Toolket.getClassFullName(student.getDepartClass())); SeldDataInfo sdi = getSeldDataInfoByIndex(request); if (sdi == null) { messages = new ActionMessages(); messages.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Course.onlineAddRemoveCourse.unselected")); saveErrors(request, messages); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } request.setAttribute(SELD_DATA_INFO, sdi); } setContentPage(request.getSession(false), "course/ModifyCourse.jsp"); return mapping.findForward(IConstants.ACTION_MAIN_NAME); }
/** * 處理學生加選線上選課紀錄之方法 * * @param mapping org.apache.struts.action.ActionMapping object * @param form org.apache.struts.action.ActionForm object * @param request javax.servlet.http.HttpServletRequest object * @param response javax.servlet.http.HttpServletResponse object * @return org.apache.struts.action.ActionForward object * @exception java.lang.Exception */ public ActionForward addCourse( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm aForm = (DynaActionForm) form; ActionMessages messages = validateInputForUpdate(aForm, Toolket.getBundle(request)); if (!messages.isEmpty()) { saveErrors(request, messages); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } else { String stdNo = aForm.getString("stdNo"); ScoreManager sm = (ScoreManager) getBean(SCORE_MANAGER_BEAN_NAME); Student student = sm.findStudentByStudentNo(stdNo); if (student != null) { aForm.set("stdName", student.getStudentName()); aForm.set("stdClassName", Toolket.getClassFullName(student.getDepartClass())); aForm.set("sterm", "1"); aForm.set("classNo", ""); aForm.set("csCode", ""); } else { messages.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Course.errorN1", "查無此人個人資料")); saveErrors(request, messages); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } } setContentPage(request.getSession(false), "course/OnlineAddCourse.jsp"); return mapping.findForward(IConstants.ACTION_MAIN_NAME); }
/** * Process the specified HTTP request, and create the corresponding HTTP response (or forward to * another web component that will create it). Return an <code>ActionForward</code> instance * describing where and how control should be forwarded, or <code>null</code> if the response has * already been completed. * * @param form * @param req * @param res * @param mapping The ActionMapping used to select this instance * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs * @return destination */ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { ActionMessages errors = new ActionMessages(); ActionForward destination = null; if (!this.checkLogon(req)) { return mapping.findForward("logon"); } Integer action; try { action = Integer.parseInt(req.getParameter("action")); } catch (Exception e) { action = BlacklistAction.ACTION_LIST; } AgnUtils.logger().info("Action: " + action); try { destination = executeIntern(mapping, req, errors, destination, action); } catch (Exception e) { AgnUtils.logger().error("execute: " + e + "\n" + AgnUtils.getStackTrace(e)); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception")); } // Report any errors we have discovered back to the original form if (!errors.isEmpty()) { saveErrors(req, errors); } return destination; }
/** * 修改 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward ok( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm dForm = (DynaActionForm) form; ActionMessages error = new ActionMessages(); // 建立共用錯誤訊息 ActionMessages msg = new ActionMessages(); CourseManager manager = (CourseManager) getBean("courseManager"); String no[] = dForm.getStrings("no"); String sname[] = dForm.getStrings("sname"); String school_name[] = dForm.getStrings("school_name"); String fname[] = dForm.getStrings("fname"); String dname[] = dForm.getStrings("dname"); String engname[] = dForm.getStrings("engname"); String Oid[] = dForm.getStrings("Oid"); String editCheck[] = dForm.getStrings("editCheck"); Member me = getUserCredential(request.getSession(false)).getMember(); for (int i = 1; i < Oid.length; i++) { // System.out.println("editCheck["+i+"]="+editCheck[i]); if (!editCheck[i].equals("")) { if (!no[i].equals("")) { Dept dept = (Dept) manager.hqlGetBy("FROM Dept WHERE Oid='" + Oid[i] + "'").get(0); dept.setDname(dname[i]); dept.setEngname(engname[i]); dept.setFname(fname[i]); dept.setLastEditUser(me.getIdno()); dept.setNo(no[i]); dept.setSchoolName(school_name[i]); dept.setLastEditTime(new Date()); dept.setSname(sname[i]); try { manager.updateObject(dept); } catch (Exception e) { e.printStackTrace(); error.add( ActionErrors.GLOBAL_MESSAGE, new ActionError("Course.messageN1", dept.getFname() + "修改失敗")); } } } } if (!error.isEmpty()) { saveErrors(request, error); return unspecified(mapping, form, request, response); } else { // msg.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("Course.messageN1", "修改完成")); saveMessages(request, msg); } return unspecified(mapping, form, request, response); }
/** * 留言板之发表留言 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ protected ActionForward doCreate( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { GuestBookForm msgform = (GuestBookForm) form; super.validateClientId(request, msgform); ActionMessages msgs = new ActionMessages(); while (true) { if (StringUtils.isEmpty(msgform.getContent())) { msgs.add("content", new ActionMessage("error.empty_content")); break; } UserBean loginUser = super.getLoginUser(request, response); if (loginUser == null) { msgs.add("message", new ActionMessage("error.user_not_login")); break; } else if (loginUser.getStatus() != UserBean.STATUS_NORMAL) { msgs.add("message", new ActionMessage("error.user_not_available")); break; } SiteBean site = super.getSiteByID(msgform.getSid()); if (site == null) { msgs.add("message", new ActionMessage("error.site_not_available")); break; } // 检查黑名单 if (isUserInBlackList(site, loginUser)) { msgs.add("message", new ActionMessage("error.user_in_blacklist")); break; } GuestBookBean msgbean = new GuestBookBean(); String content = super.autoFiltrate(site, msgform.getContent()); if (content.length() > MAX_GB_COUNT_LENGTH) content = content.substring(0, MAX_GB_COUNT_LENGTH); msgbean.setContent(super.filterScriptAndStyle(content)); msgbean.setClient(new ClientInfo(request, 0)); msgbean.setUser(loginUser); msgbean.setSiteId(site.getId()); try { GuestBookDAO.createMsg(msgbean); } catch (HibernateException e) { context().log("undelete diary failed.", e); msgs.add("message", new ActionMessage("error.database", e.getMessage())); } break; } if (!msgs.isEmpty()) { saveMessages(request, msgs); return mapping.findForward("pub"); } return makeForward(mapping.findForward("list"), msgform.getSid()); }
protected ActionForward doPublished( final ActionMapping mapping, final ActionForm form, final HttpServletRequest request, final HttpServletResponse response) throws Exception { ActionMessages msgs = new ActionMessages(); // 判断用户是否登录 UserBean loginUser = super.getLoginUser(request, response); if (loginUser == null) msgs.add("err", new ActionMessage("error.need_login")); else if (loginUser.getIsAdmin() != UserBean.TRUE) msgs.add("err", new ActionMessage("error.can_not_access")); else { try { String[] lang = request.getParameterValues("publish"); String isdefault = request.getParameter("isdefault"); List langlist = LangDAO.getLanglist(); String[] nopublish = null; int count = 0; if (lang.length < langlist.size()) { nopublish = new String[langlist.size() - lang.length]; for (int i = 0; i < langlist.size(); i++) { LangBean lb = (LangBean) langlist.get(i); for (int j = 0; j < lang.length; j++) { if (!lang[j].equals((lb.getId() + "").trim())) { nopublish[count] = lb.getId() + ""; count++; } } } } if (nopublish != null && nopublish.length > 0) { for (int m = 0; m < nopublish.length; m++) { LangBean lbn = LangDAO.getLang(Integer.parseInt(nopublish[m])); lbn.setPublished(LangBean.LANG_PUBLISHED_NOT); lbn.setIsDefault(LangBean.LANG_ISDEDAULT_NOT); LangDAO.updateLang(lbn); } } LangDAO.updatePublished(lang, isdefault); } catch (Exception e) { msgs.add("err", new ActionMessage("error.db")); log.error("database error when update site_setting", e); } } if (!msgs.isEmpty()) { saveMessages(request, msgs); return mapping.findForward("error"); } return mapping.findForward(null); }
/** * 處理學生退選線上選課紀錄之方法 * * @param mapping org.apache.struts.action.ActionMapping object * @param form org.apache.struts.action.ActionForm object * @param request javax.servlet.http.HttpServletRequest object * @param response javax.servlet.http.HttpServletResponse object * @return org.apache.struts.action.ActionForward object * @exception java.lang.Exception */ public ActionForward deleteCourse( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm aForm = (DynaActionForm) form; ActionMessages messages = validateInputForUpdate(aForm, Toolket.getBundle(request)); if (!messages.isEmpty()) { saveErrors(request, messages); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } else { List<SeldDataInfo> aList = getSeldDataListByIndex(request); if (!aList.isEmpty()) { CourseManager cm = (CourseManager) getBean(COURSE_MANAGER_BEAN_NAME); // 取得選課欲退選之Oid列表 StringBuffer seldBuf = new StringBuffer(); for (SeldDataInfo info : aList) { seldBuf.append(info.getSeldOid()).append(","); } String inSyntax = StringUtils.substringBeforeLast(seldBuf.toString(), ","); log.info("Seld Oid SQL IN Syntax : " + inSyntax); String studentNo = aForm.getString("stdNo").toUpperCase(); MemberManager mm = (MemberManager) getBean(MEMBER_MANAGER_BEAN_NAME); String classNo = mm.findStudentByNo(studentNo).getDepartClass(); // 只有第一階段不會檢查選課人數下限 cm.txRemoveSelectedSeld(studentNo, classNo, 1, inSyntax, false); String idno = getUserCredential(request.getSession(false)).getMember().getIdno(); for (SeldDataInfo info : aList) { cm.txSaveAdcdHistory(info.getDtimeOid(), studentNo.toUpperCase(), idno, "D"); } messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Message.DeleteSuccessful")); saveMessages(request, messages); // aForm.initialize(mapping); Toolket.resetCheckboxCookie(response, SELD_LIST_NAME); setContentPage(request.getSession(false), "course/OnlineAddRemoveCourse.jsp"); } else { messages = new ActionMessages(); messages.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Course.onlineAddRemoveCourse.unselected")); saveErrors(request, messages); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } } return list(mapping, form, request, response); }
/** * 添加或修改会议主题 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ protected ActionForward doAddOrModify( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SubjectForm sub = (SubjectForm) form; ActionMessages msgs = new ActionMessages(); // 判断用户是否登录 UserBean loginUser = super.getLoginUser(request, response); if (loginUser == null) msgs.add("err", new ActionMessage("error.need_login")); else if (loginUser.getIsAdmin() != UserBean.TRUE) msgs.add("err", new ActionMessage("error.can_not_access")); else if (StringUtils.isEmpty(sub.getSubject())) msgs.add("err", new ActionMessage("error.suject.not.null")); else { try { SubjectBean sbean = null; Timestamp ts = new Timestamp(System.currentTimeMillis()); if (sub.getId() > 0) { // 从数据库中读取主题信息 sbean = SubjectDAO.getSubject(sub.getId()); if (sbean == null) msgs.add("err", new ActionMessage("error.unknow")); else { sbean.setSubject(sub.getSubject()); sbean.setUpdateTime(ts); SubjectDAO.update(sbean); } } else { sbean = new SubjectBean(); sbean.setSubject(sub.getSubject()); sbean.setUpdateTime(ts); sbean.setRegTime(ts); SubjectDAO.save(sbean); } } catch (Exception e) { msgs.add("err", new ActionMessage("error.db")); log.error("database error when add or modify subject", e); } } if (!msgs.isEmpty()) { saveMessages(request, msgs); return mapping.findForward("error"); } return mapping.getInputForward(); }
/** * Process the specified HTTP request, and create the corresponding HTTP response (or forward to * another web component that will create it). Return an <code>ActionForward</code> instance * describing where and how control should be forwarded, or <code>null</code> if the response has * already been completed. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @exception Exception if business logic throws an exception */ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Extract attributes we will need User user = null; // Validate the request parameters specified by the user ActionMessages errors = new ActionMessages(); String username = (String) PropertyUtils.getSimpleProperty(form, "username"); String password = (String) PropertyUtils.getSimpleProperty(form, "password"); UserDatabase database = (UserDatabase) servlet.getServletContext().getAttribute(Constants.DATABASE_KEY); if (database == null) errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.database.missing")); else { user = getUser(database, username); if ((user != null) && !user.getPassword().equals(password)) user = null; if (user == null) errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.password.mismatch")); } // Report any errors we have discovered back to the original form if (!errors.isEmpty()) { saveErrors(request, errors); return (mapping.getInputForward()); } // Save our logged-in user in the session HttpSession session = request.getSession(); session.setAttribute(Constants.USER_KEY, user); if (log.isDebugEnabled()) { log.debug( "LogonAction: User '" + user.getUsername() + "' logged on in session " + session.getId()); } // Remove the obsolete form bean if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else session.removeAttribute(mapping.getAttribute()); } // Forward control to the specified success URI return (mapping.findForward("success")); }
/** * Method execute * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws ConfigurationException */ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ConfigurationException { XmlEditSaveAndApplyForm saveXmlForm = (XmlEditSaveAndApplyForm) form; String fileName = saveXmlForm.getFileName(); String dirName = Configuration.params.getConfigDir(); String path = dirName + "/" + fileName; ActionMessages errors = new ActionMessages(); String err; try { FileOutputStream outFile = new FileOutputStream(path); String content = saveXmlForm.getContent(); err = writeContent(outFile, "utf-8", content); if (err != "") { errors.add("errors.writecontent", new ActionMessage(err, "")); } Configuration conf = new Configuration(); Configuration.params.setBooksFile(fileName); Configuration.saveParams(); conf.destroy(); conf.init(); } catch (FileNotFoundException e) { errors.add("errors.filenotfound", new ActionMessage("FileNotFoundException", "")); } catch (ConfigurationException e) { errors.add("errors.configuration", new ActionMessage("ConfigurationException", "")); } if (errors.isEmpty() == false) { saveErrors(request, errors); } else { request.setAttribute("success", "1"); } return mapping.getInputForward(); }
/** 保存对象的Action函数. */ public ActionForward save( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { if (isCancelled(request)) return list(mapping, form, request, response); if (!isTokenValid(request)) { saveDirectlyError(request, "重复提交"); return mapping.findForward(LIST); } resetToken(request); // run validation rules on this form ActionMessages errors = form.validate(mapping, request); if (!errors.isEmpty()) { saveErrors(request, errors); refrenceData(request); return mapping.findForward(EDIT); } T object; // 如果是修改操作,id is not blank if (StringUtils.isNotBlank(request.getParameter(idName))) { object = doGetEntity(form, request); if (object == null) { saveError(request, "entity.missing"); return mapping.findForward(LIST); } } else { // 否则为新增操作 object = doNewEntity(form, request); } try { // 将lazyform内容绑定到object initEntity(form, request, object); doSaveEntity(form, request, object); savedMessage(request, object); } catch (BusinessException e) { log.error(e.getMessage(), e); saveDirectlyError(request, e.getMessage()); refrenceData(request); return mapping.findForward(EDIT); } return mapping.findForward(SUCCESS); }
/** * 增加主机服务 * * @param mapping . * @param form . * @param request . * @param response . * @return . * @throws Exception . */ public ActionForward addMonitorService( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); MonitorService monitorService = (MonitorService) ((DynaActionForm) form).get("monitorService"); String type = (String) ((DynaActionForm) form).get("type"); DependencyUtil.clearDependencyProperty(monitorService); monitorHostserviceService.saveMonitorService(monitorService); if (!errors.isEmpty()) { saveErrors(request, errors); return mapping.findForward("input"); } else { return mapping.findForward("success"); } }
public ActionForward DelConfirm( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(false); List<Keep> selKeeps = (List<Keep>) session.getAttribute("StudInspectedDelete"); StudAffairManager sm = (StudAffairManager) getBean("studAffairManager"); ActionMessages errs = sm.delStudInspected(selKeeps, Toolket.getBundle(request, "messages.studaffair")); session.removeAttribute("StudInspectedDelete"); // no undeleteScores will happen even if delete failure if (errs.isEmpty()) { session.removeAttribute("StudInspectedList"); setContentPage(session, "studaffair/StudInspected.jsp"); return mapping.findForward("Main"); } else { saveErrors(request, errs); setContentPage(session, "studaffair/StudInspected.jsp"); return mapping.findForward("Main"); } }
/** * 增加服务模板 * * @param mapping . * @param form . * @param request . * @param response . * @return . * @throws Exception . */ public ActionForward addMonitorServiceTemplate( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); try { MonitorServiceTemplate monitorServiceTemplate = (MonitorServiceTemplate) ((DynaActionForm) form).get("monitorServiceTemplate"); DependencyUtil.clearDependencyProperty(monitorServiceTemplate); templateService.saveMonitorServiceTemplate(monitorServiceTemplate); } catch (TemplateAlreadyExistException e) { errors.add("addMonitorServiceTemplate", new ActionMessage("errors.TemplateExist")); } if (!errors.isEmpty()) { saveErrors(request, errors); return mapping.findForward("input"); } else { return mapping.findForward("success"); } }
/** * 處理以學號查詢學生選課清單 * * @param mapping org.apache.struts.action.ActionMapping object * @param form org.apache.struts.action.ActionForm object * @param request javax.servlet.http.HttpServletRequest object * @param response javax.servlet.http.HttpServletResponse object * @return org.apache.struts.action.ActionForward object * @exception java.lang.Exception */ @SuppressWarnings("unchecked") public ActionForward list( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm aForm = (DynaActionForm) form; HttpSession session = request.getSession(false); Toolket.resetCheckboxCookie(response, SELD_LIST_NAME); // 確實清除變數"seldList"內所存資料,因學生可能無選課資料 session.removeAttribute(SELD_LIST_NAME); ActionMessages messages = validateInputForUpdate(aForm, Toolket.getBundle(request)); if (!messages.isEmpty()) { saveErrors(request, messages); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } else { try { CourseManager cm = (CourseManager) getBean(COURSE_MANAGER_BEAN_NAME); log.info("Student NO : " + aForm.getString("stdNo")); List<Map> seldList = doForDuplicate(cm.getSeldDataByStudentNo(aForm.getString("stdNo"), "1")); if (!seldList.isEmpty()) { session.setAttribute("NO", aForm.getString("stdNo").toUpperCase()); int hours = 0, position = 0; float credit = 0.0F; List<SeldDataInfo> result = new ArrayList<SeldDataInfo>(); SeldDataInfo info = null; for (Map content : seldList) { info = new SeldDataInfo(); Integer dtimeOid = (Integer) content.get("oid"); info.setClassNo((String) content.get("classNo")); info.setClassName((String) content.get("className")); info.setCsCode((String) content.get("cscode")); info.setCsName((String) content.get("chi_Name")); info.setStuSelect(String.valueOf(cm.findSeldCountByDtimeOid(dtimeOid))); info.setSelectLimit(((Integer) content.get("select_Limit")).toString()); info.setHour(Short.valueOf(((Integer) content.get("thour")).toString())); info.setCredit((Float) content.get("credit")); info.setSeldOid((Integer) content.get("soid")); // Seld Oid String opt = (String) content.get("opt"); info.setOpt(opt); info.setOptName(Toolket.getCourseOpt(opt)); info.setDtimeOid(dtimeOid); // Dtime Oid info.setPosition(Integer.valueOf(position++)); info.setTerm((String) content.get("sterm")); hours += ((Integer) content.get("thour")).intValue(); credit += ((Float) content.get("credit")).floatValue(); result.add(info); } session.setAttribute(SELD_LIST_COUNT, Integer.valueOf(seldList.size())); session.setAttribute(SELD_LIST_HOURS, Integer.valueOf(hours)); session.setAttribute( SELD_LIST_CREDITS, Float.valueOf(new DecimalFormat("0.0").format(credit))); session.setAttribute(SELD_LIST_NAME, result); session.setAttribute("mode", "ALL"); } else { // 查無資料則回傳空白List session.setAttribute(SELD_LIST_NAME, Collections.EMPTY_LIST); session.setAttribute("mode", "NONE"); ActionMessages msg = new ActionMessages(); msg.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Course.messageN1", "查無任何選課資料!!")); saveMessages(request, msg); } } catch (Exception e) { ActionMessages errors = new ActionMessages(); errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Exception.generic", e.getMessage())); saveErrors(request, errors); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } } setContentPage(request.getSession(false), "course/OnlineAddRemoveCourse.jsp"); return mapping.findForward(IConstants.ACTION_MAIN_NAME); }
// Esta función guarda en la base de datos correspondiente los dias seleccionados en la página. public ActionForward saveFixedHolidays( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, SessionAPI session) throws Exception { // Comprobar si el usuario tiene asignadas las funciones adecuadas FunctionHelper.checkFunctions( request, session.getClientContext(), new int[] {ISecurityAPI.FUNC_COMP_CALENDARS_EDIT}); ClientContext cct = session.getClientContext(); CalendarForm defaultForm = (CalendarForm) form; String[] selectFixedHolidays = (String[]) defaultForm.getSelectFixedHolidays(); String year = (String) defaultForm.getProperty("YEAR"); // Validación ActionMessages errors = new ActionMessages(); defaultForm.setEntityAppName("EditCTCalendar"); errors = defaultForm.validate(mapping, request); if (errors.isEmpty()) { String entityId = defaultForm.getEntity(); String regId = defaultForm.getKey(); String nombre = request.getParameter("nombre"); String dias = request.getParameter("weekDaysSelect"); // Ejecución en un contexto transaccional boolean bCommit = false; try { // Abrir transacción cct.beginTX(); IInvesflowAPI invesFlowAPI = session.getAPI(); ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI(); // Bloquear catalogAPI.queryCTEntities(ICatalogAPI.ENTITY_SPAC_CALENDARIOS, ""); IItem item = (IItem) request.getSession().getAttribute("CALENDAR"); String calendarioXML = (String) item.getString("CALENDARIO"); CalendarDef calendarDef = new CalendarDef(calendarioXML); for (int i = 0; i < selectFixedHolidays.length; i++) { String[] date = selectFixedHolidays[i].split("---"); ActionMessages errorsFixedHolidays = new ActionMessages(); validateHolyday(item, date[0] + "/" + year, session, errorsFixedHolidays); if (errorsFixedHolidays.isEmpty()) { calendarDef.addHolyday(date[1], date[0] + "/" + year); } } item.set("CALENDARIO", calendarDef.getXmlValues()); item.store(session.getClientContext()); // Si todo ha sido correcto se hace commit de la transacción bCommit = true; String url = "?method=show&entityId=" + entityId + "®Id=" + regId + "&save=true&nombre=" + nombre + "&weekDaysSelect=" + dias; request.setAttribute("target", "top"); request.setAttribute("url", url); return mapping.findForward("loadOnTarget"); } catch (ISPACException e) { throw new ISPACInfo(e.getMessage()); } finally { cct.endTX(bCommit); } } saveErrors(request, errors); request.setAttribute(DAYS_LIST, request.getAttribute(DAYS_LIST)); return mapping.findForward("errorYear"); }
public ActionForward saveholydays( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, SessionAPI session) throws Exception { // Comprobar si el usuario tiene asignadas las funciones adecuadas FunctionHelper.checkFunctions( request, session.getClientContext(), new int[] {ISecurityAPI.FUNC_COMP_CALENDARS_EDIT}); ClientContext cct = session.getClientContext(); CalendarForm defaultForm = (CalendarForm) form; // Validar el formulario defaultForm.setEntityAppName("SaveHolydaysCalendar"); ActionMessages errors = defaultForm.validate(mapping, request); String entityId = defaultForm.getEntity(); String regId = defaultForm.getKey(); String nombre = request.getParameter("nombre"); String dias = request.getParameter("weekDaysSelect"); // Ejecución en un contexto transaccional boolean bCommit = false; try { // Abrir transacción cct.beginTX(); if (errors.isEmpty()) { IInvesflowAPI invesFlowAPI = session.getAPI(); ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI(); // Bloqueo catalogAPI.queryCTEntities(ICatalogAPI.ENTITY_SPAC_CALENDARIOS, ""); IItem item = (IItem) request.getSession().getAttribute("CALENDAR"); // deberia ir abajo String calendarioXML = (String) item.getString("CALENDARIO"); validateHolyday(item, defaultForm.getProperty("HOLYDAY_DATE"), session, errors); if (!errors.isEmpty()) { saveErrors(request, errors); return mapping.findForward("success_holydays"); } CalendarDef calendarDef = new CalendarDef(calendarioXML); calendarDef.addHolyday( defaultForm.getProperty("HOLYDAY_NAME"), defaultForm.getProperty("HOLYDAY_DATE")); item.set("CALENDARIO", calendarDef.getXmlValues()); item.store(session.getClientContext()); // Si todo ha sido correcto se hace commit de la transacción bCommit = true; // Para que vaya a la direccion donde yo quiero String url = "?method=show&entityId=" + entityId + "®Id=" + regId + "&save=true&nombre=" + nombre + "&weekDaysSelect=" + dias; request.setAttribute("target", "top"); request.setAttribute("url", url); return mapping.findForward("loadOnTarget"); } else { saveErrors(request, errors); return getActionForwardHolydays(); } } catch (ISPACException e) { throw new ISPACInfo(e.getMessage()); } finally { cct.endTX(bCommit); } }
/** * 處理確定加選學生選課內容之方法 * * @param mapping org.apache.struts.action.ActionMapping object * @param form org.apache.struts.action.ActionForm object * @param request javax.servlet.http.HttpServletRequest object * @param response javax.servlet.http.HttpServletResponse object * @return org.apache.struts.action.ActionForward object * @exception java.lang.Exception */ public ActionForward add( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CourseManager cm = (CourseManager) getBean(COURSE_MANAGER_BEAN_NAME); HttpSession session = request.getSession(false); DynaActionForm aForm = (DynaActionForm) form; Seld seld = processSeldByForm(aForm); session.setAttribute("seldInfoForOnline", seld); Dtime dtime = cm.findDtimeBy(seld.getDtimeOid()); ActionMessages messages = validateInputForUpdate(aForm, Toolket.getBundle(request)); if (!messages.isEmpty()) { saveErrors(request, messages); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } else { try { // 會以紙本作業完成加選,無需考慮衝堂問題 // 選課人數上線於前端JavaScript判斷 // 跨選設定不允許須阻擋並顯示訊息 // 會顯示衝堂訊息 MemberManager mm = (MemberManager) getBean(MEMBER_MANAGER_BEAN_NAME); ScoreManager sm = (ScoreManager) getBean(IConstants.SCORE_MANAGER_BEAN_NAME); Student student = mm.findStudentByNo(seld.getStudentNo()); ScoreHist scoreHist = new ScoreHist(student.getStudentNo()); List<ScoreHist> scoreHistList = sm.findScoreHistBy(scoreHist); String[] cscodeHist = new String[0]; Float[] scoreList = new Float[0]; float passScore = Toolket.getPassScoreByDepartClass(student.getDepartClass()); for (ScoreHist hist : scoreHistList) { cscodeHist = (String[]) ArrayUtils.add(cscodeHist, hist.getCscode().toUpperCase()); // 抵免要給分數,不然就會被當做無修課記錄而被加選成功 if ("6".equals(hist.getEvgrType())) scoreList = (Float[]) ArrayUtils.add( scoreList, hist.getScore() != null ? hist.getScore() : passScore); else scoreList = (Float[]) ArrayUtils.add(scoreList, hist.getScore()); } int ind = 0, startIndex = 0; boolean isHist = false; do { ind = ArrayUtils.indexOf(cscodeHist, seld.getCscode().toUpperCase(), startIndex); startIndex = ind + 1; // 判斷是否選過且及格 isHist = ind != StringUtils.INDEX_NOT_FOUND && scoreList[ind] != null && scoreList[ind] >= passScore; } while (!isHist && ind != StringUtils.INDEX_NOT_FOUND); // 特殊班級(跨校生等)無條件加選 String[] specialDepartClass = {"1152A", "1220", "122A", "122B", "2220"}; String[] addGrade = {"42", "52"}; // 2技學生年級要+2 int stuGrade = ArrayUtils.contains(specialDepartClass, student.getDepartClass()) ? 9 : Integer.parseInt(StringUtils.substring(student.getDepartClass(), 4, 5)); stuGrade = ArrayUtils.contains(addGrade, StringUtils.substring(student.getDepartClass(), 1, 3)) ? stuGrade + 2 : stuGrade; int dtimeGrade = Integer.parseInt(StringUtils.substring(dtime.getDepartClass(), 4, 5)); if (isHist) { messages.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Course.errorN1", "歷年資料查詢到已修過該科目,請確認,謝謝!!")); saveErrors(request, messages); } else if (stuGrade >= dtimeGrade) { // 判斷學生年級與課程所開班級年級 cm.txAddSelectedSeld(seld, student, "1", true); String idno = getUserCredential(request.getSession(false)).getMember().getIdno(); cm.txSaveAdcdHistory(seld.getDtimeOid(), student.getStudentNo().toUpperCase(), idno, "A"); if (ind != StringUtils.INDEX_NOT_FOUND) messages.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Course.errorN1", "該科目於歷年資料有查詢到,但該科目未及格,所以加選成功。")); else messages.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Message.CreateSuccessful")); saveMessages(request, messages); } else { messages.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "Course.messageN1", "注意:學生低修高年級課程,加選作業尚未完成!<br/>" + " 按下[再次確定]鍵後課程才會加入學生選課資料中。")); saveErrors(request, messages); setContentPage(request.getSession(false), "course/OnlineAddHigherCourse.jsp"); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } Toolket.resetCheckboxCookie(response, SELD_LIST_NAME); return list(mapping, form, request, response); } catch (SeldException se) { ActionMessages errors = new ActionMessages(); errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Course.errorN1", se.getMessage())); saveErrors(request, errors); if (se.getMessage().indexOf("衝堂") != StringUtils.INDEX_NOT_FOUND) { // 目前會拒絕衝堂課程進行加選 dtime = cm.findDtimeBy(seld.getDtimeOid()); Csno csno = cm.findCourseInfoByCscode(dtime.getCscode()); request.setAttribute("csnoInfo", csno); request.setAttribute("classInfo", Toolket.getClassFullName(dtime.getDepartClass())); setContentPage(request.getSession(false), "course/ConflictList.jsp"); return list(mapping, form, request, response); } else return list(mapping, form, request, response); } } }
public ActionForward execute( ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { LazyValidatorForm frm = (LazyValidatorForm) actionForm; if (formCanceled(frm)) { return actionMapping.findForward(SUCCESS); } resetFocusControl(frm, CANCEL); ActionMessages msgs = new ActionMessages(); if (!formSaved(frm)) { setFormMode(frm, ((String) httpServletRequest.getParameter(BROWSE_ACTION))); setFormId(frm, (String) httpServletRequest.getParameter(BROWSE_ID)); try { LoginInfo loginInfo = getLoginInfo(httpServletRequest); if (!loginInfo.userHasAccess(getFormId(frm), getFormMode(frm))) { if (isFormInModifyMode(frm) && loginInfo.userHasAccess(getFormId(frm), Constants.ActionType.ENQUERY)) { setFormMode(frm, Constants.ActionType.ENQUERY); } else { throw new Exception(INVALID_ACCESS); } } if (!isFormInAddMode(frm)) { String formKey = (String) httpServletRequest.getParameter(BROWSE_KEY); VillageInfo inf = Geo.getVillageDetails(Integer.parseInt(formKey)); frm.set(GEO_SERIAL, Integer.toString(inf.getGeoSerial())); frm.set(GEO_DESC, inf.getGeoDesc()); frm.set(OSTAN_SERIAL, Integer.toString(inf.getOstanSerial())); frm.set(SHAHRESTAN_SERIAL, Integer.toString(inf.getShahrestanSerial())); frm.set(BAKHSH_SERIAL, Integer.toString(inf.getBakhshSerial())); frm.set(DEHESTAN_SERIAL, Integer.toString(inf.getDehestanSerial())); if (inf.isInactive()) { frm.set(CODE_ACTIVE_FLAG, "on"); } } else { frm.set(GEO_SERIAL, Integer.toString(Geo.getNewGeoSerial(Constants.GeoFlag.VILLAGE))); } String serial; serial = (String) frm.get(OSTAN_SERIAL); if (Utils.isEmpty(serial)) { serial = "0"; frm.set(OSTAN_SERIAL, serial); } frm.set(OSTAN_DESC, Geo.getOstanDesc(Integer.parseInt(serial))); serial = (String) frm.get(SHAHRESTAN_SERIAL); if (Utils.isEmpty(serial)) { serial = "0"; frm.set(SHAHRESTAN_SERIAL, serial); } frm.set(SHAHRESTAN_DESC, Geo.getShahrestanDesc(Integer.parseInt(serial))); serial = (String) frm.get(BAKHSH_SERIAL); if (Utils.isEmpty(serial)) { serial = "0"; frm.set(BAKHSH_SERIAL, serial); } frm.set(BAKHSH_DESC, Geo.getBakhshDesc(Integer.parseInt(serial))); serial = (String) frm.get(DEHESTAN_SERIAL); if (Utils.isEmpty(serial)) { serial = "0"; frm.set(DEHESTAN_SERIAL, serial); } frm.set(DEHESTAN_DESC, Geo.getDehestanDesc(Integer.parseInt(serial))); if (isFormInAddMode(frm)) { resetFocusControl(frm, GEO_SERIAL); } else if (isFormInModifyMode(frm)) { resetFocusControl(frm, GEO_DESC); } } catch (Exception ex) { addError(msgs, ex.getMessage()); saveErrors(httpServletRequest, msgs); } return actionMapping.findForward(EDIT); } else { VillageInfo inf = new VillageInfo(); String geoSerial = ((String) frm.get(GEO_SERIAL)).trim(); resetFocusControl(frm, ""); if (Utils.isEmpty(geoSerial)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "كد"); setFocusControl(frm, GEO_SERIAL); } else if (!Utils.isValidNotZeroNumber(geoSerial, 6)) { addError(msgs, FIELD_INVALID, "كد"); setFocusControl(frm, GEO_SERIAL); } else { inf.setGeoSerial(Integer.parseInt(geoSerial)); } if (!isFormInDeleteMode(frm)) { String geoDesc = Utils.charVal((String) frm.get(GEO_DESC)); frm.set(GEO_DESC, geoDesc); if (Utils.isEmpty(geoDesc)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "نام"); setFocusControl(frm, GEO_DESC); } else if (geoDesc.length() > 50) { addError(msgs, FIELD_INVALID, "نام"); setFocusControl(frm, GEO_DESC); } else { inf.setGeoDesc(geoDesc); } String ostanSerial = (String) frm.get(OSTAN_SERIAL).toString(); if (Utils.isEmpty(ostanSerial)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "استان"); setFocusControl(frm, GEO_DESC); } else if (!Utils.isValidNotZeroNumber(ostanSerial, 6)) { addError(msgs, FIELD_INVALID, "استان"); setFocusControl(frm, GEO_DESC); } else { inf.setOstanSerial(Integer.parseInt(ostanSerial)); } String shahrestanSerial = (String) frm.get(SHAHRESTAN_SERIAL).toString(); if (Utils.isEmpty(shahrestanSerial)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "شهرستان"); setFocusControl(frm, GEO_DESC); } else if (!Utils.isValidNotZeroNumber(shahrestanSerial, 6)) { addError(msgs, FIELD_INVALID, "شهرستان"); setFocusControl(frm, GEO_DESC); } else { inf.setShahrestanSerial(Integer.parseInt(shahrestanSerial)); } String bakhshSerial = (String) frm.get(BAKHSH_SERIAL).toString(); if (Utils.isEmpty(bakhshSerial)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "بخش"); setFocusControl(frm, GEO_DESC); } else if (!Utils.isValidNotZeroNumber(bakhshSerial, 6)) { addError(msgs, FIELD_INVALID, "بخش"); setFocusControl(frm, GEO_DESC); } else { inf.setBakhshSerial(Integer.parseInt(bakhshSerial)); } String dehestanSerial = (String) frm.get(DEHESTAN_SERIAL).toString(); if (Utils.isEmpty(dehestanSerial)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "دهستان"); setFocusControl(frm, GEO_DESC); } else if (!Utils.isValidNotZeroNumber(dehestanSerial, 6)) { addError(msgs, FIELD_INVALID, "دهستان"); setFocusControl(frm, GEO_DESC); } else { inf.setDehestanSerial(Integer.parseInt(dehestanSerial)); } if (Utils.isEmpty(frm.get(CODE_ACTIVE_FLAG))) { inf.setCodeActiveFlag(Constants.CodeActiveFlag.ACTIVE); } else { inf.setCodeActiveFlag(Constants.CodeActiveFlag.INACTIVE); } } if (!msgs.isEmpty()) { saveErrors(httpServletRequest, msgs); return actionMapping.findForward(EDIT); } resetFocusControl(frm, CANCEL); try { Geo.saveVillage(getFormMode(frm), inf); httpServletRequest.setAttribute(BROWSE_KEY, inf.getKey()); return actionMapping.findForward(SUCCESS); } catch (Exception ex) { resetFocusControl(frm, CANCEL); addError(msgs, ex.getMessage()); saveErrors(httpServletRequest, msgs); return actionMapping.findForward(EDIT); } } }
public ActionForward print( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws JRException, IOException, ServletException { MemberManager mm = (MemberManager) getBean(IConstants.MEMBER_MANAGER_BEAN_NAME); StudAffairManager sm = (StudAffairManager) getBean("studAffairManager"); StudAffairDAO dao = (StudAffairDAO) getBean("studAffairDAO"); HttpSession session = request.getSession(false); DynaActionForm aForm = (DynaActionForm) form; UserCredential user = (UserCredential) session.getAttribute("Credential"); String qty = aForm.getString("qty").trim(); boolean setupPrinter = false; boolean isPrint = false; ActionMessages messages = new ActionMessages(); if (!qty.equals("")) { String idno = user.getMember().getIdno(); String prefix = idno.substring(idno.length() - 5); int q = Integer.parseInt(qty); String[] codes = new String[q]; String rano = prefix + this.getRandom(4); String hql = "From AssessPaper Where serviceNo='" + rano + "' And idno='" + idno + "'"; // 建立服務編號 boolean isUniq = false; for (int j = 0; j < q; j++) { while (true) { rano = prefix + this.getRandom(4); isUniq = true; if (dao.submitQuery(hql).isEmpty()) { // 檢查服務編號是否重複 for (int k = 0; k < j; k++) { if (rano == codes[k]) { isUniq = false; break; } } if (isUniq) { codes[j] = rano; break; } } } } // Insert into DB ActionMessages msg = mm.addNewAssessPaper(idno, codes); if (!msg.isEmpty()) { messages.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("MessageN1", "滿意度調查列印資料新增失敗:" + msg)); saveErrors(request, messages); setContentPage(request, "personnel/AssessPaperPrint.jsp"); return mapping.findForward(IConstants.ACTION_MAIN_NAME); } // TODO: print the paper in pdf format String reportSourceFile = "/WEB-INF/reports/AssessPaper.jrxml"; String reportCompiledFile = "/WEB-INF/reports/AssessPaper.jasper"; List<Object> printData = new ArrayList<Object>(); ServletContext context = request.getSession().getServletContext(); JasperReportUtils.initJasperReportsClasspath(request); printData = fillPrintData(codes); DecimalFormat df = new DecimalFormat(",##0.0"); File reportFile = null; reportFile = new File(context.getRealPath(reportCompiledFile)); // 需要時再編譯即可 // if (!reportFile.exists()) { JasperReportUtils.compileJasperReports(context.getRealPath(reportSourceFile)); reportFile = new File(context.getRealPath(reportCompiledFile)); if (!reportFile.exists()) throw new JRRuntimeException("查無\"AssessPaper.jasper\"檔案,請電洽電算中心,謝謝!!"); // } Map<String, String> parameters = new HashMap<String, String>(); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportFile.getPath()); parameters.put("idno", idno); parameters.put("userName", user.getMember().getName()); parameters.put("PrintDate", Toolket.Date2Str(new Date())); // 列印日期 String[] fields = { "serviceNo0", "serviceNo1", "serviceNo2", "serviceNo3", "serviceNo4", "serviceNo5", "serviceNo6", "serviceNo7", "serviceNo8", "serviceNo9" }; JasperPrint jasperPrint = JasperFillManager.fillReport( jasperReport, parameters, new HibernateQueryResultDataSource(printData, fields)); // jasperPrint. // 列印或預覽 if (isPrint) { JasperPrintManager.printReport(jasperPrint, setupPrinter); } else { byte[] bytes = JasperRunManager.runReportToPdf( jasperReport, parameters, new HibernateQueryResultDataSource(printData, fields)); Calendar td = Calendar.getInstance(); String ran = "" + (td.get(Calendar.MINUTE)) + (td.get(Calendar.SECOND)) + (td.get(Calendar.MILLISECOND)); String ranDir = "/WEB-INF/reports/temp/" + ran; File tempdir = new File(context.getRealPath(ranDir)); if (!tempdir.exists()) tempdir.mkdirs(); OutputStream os = new BufferedOutputStream( new FileOutputStream(new File(context.getRealPath(ranDir + "/AssessPaper.pdf")))); JasperExportManager.exportReportToPdfStream(jasperPrint, os); JasperReportUtils.printPdfToFrontEnd(response, bytes); os.close(); Toolket.deleteDIR(tempdir); return null; } } else { messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("MessageN1", "請輸入欲列印張數!")); saveErrors(request, messages); } setContentPage(request, "personnel/AssessPaperPrint.jsp"); return unspecified(mapping, form, request, response); }
/** * 添加会议网站基本信息 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ protected ActionForward doSiteSetting( final ActionMapping mapping, final ActionForm form, final HttpServletRequest request, final HttpServletResponse response) throws Exception { LangForm lform = (LangForm) form; LangBean lbean = null; ActionMessages msgs = new ActionMessages(); // 判断用户是否登录 UserBean loginUser = super.getLoginUser(request, response); if (loginUser == null) msgs.add("err", new ActionMessage("error.need_login")); else if (loginUser.getIsAdmin() != UserBean.TRUE) msgs.add("err", new ActionMessage("error.can_not_access")); else { try { Timestamp ts = new Timestamp(System.currentTimeMillis()); int id = 1; String languange = StringUtils.exportString(request.getParameter("languange")); if (languange.equals("zh_cn")) { id = LangBean.LANG_ZH_CN; } if (languange.equals("zh_tw")) { id = LangBean.LANG_ZH_TW; } if (languange.equals("english")) { id = LangBean.LANG_ENGLISH; } boolean isSave = false; // 从数据库中读取设置信息 lbean = LangDAO.getLangByID(id); if (lbean == null) { lbean = new LangBean(); lbean.setId(id); isSave = true; } // 利用表单数据修改数据对象 String publishId = StringUtils.exportString(request.getParameter("publishId")); // 获取是否发布 String template = StringUtils.exportString(request.getParameter("template")); // 获得所选模板 String isdefault = request.getParameter("isdefault"); if (StringUtils.exportString(isdefault).equals("")) { isdefault = LangBean.LANG_PUBLISHED_NOT + ""; } if (StringUtils.isNotEmpty(languange)) lbean.setLanguange(languange); lbean.setIsDefault(Integer.parseInt(isdefault)); if (StringUtils.isNotEmpty(lform.getConfname())) lbean.setConfName(lform.getConfname()); if (StringUtils.isNotEmpty(lform.getShortname())) lbean.setShortName(lform.getShortname()); if (StringUtils.isNotEmpty(lform.getCopyright())) lbean.setCopyright(lform.getCopyright()); if (StringUtils.isNotEmpty(lform.getEmail())) lbean.setEmail(lform.getEmail()); if (lform.getShow1() != 0 || lform.getShow1() != 1) lbean.setShow1(lform.getShow1()); if (lform.getShow2() != 0 || lform.getShow2() != 1) lbean.setShow2(lform.getShow2()); lbean.setCreateTime(ts); lbean.setUpdateTime(ts); if (StringUtils.isNotEmpty(publishId)) lbean.setPublished(LangBean.LANG_PUBLISHED); // 如果取值不为空,则发布 if (StringUtils.isNotEmpty(template)) lbean.setTemplate(template); // 保存入数据库 if (isSave) { LangDAO.createLang(lbean); } else { LangDAO.updateLang(lbean); } } catch (Exception e) { msgs.add("err", new ActionMessage("error.db")); log.error("database error when save site_setting", e); } } if (!msgs.isEmpty()) { saveMessages(request, msgs); return mapping.findForward("error"); } request.setAttribute("lang", lbean); String fromPage = lform.getFromPage(); if (StringUtils.isNotEmpty(fromPage)) return new ActionForward(fromPage); return mapping.findForward("home.site"); }
public ActionForward save( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm aForm = (DynaActionForm) form; HttpSession session = request.getSession(false); Map initMap = (Map) session.getAttribute("TchScoreUploadInfo"); String scoretype = aForm.getString("scoretype"); String departClass = initMap.get("departClass").toString(); String cscode = initMap.get("cscode").toString(); String teacherId = initMap.get("teacherId").toString(); int dtimeoid = 0; ActionMessages messages = validateInputForUpdate(aForm, Toolket.getBundle(request)); if (!messages.isEmpty()) { saveErrors(request, messages); // request.removeAttribute("ScoreInputInit"); // log.debug("=======> Teacher Input score ValidateError='"); session.setAttribute("TchScoreUploadFormMap", aForm.getMap()); // session.setAttribute("ScoreInput", aForm.getStrings("scrinput")); return mapping.findForward("Main"); } else { ActionMessages errors = new ActionMessages(); try { List<Regs> regs = (List<Regs>) session.getAttribute("TchScoreInEdit"); ScoreManager sm = (ScoreManager) getBean("scoreManager"); dtimeoid = regs.get(0).getDtimeOid(); Map calscore = new HashMap(); // log.debug("ScoreMidTermEdit1Action->scr19f.size():" + scr19f.length); calscore.put("scr23f", scr23f); // errors = sm.updateScoreInput(aForm.getMap(), scores); errors = sm.updateTchScoreInput(aForm.getMap(), regs, calscore); if (!errors.isEmpty()) { saveErrors(request, errors); // request.removeAttribute("ScoreInputInit"); session.setAttribute("TchScoreUploadFormMap", aForm.getMap()); // session.setAttribute("ScoreInput", aForm.getStrings("scrinput")); return mapping.findForward("Main"); } Calendar now = Calendar.getInstance(); String nows = "" + (now.get(Calendar.YEAR) - 1911) + "/" + (now.get(Calendar.MONTH) + 1) + "/" + now.get(Calendar.DATE) + " " + now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND); errors = sm.updateRegsTime(dtimeoid, departClass, cscode, teacherId, scoretype, nows); if (!errors.isEmpty()) { saveErrors(request, errors); } int count = 0; String[] studentNames = new String[regs.size()]; Regs myregs; String[] score = (String[]) aForm.getMap().get("scr23"); String[] studentNos = (String[]) aForm.getMap().get("studentNo"); int scoresint = 0; int totalscore = 0; int totalstu = score.length; int nopass = 0; for (Iterator regsIter = regs.iterator(); regsIter.hasNext(); ) { myregs = (Regs) regsIter.next(); studentNames[count++] = myregs.getStudentName(); } for (int i = 0; i < score.length; i++) { scoresint = Integer.parseInt(score[i]); totalscore = totalscore + scoresint; if (scoresint < 60) { nopass++; score[i] = score[i] + "*"; } } messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Message.CreateSuccessful")); saveMessages(request, messages); aForm.initialize(mapping); Map pmap = new HashMap(); pmap.put("scoretype", scoretype); pmap.put("opmode", "Print"); pmap.put("schoolYear", Toolket.getSysParameter("School_year")); pmap.put("schoolTerm", Toolket.getSysParameter("School_term")); pmap.put("departClass", departClass); pmap.put("depClassName", initMap.get("depClassName").toString()); pmap.put("teacherName", initMap.get("teacherName").toString()); pmap.put("cscode", cscode); pmap.put("cscodeName", initMap.get("cscodeName").toString()); pmap.put("studentNo", studentNos); pmap.put("studentName", studentNames); pmap.put("score", score); pmap.put("totalstu", totalstu); pmap.put("totalscore", totalscore); pmap.put("avgscore", Math.round(totalscore / totalstu)); pmap.put("nopass", nopass); pmap.put("pass", (totalstu - nopass)); pmap.put("now", nows); session.setAttribute("TchScoreUploadPrint", pmap); // session.removeAttribute("TchScoreMidInfo"); session.removeAttribute("TchScoreInEdit"); session.removeAttribute("TchScoreUploadFormMap"); setContentPage(session, "teacher/TeachClassChoose.jsp"); return mapping.findForward("Main"); } catch (Exception e) { e.printStackTrace(); errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Exception.generic", e.getMessage())); saveErrors(request, errors); session.setAttribute("TchScoreUploadFormMap", aForm.getMap()); return mapping.findForward("Main"); } } }
public ActionMessages[] validMrgRecord( LazyValidatorForm frm, HttpServletRequest request, String action, boolean isOfficeManager) throws Exception { ActionMessages msgs[] = new ActionMessages[2]; ActionMessages msgsErrors = new ActionMessages(); ActionMessages msgsWarnings = new ActionMessages(); MarriageInfo mrgInf = null; InactiveMarriageInfo inactiveMrgInf = null; mrgInf = new MarriageInfo(); inactiveMrgInf = new InactiveMarriageInfo(); LoginInfo loginInfo = getLoginInfo(request); try { if (action.equalsIgnoreCase(Constants.ActionType.ADD) || action.equalsIgnoreCase(Constants.ActionType.MODIFY)) { reapetAjaxSideServer(frm, request); String regstLable = ""; String regstAuLabel = ""; String regstRegstGeoLabel = ""; boolean isConsul = false; mrgInf.setForeignStatusCode(Short.toString(Constants.ForeignStatusCode.FOREIGN)); String marConfirm = frm.get(MARRIAGE_CONFIRM_AUT_CODE).toString().trim(); if (!Utils.isEmpty(marConfirm)) { mrgInf.setMarriageConfirmAutCode(marConfirm); switch (Short.parseShort(frm.get(MARRIAGE_CONFIRM_AUT_CODE).toString())) { case Constants.MarriageConfirmAut.DECLARATION: frm.set( MARRIAGE_REGST_REF, String.valueOf(Constants.MarriageRegstRef.MARRIAGE_OFFICE)); regstLable = " ثبت ازدواج"; regstAuLabel = "شماره دفترخانه ازدواج "; regstRegstGeoLabel = "محل دفترخانه ازدواج "; break; case Constants.MarriageConfirmAut.PROFESSION: frm.set( MARRIAGE_REGST_REF, String.valueOf(Constants.MarriageRegstRef.FORMAL_DOCUMENT_OFFICE)); regstLable = " اقرارنامه"; regstAuLabel = "شماره دفترخانه اسناد رسمي "; regstRegstGeoLabel = "محل دفترخانه اسناد رسمي "; break; case Constants.MarriageConfirmAut.PETITION: frm.set(MARRIAGE_REGST_REF, String.valueOf(Constants.MarriageRegstRef.COURT)); regstLable = " دادنامه"; regstAuLabel = "شماره شعبه "; regstRegstGeoLabel = "محل شعبه "; break; case Constants.MarriageConfirmAut.CONSULE: frm.set( MARRIAGE_REGST_REF, String.valueOf(Constants.MarriageRegstRef.MARRIAGE_OFFICE)); isConsul = true; regstLable = " ثبت ازدواج"; regstAuLabel = "حوزه کنسولي تابعه "; regstRegstGeoLabel = "نام کشور "; break; } } boolean isDouplicateMarriageRecord = false; boolean isDouplicateMarriageHsb = false; boolean isDouplicateMarriageWf = false; if (action.equalsIgnoreCase(Constants.ActionType.ADD) && !Utils.isEmpty(frm.get(HSB_NO).toString().trim()) && Utils.isValidFoPersonalityNo(frm.get(HSB_NO).toString().trim()) && !Utils.isEmpty(frm.get(WF_NIN).toString().trim()) && Utils.isValidNin(frm.get(WF_NIN).toString().trim()) && !Utils.isEmpty(frm.get(MARRIAGE_DATE).toString().trim()) && ((!isOfficeManager && DateUtils.isValidRevFormattedFDate(((String) frm.get(MARRIAGE_DATE)).trim())) || (isOfficeManager && DateUtils.isValidNaghesOrCompDate( ((String) frm.get(MARRIAGE_DATE)).trim())))) { String hsbNo = frm.get(HSB_NO).toString().trim(); long wfNin = Long.parseLong(frm.get(WF_NIN).toString().trim()); String marriageDate = DateUtils.getCompleteDate(((String) frm.get(MARRIAGE_DATE)).trim()); isDouplicateMarriageRecord = Person.isDouplicateMarriage(hsbNo, wfNin, marriageDate); isDouplicateMarriageWf = Person.isDouplicateMarriageWife(wfNin, marriageDate); if (isDouplicateMarriageRecord) { addError(msgsErrors, "errIsDouplicateMarriage_3F"); setFocusControl(frm, HSB_NO); } else { if (isDouplicateMarriageWf) { addError(msgsWarnings, "errIsDouplicateMarriageWf_3F"); setFocusControl(frm, HSB_NO); } } } if (msgsErrors.isEmpty()) { String mrgType = frm.get(MARRIAGE_TYPE).toString().trim(); if (Utils.isEmpty(mrgType)) { addError(msgsErrors, FIELD_CAN_NOT_BE_EMPTY, "نوع ازدواج"); setFocusControl(frm, MARRIAGE_TYPE); } else if (mrgType.length() > 1) { addError(msgsErrors, FIELD_INVALID, "نوع ازدواج"); setFocusControl(frm, MARRIAGE_TYPE); } else { mrgInf.setMarriageTypeCode(mrgType); } String marRegstRef = frm.get(MARRIAGE_REGST_REF).toString().trim(); if (Utils.isEmpty(marRegstRef)) { addError(msgsErrors, FIELD_CAN_NOT_BE_EMPTY, "مرجع ثبت"); setFocusControl(frm, MARRIAGE_REGST_REF); } else if (marRegstRef.length() > 2) { addError(msgsErrors, FIELD_INVALID, "مرجع ثبت"); setFocusControl(frm, MARRIAGE_REGST_REF); } else { mrgInf.setMarriageRegstRefCode(marRegstRef); } String marriageDate = ""; String husbandNo = ""; long wifeNin = 0; String hsbDeathDate = ""; String wfDeathDate = ""; String lastBeforHsbDateOfDeath = ""; String lastAfterDateOfMarriage = ""; if (!Utils.isEmpty(frm.get(HSB_NO).toString().trim())) { husbandNo = frm.get(HSB_NO).toString().trim(); } if (!Utils.isEmpty(frm.get(WF_NIN).toString().trim()) && Utils.isValidNin(frm.get(WF_NIN).toString().trim())) { wifeNin = Long.parseLong(frm.get(WF_NIN).toString().trim()); String wifeDateOfDeath = getDateOfDeath(wifeNin); if (!Utils.isEmpty(wifeDateOfDeath)) wfDeathDate = DateUtils.unformatSpaceToZeroDate(wifeDateOfDeath); IranianInfo wfInfo = (IranianInfo) Person.getIranianDetails(wifeNin); if (wfInfo != null) { if (!Utils.isEmpty(frm.get(MARRIAGE_DATE).toString().trim()) && ((!isOfficeManager && DateUtils.isValidRevFormattedFDate( ((String) frm.get(MARRIAGE_DATE)).trim())) || (isOfficeManager && DateUtils.isValidNaghesOrCompDate( ((String) frm.get(MARRIAGE_DATE)).trim())))) { MarriageInfo lastBeforMarriage = Person.getLastBeforMarriageDetails( wifeNin, DateUtils.getCompleteDate(((String) frm.get(MARRIAGE_DATE)).trim())); MarriageInfo lastAfterMarriage = Person.getLastAfterMarriageDetails( wifeNin, DateUtils.getCompleteDate(((String) frm.get(MARRIAGE_DATE)).trim())); long hsbBeforNin = 0; if (lastBeforMarriage != null) { hsbBeforNin = lastBeforMarriage.getHusbandNin(); lastBeforHsbDateOfDeath = getDateOfDeath(hsbBeforNin); } if (lastAfterMarriage != null) { lastAfterDateOfMarriage = lastAfterMarriage.getMarriageDate(); } } } } boolean marriageDateIsTrue = true; if (Utils.isEmpty(frm.get(MARRIAGE_DATE).toString().trim())) { addError(msgsErrors, FIELD_CAN_NOT_BE_EMPTY, "تاريخ ازدواج"); setFocusControl(frm, MARRIAGE_DATE); marriageDateIsTrue = false; } else if ((!isOfficeManager && !DateUtils.isValidRevFormattedFDate(((String) frm.get(MARRIAGE_DATE)).trim())) || isOfficeManager && !DateUtils.isValidNaghesOrCompDate(((String) frm.get(MARRIAGE_DATE)).trim())) { addError(msgsErrors, FIELD_INVALID, "تاريخ ازدواج"); setFocusControl(frm, MARRIAGE_DATE); marriageDateIsTrue = false; } else if (DateUtils.getCompleteDate(((String) frm.get(MARRIAGE_DATE)).trim()) .compareTo(DateUtils.fDate()) > 0) { addError(msgsErrors, SHOULD_BE_LESS_EQUAL, "تاريخ ازدواج", "تاريخ روز "); setFocusControl(frm, MARRIAGE_DATE); marriageDateIsTrue = false; } else if (!Utils.isEmpty(frm.get(MARRIAGE_DATE).toString().trim()) && ((!isOfficeManager && DateUtils.isValidRevFormattedFDate( ((String) frm.get(MARRIAGE_DATE)).trim())) || isOfficeManager && DateUtils.isValidNaghesOrCompDate( ((String) frm.get(MARRIAGE_DATE)).trim())) && DateUtils.getCompleteDate(((String) frm.get(MARRIAGE_DATE)).trim()) .compareTo(DateUtils.fDate()) <= 0) { marriageDate = DateUtils.getCompleteDate(((String) frm.get(MARRIAGE_DATE)).trim()); if (action.equalsIgnoreCase(Constants.ActionType.ADD) && !Utils.isEmpty(wfDeathDate) && !wfDeathDate.equalsIgnoreCase("نامعلوم") && Integer.parseInt(wfDeathDate) < Integer.parseInt(marriageDate)) { addError(msgsErrors, "errMrgDateIsGreaterWfDeathDate_3F"); setFocusControl(frm, MARRIAGE_DATE); marriageDateIsTrue = false; } } if (marriageDateIsTrue) { mrgInf.setMarriageDate(DateUtils.unformatZeroToSpaceDate(marriageDate)); if ((!Utils.isEmpty(lastBeforHsbDateOfDeath) && marriageDate.compareTo(lastBeforHsbDateOfDeath) >= 0 && (marriageDate.compareTo( Utils_3F.threeOrFourAndTenAfter(lastBeforHsbDateOfDeath, 4)) < 0)) || (!Utils.isEmpty(hsbDeathDate) && !Utils.isEmpty(lastAfterDateOfMarriage) && lastAfterDateOfMarriage.compareTo(hsbDeathDate) >= 0 && (lastAfterDateOfMarriage.compareTo( Utils_3F.threeOrFourAndTenAfter(hsbDeathDate, 4)) < 0))) { addError(msgsWarnings, "errHusbandDead130Day_3F"); setFocusControl(frm, MARRIAGE_DATE); } DivorceInfo lastBeforDivorce = Person.getLastBeforDivorcesDetails(wifeNin, marriageDate); String lastBeforDivorceDate = ""; if (lastBeforDivorce != null) lastBeforDivorceDate = DateUtils.unformatSpaceToZeroDate(lastBeforDivorce.getDivorceDate()); if (lastBeforDivorce != null && !lastBeforDivorce .getDivorceTypeCode() .equalsIgnoreCase(Constants.DivorceType.BAEN_GHEIR_MADKHULEH) && !lastBeforDivorce .getDivorceTypeCode() .equalsIgnoreCase(Constants.DivorceType.BAEN_SAER) && !Utils.isEmpty(lastBeforDivorceDate) && marriageDate.compareTo(lastBeforDivorceDate) >= 0 && (lastBeforDivorceDate.compareTo( Utils_3F.xMonthBefore(DateUtils.unformatSpaceToZeroDate(marriageDate), 3)) > 0)) { addError(msgsWarnings, "errLastDivorce90Day_3F"); setFocusControl(frm, MARRIAGE_DATE); } } Vector allMarriage = Person.getAllMarriage(husbandNo, wifeNin); Vector allCorrespondingDivorce = new Vector(); DivorceInfo correspondingDivorce = new DivorceInfo(); for (int i = 0; i < allMarriage.size(); i++) { String correspondingMrgDate = ((MarriageInfo) allMarriage.elementAt(i)).getMarriageDate(); correspondingDivorce = Person.getCorrespondingDivorce(husbandNo, wifeNin, correspondingMrgDate); if (correspondingDivorce != null) allCorrespondingDivorce.add(correspondingDivorce); } if (allMarriage.size() >= 3 && allCorrespondingDivorce.size() >= 3) { addError(msgsWarnings, "err3HusbandWifeMarriage_3F"); setFocusControl(frm, HSB_NO); } int countAllDivorce = Person.getCountAllDivorce(husbandNo, wifeNin); if (countAllDivorce >= 9) { addError(msgsWarnings, "err9HusbandWifeDivorce_3F"); setFocusControl(frm, HSB_NO); } if (mrgInf.getMarriageTypeCode().equalsIgnoreCase(Constants.MarriageType.BROKEN)) { String expDate = ""; if (!Utils.isEmpty(frm.get(EXPIRY_DATE).toString().trim())) { if (((!isOfficeManager && !DateUtils.isValidRevFormattedFDate( ((String) frm.get(EXPIRY_DATE)).trim())) || isOfficeManager && !DateUtils.isValidNaghesOrCompDate( ((String) frm.get(EXPIRY_DATE)).trim()))) { addError(msgsErrors, FIELD_INVALID, "تاريخ انقضاء"); setFocusControl(frm, EXPIRY_DATE); } else if (!Utils.isEmpty(frm.get(EXPIRY_DATE).toString().trim()) && !Utils.isEmpty(marriageDate) && marriageDate.compareTo( DateUtils.getCompleteDate(((String) frm.get(EXPIRY_DATE)).trim())) > 0) { addError(msgsErrors, SHOULD_BE_GREATER_EQUAL, "تاريخ انقضاء", "تاريخ ازدواج"); setFocusControl(frm, EXPIRY_DATE); } else { expDate = DateUtils.getCompleteDate(((String) frm.get(EXPIRY_DATE)).trim()); mrgInf.setExpiryDate(DateUtils.unformatZeroToSpaceDate(expDate)); } } } else if (mrgInf.getMarriageTypeCode().equalsIgnoreCase(Constants.MarriageType.BROKEN)) { mrgInf.setExpiryDate(""); } String regstDate = frm.get(REGST_DATE).toString().trim(); if (Utils.isEmpty(regstDate)) { addError(msgsErrors, FIELD_CAN_NOT_BE_EMPTY, "تاريخ " + regstLable); setFocusControl(frm, REGST_DATE); } else if ((!isOfficeManager && !DateUtils.isValidRevFormattedFDate(((String) frm.get(REGST_DATE)).trim())) || isOfficeManager && !DateUtils.isValidNaghesOrCompDate(((String) frm.get(REGST_DATE)).trim())) { addError(msgsErrors, FIELD_INVALID, "تاريخ " + regstLable); setFocusControl(frm, REGST_DATE); } else if (DateUtils.getCompleteDate(regstDate).compareTo(DateUtils.fDate()) > 0) { addError(msgsErrors, SHOULD_BE_LESS_EQUAL, "تاريخ " + regstLable, "تاريخ روز "); setFocusControl(frm, REGST_DATE); } else { boolean regstDateIsTrue = true; regstDate = DateUtils.getCompleteDate(((String) frm.get(REGST_DATE)).trim()); if (!Utils.isEmpty(frm.get(HSB_DATE_OF_BIRTH_SUN).toString().trim()) && (DateUtils.getCompleteDate(((String) frm.get(HSB_DATE_OF_BIRTH_SUN)).trim())) .compareTo(regstDate) >= 0) { addError(msgsErrors, SHOULD_BE_GREATER, "تاريخ " + regstLable, "تاريخ تولد زوج"); setFocusControl(frm, REGST_DATE); regstDateIsTrue = false; } if (!Utils.isEmpty(frm.get(WF_DATE_OF_BIRTH_SUN).toString().trim()) && (DateUtils.getCompleteDate(((String) frm.get(WF_DATE_OF_BIRTH_SUN)).trim())) .compareTo(regstDate) >= 0) { addError(msgsErrors, SHOULD_BE_GREATER, "تاريخ " + regstLable, "تاريخ تولد زوجه"); setFocusControl(frm, REGST_DATE); regstDateIsTrue = false; } if (!Utils.isEmpty(marriageDate) && marriageDate.compareTo(regstDate) > 0) { addError(msgsErrors, SHOULD_BE_GREATER_EQUAL, "تاريخ " + regstLable, "تاريخ ازدواج"); setFocusControl(frm, REGST_DATE); regstDateIsTrue = false; } if (regstDateIsTrue) { mrgInf.setRegstDate( DateUtils.unformatZeroToSpaceDate( DateUtils.getCompleteDate(frm.get(REGST_DATE).toString().trim()))); } } String regstNo = Utils.charVal2((String) frm.get(REGST_NO)); if (Utils.isEmpty(regstNo)) { addError(msgsErrors, FIELD_CAN_NOT_BE_EMPTY, "شماره " + regstLable); setFocusControl(frm, REGST_NO); } else if (regstNo.length() > 20 || regstNo.matches("[0]*")) { addError(msgsErrors, FIELD_INVALID, "شماره " + regstLable); setFocusControl(frm, REGST_NO); } else { mrgInf.setRegstNo(regstNo); } String regstAu = ""; if (!isConsul) regstAu = Utils.charVal2((String) frm.get(REGST_AU)); else if (isConsul) regstAu = Utils.charVal2((String) frm.get(CONSUL_NO)); if (Utils.isEmpty(regstAu)) { addError(msgsErrors, FIELD_CAN_NOT_BE_EMPTY, regstAuLabel); setFocusControl(frm, REGST_AU); } else if ((!isConsul && !Utils.isValidNumber(regstAu, 10) || regstAu.matches("[0]*")) || (isConsul && regstAu.length() > 10)) { addError(msgsErrors, FIELD_INVALID, regstAuLabel); setFocusControl(frm, REGST_AU); } else { mrgInf.setRegstAu(regstAu); } String regstGeo = ""; if (!isConsul) regstGeo = ((String) frm.get(REGST_GEO)); else if (isConsul) regstGeo = ((String) frm.get(CONSUL_GEO)); if (Utils.isEmpty(regstGeo)) { addError(msgsErrors, FIELD_CAN_NOT_BE_EMPTY, regstRegstGeoLabel); setFocusControl(frm, REGST_GEO); } else if (!isConsul && searchOfficeGeoSerial(frm) == false) { addError(msgsErrors, FIELD_INVALID, regstRegstGeoLabel); setFocusControl(frm, REGST_GEO); } else { mrgInf.setRegstGeoSerial(regstGeo); } if (action.equalsIgnoreCase(Constants.ActionType.ADD)) { mrgInf.setMamoorId((new Security()).getMamoorIdByUserId(loginInfo.getUserId())); mrgInf.setUserId(loginInfo.getUserId()); mrgInf.setOfficeCode(loginInfo.getOfficeCode()); } mrgInf.setCodeActiveFlag(Constants.CodeActiveFlag.ACTIVE); } } else if (action.equalsIgnoreCase(Constants.ActionType.DELETE)) { String marriageDate = DateUtils.unformatZeroToSpaceDate( DateUtils.getCompleteDate(frm.get(MARRIAGE_DATE).toString().trim())); mrgInf = Person.getMarriageDetails( frm.get(HSB_NO).toString().trim(), Long.parseLong(frm.get(WF_NIN).toString().trim()), marriageDate); mrgInf.setInactiveMarriageReasonCode(Constants.InactiveMrgReasonCode.DELETE); String opinionNo = Utils.charVal2(frm.get(OPINION_NO).toString().trim()); frm.set(OPINION_NO, opinionNo); if (Utils.isEmpty(opinionNo)) { addError(msgsErrors, FIELD_CAN_NOT_BE_EMPTY, "شماره رأي هيأت "); setFocusControl(frm, OPINION_NO); } else if (opinionNo.length() > 20) { addError(msgsErrors, FIELD_INVALID, "شماره رأي هيأت "); setFocusControl(frm, OPINION_NO); } else { inactiveMrgInf.setOpinionNo(opinionNo); } String opinionDate = ""; if (Utils.isEmpty(frm.get(OPINION_DATE).toString().trim())) { addError(msgsErrors, FIELD_CAN_NOT_BE_EMPTY, "تاريخ رأي هيأت "); setFocusControl(frm, OPINION_DATE); } else if ((!isOfficeManager && !DateUtils.isValidRevFormattedFDate(((String) frm.get(OPINION_DATE)).trim())) || isOfficeManager && !DateUtils.isValidNaghesOrCompDate(((String) frm.get(OPINION_DATE)).trim())) { addError(msgsErrors, FIELD_INVALID, "تاريخ رأي هيأت "); setFocusControl(frm, OPINION_DATE); } else if (DateUtils.getCompleteDate(((String) frm.get(OPINION_DATE)).trim()) .compareTo(DateUtils.fDate()) > 0) { addError(msgsErrors, SHOULD_BE_LESS_EQUAL, "تاريخ رأي هيأت ", "تاريخ روز "); setFocusControl(frm, OPINION_DATE); } else if (DateUtils.getCompleteDate(((String) frm.get(OPINION_DATE)).trim()) .compareTo(DateUtils.getCompleteDate(((String) frm.get(MARRIAGE_DATE)).trim())) < 0) { addError(msgsErrors, SHOULD_BE_GREATER_EQUAL, "تاريخ رأي هيأت ", "تاريخ ازدواج"); setFocusControl(frm, OPINION_DATE); } else { opinionDate = DateUtils.getCompleteDate(((String) frm.get(OPINION_DATE)).trim()); inactiveMrgInf.setOpinionDate(DateUtils.unformatZeroToSpaceDate(opinionDate)); } mrgInf.setInactiveMarriageReasonCode(Constants.InactiveMrgReasonCode.DELETE); mrgInf.setCodeActiveFlag(Constants.CodeActiveFlag.INACTIVE); inactiveMrgInf.setMamoorId((new Security()).getMamoorIdByUserId(loginInfo.getUserId())); inactiveMrgInf.setUserId(loginInfo.getUserId()); inactiveMrgInf.setOfficeCode(loginInfo.getOfficeCode()); } request.getSession().setAttribute("marriageInf", mrgInf); request.getSession().setAttribute("inactiveMarriageInf", inactiveMrgInf); msgs[0] = msgsErrors; msgs[1] = msgsWarnings; } catch (Exception ex) { Utils.log4j(ex); } return msgs; }
public ActionForward execute( ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { LazyValidatorForm frm = (LazyValidatorForm) actionForm; resetFocusControl(frm, CANCEL); ActionMessages msgs = new ActionMessages(); if (formCanceled(frm)) { return actionMapping.findForward(SUCCESS); } String geoFlag = (String) frm.get(GEO_FLAG); if (Utils.isEmpty(geoFlag)) { geoFlag = (String) httpServletRequest.getParameter(GEO_FLAG); frm.set(GEO_FLAG, geoFlag); } if (!formSaved(frm)) { setFormMode(frm, ((String) httpServletRequest.getParameter(BROWSE_ACTION))); setFormId(frm, (String) httpServletRequest.getParameter(BROWSE_ID)); try { LoginInfo loginInfo = getLoginInfo(httpServletRequest); String geoFlagDesc = Misc.getHardCodeDesc(Constants.TableId.GEO_FLAG, geoFlag); frm.set(GEO_FLAG_DESC, geoFlagDesc); if (!loginInfo.userHasAccess("Geo_Conversion", getFormMode(frm))) { if (isFormInModifyMode(frm) && loginInfo.userHasAccess("Geo_Conversion", Constants.ActionType.ENQUERY)) { setFormMode(frm, Constants.ActionType.ENQUERY); } else { throw new Exception(INVALID_ACCESS); } } if (!geoFlag.equals(Constants.GeoFlag.VILLAGE)) { throw new Exception(INVALID_ACCESS); } if (!isFormInAddMode(frm)) { String formKey = (String) httpServletRequest.getParameter(BROWSE_KEY); GeoFormationInfo inf = Geo.getGeoFormationDetails(Integer.parseInt(formKey)); frm.set(GEO_FORMATION_SERIAL, Integer.toString(inf.getGeoFormationSerial())); frm.set(GEO_SERIAL, Integer.toString(inf.getGeoSerial())); frm.set(APPROVAL_LETTER_NO, inf.getApprovalLetterNo()); frm.set(APPROVAL_LETTER_DATE, DateUtils.revFormatDate(inf.getApprovalLetterDate())); frm.set(GEO_DESC, Geo.getGeoDesc(inf.getGeoSerial())); } frm.set(GEO_FLAG_DESC, geoFlagDesc); if (isFormInModifyMode(frm)) { resetFocusControl(frm, APPROVAL_LETTER_NO); } } catch (Exception ex) { addError(msgs, ex.getMessage()); saveErrors(httpServletRequest, msgs); } return actionMapping.findForward(EDIT); } else { try { String geoFlagDesc = (String) frm.get(GEO_FLAG_DESC); if (!geoFlag.equals(Constants.GeoFlag.VILLAGE)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "علامت محل جغرافيايي"); setFocusControl(frm, GEO_SERIAL); } GeoFormationInfo inf = new GeoFormationInfo(); resetFocusControl(frm, ""); if (isFormInDeleteMode(frm) || isFormInModifyMode(frm)) { String geoFormationSerial = ((String) frm.get(GEO_FORMATION_SERIAL)).trim(); if (Utils.isEmpty(geoFormationSerial)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "سريال"); setFocusControl(frm, GEO_SERIAL); } else if (!Utils.isValidNotZeroNumber(geoFormationSerial, 6)) { addError(msgs, FIELD_INVALID, "سريال"); setFocusControl(frm, GEO_SERIAL); } else { inf.setGeoFormationSerial(Integer.parseInt(geoFormationSerial)); } } if (isFormInAddMode(frm)) { String geoSerial = ((String) frm.get(GEO_SERIAL)).trim(); if (Utils.isEmpty(geoSerial)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "سريال " + geoFlagDesc); setFocusControl(frm, GEO_SERIAL); } /* else if (searchGeoDesc(frm, geoFlag) == false) { addError(msgs, FIELD_INVALID, "سريال " + geoFlagDesc); setFocusControl(frm, GEO_SERIAL); } */ else { inf.setGeoSerial(Integer.parseInt(geoSerial)); } } if (!isFormInDeleteMode(frm)) { String approvalLetterNo = Utils.trimConvert((String) frm.get(APPROVAL_LETTER_NO)); frm.set(APPROVAL_LETTER_NO, approvalLetterNo); if (Utils.isEmpty(approvalLetterNo)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "شماره تصويب نامه"); setFocusControl(frm, APPROVAL_LETTER_NO); } else if (approvalLetterNo.length() > 20) { addError(msgs, FIELD_INVALID, "شماره تصويب نامه"); setFocusControl(frm, APPROVAL_LETTER_NO); } else { inf.setApprovalLetterNo(approvalLetterNo); } String approvalLetterDate = ((String) frm.get(APPROVAL_LETTER_DATE)).trim(); if (Utils.isEmpty(approvalLetterDate)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "تاريخ تصويب نامه"); setFocusControl(frm, APPROVAL_LETTER_DATE); } else if (!DateUtils.isValidRevFormattedFDate(approvalLetterDate)) { addError(msgs, FIELD_INVALID, "تاريخ تصويب نامه"); setFocusControl(frm, APPROVAL_LETTER_DATE); } else if (DateUtils.unformatRevFormattedFdate(approvalLetterDate) .compareTo(DateUtils.fDate()) > 0) { addError(msgs, FIELD_SHOULD_BE_LESS_THAN, "تاريخ تصويب نامه", "تاريخ روز"); setFocusControl(frm, APPROVAL_LETTER_DATE); } else { inf.setApprovalLetterDate(DateUtils.unformatRevFormattedFdate(approvalLetterDate)); } } if (!msgs.isEmpty()) { saveErrors(httpServletRequest, msgs); return actionMapping.findForward(EDIT); } resetFocusControl(frm, CANCEL); Geo.saveConversion(getFormMode(frm), inf, geoFlag); httpServletRequest.setAttribute(BROWSE_KEY, inf.getKey()); return actionMapping.findForward(SUCCESS); } catch (Exception ex) { resetFocusControl(frm, CANCEL); addError(msgs, ex.getMessage()); saveErrors(httpServletRequest, msgs); return actionMapping.findForward(EDIT); } } }
/** * Render the specified error messages if there are any. * * @throws JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { // Were any error messages specified? ActionMessages errors = null; try { errors = TagUtils.getInstance().getActionMessages(pageContext, name); } catch (JspException e) { TagUtils.getInstance().saveException(pageContext, e); throw e; } if ((errors == null) || errors.isEmpty()) { return (EVAL_BODY_INCLUDE); } boolean headerPresent = TagUtils.getInstance().present(pageContext, bundle, locale, getHeader()); boolean footerPresent = TagUtils.getInstance().present(pageContext, bundle, locale, getFooter()); boolean prefixPresent = TagUtils.getInstance().present(pageContext, bundle, locale, getPrefix()); boolean suffixPresent = TagUtils.getInstance().present(pageContext, bundle, locale, getSuffix()); // Render the error messages appropriately StringBuffer results = new StringBuffer(); boolean headerDone = false; String message = null; Iterator reports = (property == null) ? errors.get() : errors.get(property); while (reports.hasNext()) { ActionMessage report = (ActionMessage) reports.next(); if (!headerDone) { if (headerPresent) { message = TagUtils.getInstance().message(pageContext, bundle, locale, getHeader()); results.append(message); } headerDone = true; } if (prefixPresent) { message = TagUtils.getInstance().message(pageContext, bundle, locale, getPrefix()); results.append(message); } if (report.isResource()) { message = TagUtils.getInstance() .message(pageContext, bundle, locale, report.getKey(), report.getValues()); } else { message = report.getKey(); } if (message != null) { results.append(message); } if (suffixPresent) { message = TagUtils.getInstance().message(pageContext, bundle, locale, getSuffix()); results.append(message); } } if (headerDone && footerPresent) { message = TagUtils.getInstance().message(pageContext, bundle, locale, getFooter()); results.append(message); } TagUtils.getInstance().write(pageContext, results.toString()); return (EVAL_BODY_INCLUDE); }
public ActionForward execute( ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { LazyValidatorForm frm = (LazyValidatorForm) actionForm; if (formCanceled(frm)) { return actionMapping.findForward(SUCCESS); } resetFocusControl(frm, CANCEL); ActionMessages msgs = new ActionMessages(); if (!formSaved(frm)) { setFormMode(frm, ((String) httpServletRequest.getParameter(BROWSE_ACTION))); setFormId(frm, (String) httpServletRequest.getParameter(BROWSE_ID)); try { httpServletRequest .getSession() .setAttribute("hozehKindList", Misc.listHardCode(Constants.TableId.HOZEH_KIND)); LoginInfo loginInfo = getLoginInfo(httpServletRequest); if (!loginInfo.userHasAccess(getFormId(frm), getFormMode(frm))) { if (isFormInModifyMode(frm) && loginInfo.userHasAccess(getFormId(frm), Constants.ActionType.ENQUERY)) { setFormMode(frm, Constants.ActionType.ENQUERY); } else { throw new Exception(INVALID_ACCESS); } } if (!isFormInAddMode(frm)) { String formKey = (String) httpServletRequest.getParameter(BROWSE_KEY); frm.set("formKey", formKey); String key[] = formKey.split(Constants.DATA_SEPARATOR_SPLIT); short officeCode = Short.parseShort(key[0]); short hozehCode = Short.parseShort(key[1]); String hozehKind = key[2]; HozehInfo inf = Place.getHozehDetails(officeCode, hozehCode, hozehKind); frm.set(OFFICE_CODE, Short.toString(inf.getOfficeCode())); frm.set(HOZEH_CODE, Short.toString(inf.getHozehCode())); frm.set(HOZEH_KIND, inf.getHozehKind()); frm.set(HOZEH_DESC, inf.getHozehDesc()); if (inf.isInactive()) { frm.set(CODE_ACTIVE_FLAG, "on"); } } String officeCode = (String) frm.get(OFFICE_CODE); if (Utils.isEmpty(officeCode)) { officeCode = "0"; frm.set(OFFICE_CODE, officeCode); } frm.set(OFFICE_NAME, Place.getOfficeName(Short.parseShort(officeCode))); if (isFormInAddMode(frm)) { resetFocusControl(frm, HOZEH_CODE); } else if (isFormInModifyMode(frm)) { resetFocusControl(frm, HOZEH_DESC); } } catch (Exception ex) { addError(msgs, ex.getMessage()); saveErrors(httpServletRequest, msgs); } return actionMapping.findForward(EDIT); } else { HozehInfo inf = new HozehInfo(); resetFocusControl(frm, ""); if (isFormInAddMode(frm)) { String officeCode = ((String) frm.get(OFFICE_CODE)).trim(); resetFocusControl(frm, ""); if (Utils.isEmpty(officeCode)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "اداره"); setFocusControl(frm, OFFICE_CODE); } else if (!Utils.isValidNotZeroNumber(officeCode, 3)) { addError(msgs, FIELD_INVALID, "اداره"); setFocusControl(frm, OFFICE_CODE); } else { inf.setOfficeCode(Short.parseShort(officeCode)); } String hozehCode = ((String) frm.get(HOZEH_CODE)).trim(); if (Utils.isEmpty(hozehCode)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "كد"); setFocusControl(frm, HOZEH_CODE); } else if (!Utils.isValidNotZeroNumber(hozehCode, 3)) { addError(msgs, FIELD_INVALID, "كد"); setFocusControl(frm, HOZEH_CODE); } else { inf.setHozehCode(Short.parseShort(hozehCode)); } String hozehKind = ((String) frm.get(HOZEH_KIND)).trim(); if (Utils.isEmpty(hozehKind)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "نوع"); setFocusControl(frm, HOZEH_KIND); } else if (hozehKind.length() > 1) { addError(msgs, FIELD_INVALID, "نوع"); setFocusControl(frm, HOZEH_KIND); } else { inf.setHozehKind(hozehKind); } } else { String formKey = (String) frm.get("formKey"); String key[] = formKey.split(Constants.DATA_SEPARATOR_SPLIT); inf.setOfficeCode(Short.parseShort(key[0])); inf.setHozehCode(Short.parseShort(key[1])); inf.setHozehKind(key[2]); } if (!isFormInDeleteMode(frm)) { String hozehDesc = Utils.charVal((String) frm.get(HOZEH_DESC)); frm.set(HOZEH_DESC, hozehDesc); if (Utils.isEmpty(hozehDesc)) { addError(msgs, FIELD_CAN_NOT_BE_EMPTY, "شرح"); setFocusControl(frm, HOZEH_DESC); } else if (hozehDesc.length() > 50) { addError(msgs, FIELD_INVALID, "شرح"); setFocusControl(frm, HOZEH_DESC); } else { inf.setHozehDesc(hozehDesc); } if (frm.get(CODE_ACTIVE_FLAG) == null) { inf.setCodeActiveFlag(Constants.CodeActiveFlag.ACTIVE); } else { inf.setCodeActiveFlag(Constants.CodeActiveFlag.INACTIVE); } } if (!msgs.isEmpty()) { saveErrors(httpServletRequest, msgs); return actionMapping.findForward(EDIT); } resetFocusControl(frm, CANCEL); try { Place.saveHozeh(getFormMode(frm), inf); httpServletRequest.setAttribute(BROWSE_KEY, inf.getKey()); return actionMapping.findForward(SUCCESS); } catch (Exception ex) { resetFocusControl(frm, CANCEL); addError(msgs, ex.getMessage()); saveErrors(httpServletRequest, msgs); return actionMapping.findForward(EDIT); } } }
/** * Método de execução da ação. Realiza dois forwards: um em caso de sucesso e outro em caso de * falha * * @param mapping * @param form ActionForm, caso necessário * @param request * @param response */ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages msgs = new ActionMessages(); Orgao orgao = this.getOrgao(request); Long funcionarioId = (Long) request.getSession().getAttribute(Constants.PA_FUNCIONARIO); FuncionarioCtrl funcionarioCtrl = new FuncionarioCtrl(getDaoFactory()); Funcionario funcionario = (Funcionario) funcionarioCtrl.get(funcionarioId); ListarAcionamentoRespostaCtrl controle = new ListarAcionamentoRespostaCtrl(getDaoFactory()); String numeroProtocolo = ((DynaActionForm) form).getString("numeroProtocolo"); String enviados = ((DynaActionForm) form).getString("enviado"); String naoEnviados = ((DynaActionForm) form).getString("naoEnviado"); String meioEnvioResposta = ((DynaActionForm) form).getString("meioEnvioResposta"); Collection acionamentos = null; if (numeroProtocolo != null && numeroProtocolo.trim().length() > 0) { try { Acionamento acnmnt = controle.getAcionamentoPeloProtocolo(orgao, funcionario, numeroProtocolo); if (acnmnt != null) { acionamentos = new ArrayList(); acionamentos.add(acnmnt); } } catch (Exception a) { msgs.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.listarAcionamentoResposta.protocolo.invalido")); } } else { String situacao = null; if ((enviados == null || enviados.trim().length() == 0) && naoEnviados != null) { situacao = EstadoAcionamento.RESPONDIDO.getId().toString(); } else if (enviados != null && (naoEnviados == null || naoEnviados.trim().length() == 0)) { situacao = EstadoAcionamento.ENVIADO.getId().toString(); } acionamentos = controle.listarAcionamentos(orgao, funcionario, meioEnvioResposta, situacao); } request.setAttribute("numeroProtocolo", numeroProtocolo); request.setAttribute("meioEnvioResposta", meioEnvioResposta); request.setAttribute("enviado", enviados); request.setAttribute("naoEnviado", naoEnviados); request.setAttribute("listarAcionamentos", acionamentos); if (msgs.isEmpty()) { return (mapping.findForward("success")); } saveErrors(request, msgs); return (mapping.findForward("error")); }