public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Initialize action initAction(request); if (null == config) { return (mapping.findForward("noconfig")); } // Was this transaction cancelled? if (isCancelled(request)) { removeFormBean(mapping, request); return (mapping.findForward("cancel")); } DynaActionForm alterTracingPropertiesForm = (DynaActionForm) form; String form_properties = (String) alterTracingPropertiesForm.get("properties"); try { TracingUtil.setProperties(form_properties); } catch (Throwable t) { error("could not set properties", t); } if (!errors.isEmpty()) { saveErrors(request, errors); return (new ActionForward(mapping.getInput())); } // Forward control to the specified success URI log.debug("forward to success"); return (mapping.findForward("success")); }
public ActionForward perform( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Logger log = Logger.getLogger(EditSecurityGroupAction.class.getName()); // Extract attributes we will need Locale locale = getLocale(request); MessageResources messages = getResources(); String action = request.getParameter("action"); String permissionId = request.getParameter("permissionId"); String description = request.getParameter("description"); if (action == null) action = "create"; if (action.equals("create")) { if ((permissionId == null) || (permissionId.length() < 1)) actionDebug.addGlobalError(errors, "error.permission.required"); if ((description == null) || (description.length() < 1)) actionDebug.addGlobalError(errors, "error.description.required"); SecurityServices ss = new SecurityServices(); try { ss.createSecurityPermission(permissionId, description); log.info("Create Security Permission Success !"); } catch (HibernateException e) { log.error("Error:" + e.getMessage()); actionDebug.addGlobalError(errors, "error.edit"); e.printStackTrace(); } if (!errors.empty()) { saveErrors(request, errors); return (new ActionForward(mapping.getInput())); } } if (action.equals("edit")) { if ((permissionId == null) || (permissionId.length() < 1)) actionDebug.addGlobalError(errors, "error.permission.required"); SecurityServices ss = new SecurityServices(); try { ss.updateSecurityPermission(permissionId, description); log.info("Update Security Permission Success !"); } catch (HibernateException e) { log.error("Error:" + e.getMessage()); actionDebug.addGlobalError(errors, "error.update"); e.printStackTrace(); } if (!errors.empty()) { saveErrors(request, errors); return (new ActionForward(mapping.getInput())); } } if (action.equals("delete")) { if ((permissionId == null) || (permissionId.length() < 1)) actionDebug.addGlobalError(errors, "error.permission.required"); SecurityServices ss = new SecurityServices(); try { ss.deleteSecurityPermission(permissionId); log.info("Delete Security Permission Success !"); } catch (HibernateException e) { log.error("Error:" + e.getMessage()); actionDebug.addGlobalError(errors, "error.delete"); e.printStackTrace(); } if (!errors.empty()) { saveErrors(request, errors); return (new ActionForward(mapping.getInput())); } } return (mapping.findForward("success")); }
public ActionForward perform( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // Extract attributes we will need ActionErrors errors = this.getActionErrors(request.getSession()); Logger log = Logger.getLogger(EditCustPartyAction.class.getName()); Locale locale = getLocale(request); MessageResources messages = getResources(); String action = request.getParameter("action"); String openType = request.getParameter("openType"); log.info("action=" + action); try { String PartyId = request.getParameter("PartyId"); String description = request.getParameter("description"); // String ParentpartyId = request.getParameter("ParentpartyId"); String address = request.getParameter("address"); String postcode = request.getParameter("postcode"); String telecode = request.getParameter("telecode"); String note = request.getParameter("note"); String role = request.getParameter("role"); String ChineseName = request.getParameter("ChineseName"); String AccountId = request.getParameter("AccountId"); String IndustryId = request.getParameter("IndustryId"); String t2code = request.getParameter("t2code"); String AccountCode = request.getParameter("AccountCode"); String CustPartyTypeId = "PARTY_GROUP"; if (address == null) address = ""; if (postcode == null) postcode = ""; if (telecode == null) telecode = ""; if (note == null) note = ""; if (role == null) role = ""; if (ChineseName == null) ChineseName = ""; if (AccountId == null) AccountId = "0"; if (IndustryId == null) IndustryId = "0"; if (t2code == null) t2code = ""; if (AccountCode == null) AccountCode = ""; net.sf.hibernate.Session hs = Hibernate2Session.currentSession(); Transaction tx = null; if (action == null) action = "view"; if (!isTokenValid(request)) { if (action.equals("create") || action.equals("update")) { action = "view"; } } saveToken(request); if (action.equals("view")) { log.info(action); CustomerProfile CustParty = null; if (!((PartyId == null) || (PartyId.length() < 1))) CustParty = (CustomerProfile) hs.load(CustomerProfile.class, PartyId); request.setAttribute("CustParty", CustParty); if ("dialogView".equals(openType)) { return (mapping.findForward("dialogView")); } else { return (mapping.findForward("view")); } } if (action.equals("create")) { if ((PartyId == null) || (PartyId.length() < 1)) { CustomerService cs = new CustomerService(); PartyId = cs.getCustomerNo(hs); } if ((description == null) || (description.length() < 1)) actionDebug.addGlobalError(errors, "error.context.required"); if (!errors.empty()) { saveErrors(request, errors); return (new ActionForward(mapping.getInput())); } try { tx = hs.beginTransaction(); CustomerProfile CustParty = new CustomerProfile(); CustParty.setPartyId(PartyId); CustParty.setDescription(description); CustParty.setAddress(address); CustParty.setPostCode(postcode); CustParty.setTeleCode(telecode); CustParty.setNote(note); CustParty.setType("C"); CustParty.setChineseName(ChineseName); CustParty.setAccountCode(AccountCode); Industry ind = (Industry) hs.load(Industry.class, new Long(IndustryId)); CustParty.setIndustry(ind); CustomerAccount acc = (CustomerAccount) hs.load(CustomerAccount.class, new Long(AccountId)); CustParty.setAccount(acc); CustT2Code T2C = (CustT2Code) hs.load(CustT2Code.class, t2code); CustParty.setT2Code(T2C); PartyType CustPartyType = (PartyType) hs.load(PartyType.class, CustPartyTypeId); CustParty.setPartyType(CustPartyType); Set mset = CustParty.getPartyRoles(); if (mset == null) { mset = new HashSet(); } mset.add((RoleType) hs.load(RoleType.class, role)); CustParty.setPartyRoles(mset); hs.save(CustParty); hs.flush(); tx.commit(); // edit prospect Company String prospectCompanyId = request.getParameter("prospectCompanyId"); if (prospectCompanyId != null && !prospectCompanyId.equals("") && !prospectCompanyId.equals("null")) { tx = hs.beginTransaction(); com.aof.component.prm.bid.ProspectCompany prospect = (com.aof.component.prm.bid.ProspectCompany) hs.load( com.aof.component.prm.bid.ProspectCompany.class, new Long(prospectCompanyId)); prospect.setName(description); prospect.setAddress(address); prospect.setPostCode(postcode); prospect.setTeleNo(telecode); prospect.setChineseName(ChineseName); prospect.setIndustry(IndustryId); prospect.setCustomerGroup(AccountId); prospect.setStatus("Existing"); hs.update(prospect); hs.flush(); tx.commit(); } request.setAttribute("CustParty", CustParty); log.info("go to >>>>>>>>>>>>>>>>. view forward"); } catch (Exception e) { e.printStackTrace(); } if ("dialogView".equals(openType)) { return (mapping.findForward("dialogView")); } else { return (mapping.findForward("view")); } } if (action.equals("update")) { if ((PartyId == null) || (PartyId.length() < 1)) actionDebug.addGlobalError(errors, "error.context.required"); if (!errors.empty()) { saveErrors(request, errors); return (new ActionForward(mapping.getInput())); } tx = hs.beginTransaction(); CustomerProfile CustParty = (CustomerProfile) hs.load(CustomerProfile.class, PartyId); CustParty.setDescription(description); CustParty.setAddress(address); CustParty.setPostCode(postcode); CustParty.setTeleCode(telecode); CustParty.setNote(note); CustParty.setChineseName(ChineseName); Industry ind = (Industry) hs.load(Industry.class, new Long(IndustryId)); CustParty.setIndustry(ind); CustomerAccount acc = (CustomerAccount) hs.load(CustomerAccount.class, new Long(AccountId)); CustParty.setAccount(acc); CustT2Code T2C = (CustT2Code) hs.load(CustT2Code.class, t2code); CustParty.setT2Code(T2C); CustParty.setAccountCode(AccountCode); hs.update(CustParty); tx.commit(); request.setAttribute("CustParty", CustParty); if ("dialogView".equals(openType)) { return (mapping.findForward("dialogView")); } else { return (mapping.findForward("view")); } } if (action.equals("delete")) { if ((PartyId == null) || (PartyId.length() < 1)) actionDebug.addGlobalError(errors, "error.context.required"); if (!errors.empty()) { saveErrors(request, errors); return (new ActionForward(mapping.getInput())); } tx = hs.beginTransaction(); CustomerProfile CustParty = (CustomerProfile) hs.load(CustomerProfile.class, PartyId); log.info("PartyId=" + CustParty.getPartyId()); hs.delete(CustParty); tx.commit(); return (mapping.findForward("after_delete")); } if (!errors.empty()) { saveErrors(request, errors); return (new ActionForward(mapping.getInput())); } if ("dialogView".equals(openType)) { return (mapping.findForward("dialogView")); } else { return (mapping.findForward("view")); } } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); // cannot delete due to the database constraints if (action.equals("delete")) { request.setAttribute("errorSign", "Cannot delete the record !"); } if ("dialogView".equals(openType)) { return (mapping.findForward("dialogView")); } else { return (mapping.findForward("view")); } } finally { try { Hibernate2Session.closeSession(); } catch (HibernateException e1) { log.error(e1.getMessage()); e1.printStackTrace(); } catch (SQLException e1) { log.error(e1.getMessage()); e1.printStackTrace(); } } }
/** * SystemException例外ハンドラのエントリポイント。 * * @param ex 例外 * @param eConfig 例外コンフィグ * @param mapping アクションマッピング * @param formInstance アクションフォーム * @param request HTTPリクエスト * @param response HTTPレスポンス * @return 遷移情報 * @throws ServletException サーブレット例外 * @see jp.terasoluna.fw.web.struts.action.DefaultExceptionHandler#execute( java.lang.Exception, * org.apache.struts.config.ExceptionConfig, org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse ) */ @Override public ActionForward execute( Exception ex, ExceptionConfig eConfig, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException { // 【フォワード先を設定する】 // pathによるフォワード先が指定されない場合は、 // アクションマッピングのinput属性をデフォルトとする。 String path = null; if (eConfig.getPath() != null) { path = eConfig.getPath(); } else { path = mapping.getInput(); } ActionForward forward = new ActionForward(path); String logLevel = null; // 【遷移先を設定する】 if (eConfig instanceof ExceptionConfigEx) { // 遷移先モジュールが設定されているとき、モジュール名を設定する forward.setModule(((ExceptionConfigEx) eConfig).getModule()); // ログレベルを取得する logLevel = ((ExceptionConfigEx) eConfig).getLogLevel(); } // 【SystemExceptionの場合、エラーキーとエラーメッセージの置換を行う】 if (ex instanceof SystemException) { SystemException se = (SystemException) ex; // 【リクエストからメッセージリソースを取得する。】 MessageResources resources = null; // スコープからメッセージリソースを取得する際のバンドルキーを取得する。 String bundle = eConfig.getBundle(); if (bundle == null) { // struts-config.xmlのmessage-resourcesで // bundle属性が指定されていない場合、 // デフォルトのバンドルキーを設定する bundle = Globals.MESSAGES_KEY; } // リクエスト属性からの取得を試みる。 resources = (MessageResources) request.getAttribute(bundle); if (resources == null) { // リクエスト属性になければアプリケーション属性からの取得を試みる。 resources = (MessageResources) RequestUtil.getServletContext(request).getAttribute(bundle); } // 【エラーキーとエラーメッセージの置換を行う】 // SystemExceptionのエラーキーをエラーメッセージに置換する。 String message = null; if (resources == null) { // リソース取得できない場合はエラーキーをメッセージとする message = se.getErrorCode(); } else { message = getErrorMessage(request, se, resources); } se.setMessage(message); // 【画面表示用にActionMessageを設定する】 String key = eConfig.getKey(); ActionMessage error = null; if (resources != null) { // エラーメッセージの置換文字列を取得する String[] options = se.getOptions(); if (options != null && options.length > 0) { error = new ActionMessage(key, options); } else { error = new ActionMessage(key); } } else { // 画面であってもメッセージリソースが無い場合はエラーキーをメッセージにする error = new ActionMessage(key, false); } super.storeException(request, key, error, forward, eConfig.getScope()); // 変換された例外メッセージ、スタックトレースと // セッションハッシュ値をログに出力 String sessionHash = RequestUtil.getSessionHash(request); logException(logLevel, "sessionHash = " + sessionHash); logException(logLevel, ExceptionUtil.getStackTrace(se)); // 【置換済のSystemExceptionを設定する】 // システム例外をJSPエラーページで exception として // 取得できるように request に設定する request.setAttribute(PageContext.EXCEPTION, se); } // システムエラー時は、アクションマッピングの設定に沿って遷移する。 return forward; }
/** * Hooks into validate to catch any errors from the populate, and translate the ErrorMap to * ActionMessages. */ @Override protected boolean processValidate( HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping) throws IOException, ServletException, InvalidCancelException { // skip form validate if we had errors from populate if (GlobalVariables.getMessageMap().hasNoErrors()) { if (form == null) { return (true); } // Was this request cancelled? if (request.getAttribute(Globals.CANCEL_KEY) != null) { if (LOG.isDebugEnabled()) { LOG.debug(" Cancelled transaction, skipping validation"); } return (true); } // Has validation been turned off for this mapping? if (!mapping.getValidate()) { return (true); } // call super to call forms validate super.processValidate(request, response, form, mapping); } publishMessages(request); if (!GlobalVariables.getMessageMap().hasNoErrors()) { // Special handling for multipart request if (form.getMultipartRequestHandler() != null) { if (LOG.isDebugEnabled()) { LOG.debug(" Rolling back multipart request"); } form.getMultipartRequestHandler().rollback(); } // Fix state that could be incorrect because of validation failure if (form instanceof PojoForm) { ((PojoForm) form).processValidationFail(); } // Was an input path (or forward) specified for this mapping? String input = mapping.getInput(); if (input == null) { if (LOG.isDebugEnabled()) { LOG.debug(" Validation failed but no input form available"); } response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, getInternal().getMessage("noInput", mapping.getPath())); return (false); } if (moduleConfig.getControllerConfig().getInputForward()) { ForwardConfig forward = mapping.findForward(input); processForwardConfig(request, response, forward); } else { internalModuleRelativeForward(input, request, response); } return (false); } return true; }
public ActionForward execute( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { logger.debug("********************************************"); logger.debug("*** Entering ProcessFirstCallInformation ***"); CemAnStatus form = (CemAnStatus) actionForm; ActionErrors errors = new ActionErrors(); formErrors = new ArrayList(); HttpSession session = request.getSession(); DbUserSession sessionUser = (DbUserSession) session.getAttribute(SessionValueKeys.DB_USER); logger.debug("ExecutorSame request value : " + request.getParameter("executorSame")); DatabaseTransaction t = null; FdmsDb fdmsdb = null; DbVitalsDeceased deceased = null; DbVitalsInformant informant = null; DbVitalsFirstCall firstCall = null; DbCase caseinfo = null; DbVitalsNextKin nextkin = null; DbPreneed preneed = null; DbVitalsSchedule sched = null; DbVitalsExecutor executor = null; DbCemAtneed cematneed = null; boolean addmode = false; int vitalsid = 0; String directive = form.getDirective(); // Try to set the vitalsid from the form. try { vitalsid = FormatNumber.parseInteger(form.getVitalsId()); } catch (Exception e) { vitalsid = 0; } cematneed = new DbCemAtneed(); cematneed.setNew(); if (directive.equals("cancel")) { // go back to case status unless no vitalsid then, show introduction. vitalsid = SessionHelpers.getVitalsIdFromSession(request, sessionUser); if (vitalsid > 0) { return mapping.findForward("showCaseStatusGlobal"); } else { return mapping.findForward("ShowIntroductionGlobal"); } } if (directive.equals("help")) { return mapping.findForward("usingHelp"); } // From this point, we need to access the database try { t = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser); fdmsdb = FdmsDb.getInstance(); if (directive.equals("redisplay")) { redisplayForm(t, sessionUser, form, errors); form.setDirective(" "); session.setAttribute("cemAnStatus", form); return new ActionForward(mapping.getInput()); } validateForm(t, sessionUser, form, errors); // if errors found, return to input screen without saving anything if (!errors.isEmpty()) { // AppLog.info("ProcessFirstCall Invoking forward mapping getInput() after validation."); saveErrors(request, errors); request.setAttribute("formErrors", formErrors); form.setDirective(" "); session.setAttribute("cemAnStatus", form); return new ActionForward(mapping.getInput()); } else { // AppLog.trace("ProcessFirstCall past validation."); } // Get the DbVitalDeceased and DbVitalsFirstCall objects if (vitalsid == 0) { deceased = new DbVitalsDeceased(); deceased.setNew(); addmode = true; } else { deceased = fdmsdb.getVitalsDeceased(t, vitalsid); } // Set the data in the DbVitalsDeceased and DbVitalsFirstCall records setVitalsDeceased(deceased, informant, form, errors); // if errors found, return to input screen without saving anything if (!errors.isEmpty()) { // AppLog.info("ProcessFirstCall Invoking forward mapping getInput() after // setVitalsDeceased."); saveErrors(request, errors); request.setAttribute("formErrors", formErrors); session.setAttribute("cemAnStatus", form); form.setDirective(" "); return new ActionForward(mapping.getInput()); } else { // AppLog.trace("ProcessFirstCall past setVitalsDeceased."); } if (vitalsid == 0) { t.addPersistent(deceased); t.save(); t.closeConnection(); t = null; vitalsid = deceased.getId(); form.setVitalsId(String.valueOf(vitalsid)); sessionUser.setCurrentCaseID(vitalsid); // Need another transaction to continue with add t = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser); // increment next contract number if user did not change it // and assign to this case // if user changed contract# then use the one they entered. if (form.getContractNumber().equals(form.getNextContractNumber())) { int newnextno = SessionHelpers.nextContractNumber(sessionUser.getDbLookup(), sessionUser.getRegion()); form.setContractNumber(String.valueOf(newnextno)); form.setNextContractNumber(form.getContractNumber()); // need new transaction since save in above method ends that transaction } sched = fdmsdb.getVitalsSchedule(t, vitalsid); sched.setDefaultAtNeedCheckList(sessionUser.getRegion(), sessionUser.getDbLookup()); } else { sched = fdmsdb.getVitalsSchedule(t, vitalsid); } // Now, lets update the other Vitals information SessionHelpers.setVitalsIdInRequest(request, vitalsid); firstCall = fdmsdb.getVitalsFirstCall(t, vitalsid); informant = fdmsdb.getVitalsInformant(t, vitalsid); caseinfo = fdmsdb.getCase(t, vitalsid); nextkin = fdmsdb.getVitalsNextKin(t, vitalsid); executor = fdmsdb.getVitalsExecutor(t, vitalsid); // cematneed = fdmsdb.getCemAtneed(t, vitalsid); if (executor == null) { executor = new DbVitalsExecutor(); executor.setNew(); } setVitalsRest( t, sessionUser, deceased, firstCall, informant, caseinfo, nextkin, executor, cematneed, form, errors); // if errors found, return to input screen without saving anything if (!errors.isEmpty()) { // AppLog.info("ProcessFirstCall Invoking forward mapping getInput() after setVitalsRest."); saveErrors(request, errors); request.setAttribute("formErrors", formErrors); session.setAttribute("cemAnStatus", form); form.setDirective(" "); return new ActionForward(mapping.getInput()); } else { logger.debug("no errors exist in processfirstcall information"); // AppLog.trace("ProcessFirstCall past setVitalsRest."); } // determine whether active preneed or deceased preneed = fdmsdb.getPreneed(t, vitalsid); String relation = "Deceased"; if (preneed.getStatus().equals(DbPreneed.ACTIVE)) { relation = "Preneed"; } t.removePersistent(preneed); // update special survivor information for searching deceased, informant, case#, contract# DbSurvivor.addUpdateSurvivor( t, vitalsid, DbSurvivor.DECEASED, deceased.getSalutation(), deceased.getDecFName(), deceased.getDecMName(), deceased.getDecLName(), deceased.getSuffix(), deceased.getMaidenName(), deceased.getFullName(), deceased.getDecResStreet() + " " + deceased.getDecAptNo(), "", deceased.getDecResMailCity(), deceased.getDecResState(), deceased.getDecResZip(), "", "", "", relation, "", "", ""); DbSurvivor.addUpdateSurvivor( t, vitalsid, DbSurvivor.INFORMANT, informant.getSalutation(), informant.getFname(), informant.getMname(), informant.getLname(), "", "", "", informant.getStreet() + " " + informant.getRoad2() + " " + informant.getRoad3(), "", informant.getCity(), informant.getState(), informant.getZip(), informant.getPhone(), "", informant.getInformantEmail(), "Informant", "", "", ""); DbSurvivor.addUpdateSurvivor( t, vitalsid, DbSurvivor.CONTRACT, "", deceased.getDecLName(), "", caseinfo.getContractCode(), "", "", "", "", "", "", "", "", "", "", "", deceased.getDecFName(), "", "", ""); DbSurvivor.addUpdateSurvivor( t, vitalsid, DbSurvivor.CASECODE, "", deceased.getDecLName(), "", caseinfo.getCaseCode(), "", "", "", "", "", "", "", "", "", "", "", deceased.getDecFName(), "", "", ""); // add informant and next-of-kin as normal survivors but only during add cycle if (addmode) { // AppLog.trace("Adding informant and NOK as survivors."); DbSurvivor infsurv = new DbSurvivor( vitalsid, informant.getSalutation(), informant.getFname(), informant.getMname(), informant.getLname(), "", "", "", informant.getStreet() + " " + informant.getRoad2() + " " + informant.getRoad3(), "", informant.getCity(), informant.getState(), informant.getZip(), informant.getPhone(), "", informant.getInformantEmail(), informant.getRelated(), "", "", "", ""); t.addPersistent(infsurv); if (!form.getNextKinSame()) { DbSurvivor noksurv = new DbSurvivor( vitalsid, nextkin.getSalutation(), nextkin.getFirstname(), "", nextkin.getLastname(), "", "", "", nextkin.getStreet() + nextkin.getRoad2() + " " + nextkin.getRoad3(), "", nextkin.getCity(), nextkin.getState(), nextkin.getZip(), nextkin.getPhone(), "", "", nextkin.getRelation(), "", "", "", ""); t.addPersistent(noksurv); } } t.addPersistent(cematneed); if (executor != null) t.addPersistent(executor); // Final commit and cleanup t.save(); } catch (PersistenceException pe) { logger.error("PersistenceException in doPerform() : ", pe); errors.add( ActionErrors.GLOBAL_ERROR, new ActionError("error.PersistenceException", pe.getCause())); } catch (Exception pe) { logger.error("Error in doPerform() : ", pe); errors.add( ActionErrors.GLOBAL_ERROR, new ActionError("error.GeneralException", pe.getMessage())); } finally { if (t != null) { try { t.closeConnection(); t = null; } catch (Exception e) { logger.error("Error in closeConnection() : ", e); } } } if (!errors.isEmpty()) { // AppLog.info("ProcessFirstCallInformation Invoking forward mapping getInput()."); saveErrors(request, errors); request.setAttribute("formErrors", formErrors); form.setDirective(" "); session.setAttribute("cemAnStatus", form); return (new ActionForward(mapping.getInput())); } // remove session variables used in FirstCall page SessionHelpers.removeArrangerListFromSession(request); SessionHelpers.removeChapelListInSession(request); session.removeAttribute("cemAnStatus"); SessionHelpers.setVitalsIdInRequest(request, vitalsid); // Since we are forwarding to another ACTION, need to go through this exercise /* ActionMappings mappings = mapping.getMappings(); String returnPath = actionForward.getPath(); int periodpos = returnPath.indexOf(".do"); returnPath = returnPath.substring(0,periodpos); ActionMapping finalMapping = mappings.findMapping(returnPath); Action finalAction = null; try { Class clazz = Class.forName(finalMapping.getType()); finalAction = (Action) clazz.newInstance(); AppLog.trace("chaining to:"+finalAction.toString()); } catch (Exception e) { AppLog.warning("Could not find chained action: " + e.getMessage()); return forwardGlobalCancel(mapping) ; } return finalAction.perform(finalMapping,form,request,response); */ // return forwardShowCaseStatusGlobal(mapping); if (errors.isEmpty()) { request.setAttribute("redirect", Boolean.TRUE); request.setAttribute("vitalsId", new Integer(vitalsid)); } return new ActionForward(mapping.getInput()); }
public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { ActionErrors errors = new ActionErrors(); HttpSession session = request.getSession(); DbUserSession sessionUser = SessionHelpers.getUserSession(request); DatabaseTransaction t = null; DbSpeedData[] dbSpeedData = null; DbLocation[] dbLocation = null; LocaleDTO userlocale = null; MiscCashReceiptsForm miscCashReceipts = new MiscCashReceiptsForm(); java.util.ArrayList locationList = new java.util.ArrayList(); java.util.ArrayList glDescriptionList = new java.util.ArrayList(); java.util.ArrayList cashAcctList = new java.util.ArrayList(); java.util.ArrayList payMethodList = new java.util.ArrayList(); java.util.ArrayList pleaseSelect = new java.util.ArrayList(); if (sessionUser == null) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.login.invalid")); } // Database Access Logic try { t = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser); // Set the list of receipt types in session. SessionHelpers.setReceiptTypesInSession(request); // Populate the locationList collection dbLocation = FdmsDb.getInstance().getLocationsForRegion(t, sessionUser.getRegion()); // AppLog.trace("DbLocation list length = " +dbLocation.length); for (int i = 0; i < dbLocation.length; i++) { String listValue = String.valueOf(dbLocation[i].getId()); String listLabel = dbLocation[i].getName(); locationList.add(new OptionsList(listValue, listLabel)); } // Populate the glDescriptionList collection dbSpeedData = FdmsDb.getInstance() .getSpeedData(sessionUser.getDbLookup(), sessionUser.getRegion(), "REVTYPE"); // AppLog.trace("DbSpeedData for REVTYPE list length = " +dbSpeedData.length); for (int i = 0; i < dbSpeedData.length; i++) { String listValue = CsvTable.getField(dbSpeedData[i].getData(), 2); String listLabel = CsvTable.getField(dbSpeedData[i].getData(), 1); glDescriptionList.add(new OptionsList(listValue, listLabel)); } // Populate the cashAcctList collection dbSpeedData = FdmsDb.getInstance() .getSpeedData(sessionUser.getDbLookup(), sessionUser.getRegion(), "CASHTYPE"); // AppLog.trace("DbSpeedData for CASHTYPE list length = " +dbSpeedData.length); for (int i = 0; i < dbSpeedData.length; i++) { String listValue = CsvTable.getField(dbSpeedData[i].getData(), 2); String listLabel = CsvTable.getField(dbSpeedData[i].getData(), 1); cashAcctList.add(new OptionsList(listValue, listLabel)); } // Populate the payMethodList", payMethodList) userlocale = FdmsDb.getInstance().getLocale(sessionUser.getDbLookup(), sessionUser.getRegion()); dbSpeedData = FdmsDb.getInstance() .getSpeedData(sessionUser.getDbLookup(), sessionUser.getRegion(), "PAYMETHOD"); // AppLog.trace("DbSpeedData for PAYMETHOD list length = " +dbSpeedData.length); for (int i = 0; i < dbSpeedData.length; i++) { if (dbSpeedData[i].getData() != null && dbSpeedData[i].getData().length() > 1) { String listValue = dbSpeedData[i].getData().substring(0, 2); String listLabel = dbSpeedData[i].getData(); payMethodList.add(new OptionsList(listValue, listLabel)); } } // Form Defaults miscCashReceipts.setSubmitButton(""); miscCashReceipts.setAmountOfTran("0"); miscCashReceipts.setDateOfTran(FormatDate.getCurrentDateFormatedMMDDYYYY()); miscCashReceipts.setFormId("None"); miscCashReceipts.setReceiptNumber(String.valueOf(userlocale.getNextReceiptNo())); pleaseSelect.add(new OptionsList("", "--Select--")); // AppLog.trace("Finished setting miscCashReceipts form bean"); } catch (PersistenceException pe) { logger.error("Persistence Exception in ShowMiscCashReceipts.doPerform. " + pe); errors.add( ActionErrors.GLOBAL_ERROR, new ActionError("error.PersistenceException", pe.getCause())); } catch (Exception pe) { logger.error("Exception in ShowMiscCashReceipts.doPerform. ", pe); errors.add( ActionErrors.GLOBAL_ERROR, new ActionError("error.GeneralException", pe.getMessage())); } finally { if (t != null) t.closeConnection(); } // Set Form Bean Into Scope session.setAttribute("miscCashReceipts", miscCashReceipts); session.setAttribute("locationList", locationList); session.setAttribute("glDescriptionList", glDescriptionList); session.setAttribute("cashAcctList", cashAcctList); session.setAttribute("payMethodList", payMethodList); session.setAttribute("pleaseSelect", pleaseSelect); // AppLog.trace("Setting miscCashReceipts form bean and collection arrays into session scope."); ActionForward actionForward = mapping.findForward("miscCashReceipts"); if (!errors.isEmpty()) { // AppLog.info("ShowMiscCahsReceipts invoking forward mapping getInput()."); saveErrors(request, errors); actionForward = new ActionForward(mapping.getInput()); } return actionForward; }
public ActionForward executeAction( 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_INV_DOCTYPES_EDIT, ISecurityAPI.FUNC_INV_TEMPLATES_EDIT}); IInvesflowAPI invesFlowAPI = session.getAPI(); ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI(); ITemplateAPI templateAPI = invesFlowAPI.getTemplateAPI(); // Formulario asociado a la acción UploadForm defaultForm = (UploadForm) form; int keyId = Integer.parseInt(defaultForm.getKey()); int entityId = Integer.parseInt(defaultForm.getEntity()); String name = defaultForm.getProperty("NOMBRE"); String code = defaultForm.getProperty("COD_PLANT"); CTTemplate template = null; try { if (keyId == ISPACEntities.ENTITY_NULLREGKEYID) { int type = Integer.parseInt(defaultForm.getProperty("ID_TPDOC")); String expresion = defaultForm.getProperty("EXPRESION"); FormFile fichero = defaultForm.getUploadFile(); EntityApp entityapp = catalogAPI.getCTDefaultEntityApp(entityId, getRealPath("")); // Comprobar si existe otra plantilla con el mismo nombre IItemCollection itemcol = catalogAPI.queryCTEntities( ICatalogAPI.ENTITY_CT_TEMPLATE, " WHERE NOMBRE = '" + DBUtil.replaceQuotes(name) + "'"); if (itemcol.next() && !isGeneric(templateAPI, itemcol)) { ActionMessages errors = new ActionMessages(); errors.add( "property(NOMBRE)", new ActionMessage("error.template.nameDuplicated", new String[] {name})); saveAppErrors(request, errors); return new ActionForward(mapping.getInput()); } // Comprobar si existe otra plantilla con el mismo código if (StringUtils.isNotBlank(code)) { itemcol = catalogAPI.queryCTEntities( ICatalogAPI.ENTITY_CT_TEMPLATE, " WHERE COD_PLANT = '" + DBUtil.replaceQuotes(code) + "'"); if (itemcol.next()) { ActionMessages errors = new ActionMessages(); errors.add( "property(COD_PLANT)", new ActionMessage("error.template.codeDuplicated", new String[] {code})); saveAppErrors(request, errors); return new ActionForward(mapping.getInput()); } } if (!entityapp.validate()) { ActionMessages errors = new ActionMessages(); List errorList = entityapp.getErrors(); Iterator iteError = errorList.iterator(); while (iteError.hasNext()) { ValidationError validError = (ValidationError) iteError.next(); ActionMessage error = new ActionMessage(validError.getErrorKey(), validError.getArgs()); errors.add(ActionMessages.GLOBAL_MESSAGE, error); } saveAppErrors(request, errors); return new ActionForward(mapping.getInput()); } if (fichero.getFileName().equals("")) { template = templateAPI.newTemplate(type, name, code, 0, expresion, null); } else { if (fichero.getFileSize() > 0) { // Comprobar si el tipo MIME de la plantilla está soportado String mimeType = MimetypeMapping.getFileMimeType(fichero.getFileName()); // Se comprueba si esta habilitado el uso de plantillas ODT if (StringUtils.equals(mimeType, "application/vnd.oasis.opendocument.text") && !ConfigurationMgr.getVarGlobalBoolean( session.getClientContext(), ConfigurationMgr.USE_ODT_TEMPLATES, false)) { throw new ISPACInfo( getResources(request).getMessage("exception.template.odt.disabled")); } if (templateAPI.isMimeTypeSupported(mimeType)) { template = templateAPI.newTemplate( type, name, code, 0, expresion, fichero.getInputStream(), mimeType); } else { throw new ISPACInfo( getResources(request).getMessage("exception.template.document.invalidFile")); } } else { throw new ISPACInfo("exception.uploadfile.empty"); } } } else { EntityApp entityapp = catalogAPI.getCTDefaultEntityApp(entityId, getRealPath("")); // Comprobar si existe otra plantilla con el mismo nombre IItemCollection itemcol = catalogAPI.queryCTEntities( ICatalogAPI.ENTITY_CT_TEMPLATE, " WHERE NOMBRE = '" + DBUtil.replaceQuotes(name) + "' AND ID != " + keyId); if (itemcol.next() && !isGeneric(templateAPI, itemcol)) { ActionMessages errors = new ActionMessages(); errors.add( "property(NOMBRE)", new ActionMessage("error.template.nameDuplicated", new String[] {name})); saveAppErrors(request, errors); return new ActionForward(mapping.getInput()); } // Comprobar si existe otra plantilla con el mismo código if (StringUtils.isNotBlank(code)) { itemcol = catalogAPI.queryCTEntities( ICatalogAPI.ENTITY_CT_TEMPLATE, " WHERE COD_PLANT = '" + DBUtil.replaceQuotes(code) + "' AND ID != " + keyId); if (itemcol.next()) { ActionMessages errors = new ActionMessages(); errors.add( "property(COD_PLANT)", new ActionMessage("error.template.codeDuplicated", new String[] {code})); saveAppErrors(request, errors); return new ActionForward(mapping.getInput()); } } defaultForm.processEntityApp(entityapp); entityapp.getItem().set("FECHA", new Date()); entityapp.store(); } } catch (Exception e) { ActionForward action = mapping.findForward("success"); String url = action.getPath() + "?entity=" + entityId + "&type=" + defaultForm.getProperty("ID_TPDOC") + "&key=" + keyId; request.getSession().setAttribute(BaseAction.LAST_URL_SESSION_KEY, url); if (e instanceof ISPACInfo) { throw e; } else { throw new ISPACInfo(e.getMessage()); } } if (template != null) { keyId = template.getInt("TEMPLATE:ID"); } ActionForward action = mapping.findForward("success"); String redirected = action.getPath() + "?entity=" + entityId + "&type=" + defaultForm.getProperty("ID_TPDOC") + "&key=" + keyId; return new ActionForward(action.getName(), redirected, true); }
public ActionForward store( 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(); IInvesflowAPI invesFlowAPI = session.getAPI(); ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI(); // Formulario asociado a la acción CalendarForm defaultForm = (CalendarForm) form; // int keyId = Integer.parseInt(defaultForm.getKey()); // int entityId = Integer.parseInt(defaultForm.getEntity()); String parameter = request.getParameter("entityId"); if (parameter == null) { parameter = defaultForm.getEntity(); } int entityId = Integer.parseInt(parameter); parameter = request.getParameter("regId"); int condicion = Integer.parseInt(parameter); if (parameter == null) { parameter = defaultForm.getKey(); } int keyId = Integer.parseInt(parameter); EntityApp entityapp = null; String path = getRealPath(""); // Ejecución en un contexto transaccional boolean bCommit = false; try { // Abrir transacción cct.beginTX(); // Obtener la aplicación que gestiona la entidad if (keyId == ISPACEntities.ENTITY_NULLREGKEYID) { entityapp = catalogAPI.newCTDefaultEntityApp(entityId, path); keyId = entityapp.getEntityRegId(); } else { entityapp = catalogAPI.getCTDefaultEntityApp(entityId, path); } // Permite modificar los datos del formulario defaultForm.setReadonly("false"); // Salva el identificador de la entidad defaultForm.setEntity(Integer.toString(entityId)); // Salva el identificador del registro defaultForm.setKey(Integer.toString(keyId)); defaultForm.processEntityApp(entityapp); // Se le asigna la clave del registro. Es necesario ya que el // item al que hace referencia puede estar recien creado y por tanto // tendría su campo clave a -1 (ISPACEntities.ENTITY_REGKEYID) entityapp.getItem().setKey(keyId); // entityapp.setAppName("EditCalendar"); if (!entityapp.validate()) { ActionMessages errors = new ActionMessages(); List errorList = entityapp.getErrors(); Iterator iteError = errorList.iterator(); while (iteError.hasNext()) { ValidationError validError = (ValidationError) iteError.next(); ActionMessage error = new ActionMessage(validError.getErrorKey(), validError.getArgs()); errors.add("property(NOMBRE)", error); } saveErrors(request, errors); return new ActionForward(mapping.getInput()); } // Guardar la entidad entityapp.store(); // Si todo ha sido correcto se hace commit de la transacción bCommit = true; } catch (ISPACException e) { if (entityapp != null) { // Establecer la aplicación para acceder a los valores extra en // el formulario defaultForm.setValuesExtra(entityapp); // Página jsp asociada a la presentación de la entidad request.setAttribute("application", entityapp.getURL()); request.setAttribute("EntityId", Integer.toString(entityId)); request.setAttribute("KeyId", Integer.toString(keyId)); throw new ISPACInfo(e.getMessage()); } else { // Suele producirse error en las secuencias al estar mal // inicializadas // provocando una duplicación de keys throw e; } } finally { cct.endTX(bCommit); } if (condicion == ISPACEntities.ENTITY_NULLREGKEYID) { return getActionForwardShow(String.valueOf(entityId), String.valueOf(keyId)); } return updateWeekEnd(mapping, defaultForm, request, response, session); // ActionForward forward = mapping.findForward("ShowEntity" + entityId); // if (forward == null) { // // forward = mapping.findForward("reloadShowEntity" + entityId); // if (forward == null) { // forward = mapping.findForward("reload"); // } // // String redirected = forward.getPath() + "?entityId=" + entityId + "®Id=" + keyId; // if (request.getQueryString() != null) { // redirected += "&" + request.getQueryString(); // } // forward = new ActionForward(forward.getName(), redirected, true); // } // // return forward; }
public ActionForward execute( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { formErrors = new ArrayList(); MiscCashReceiptsForm form = (MiscCashReceiptsForm) actionForm; ActionErrors errors = new ActionErrors(); HttpSession session = request.getSession(); DbUserSession sessionUser = SessionHelpers.getUserSession(request); DatabaseTransaction t = null; DbHistory dbHistory = null; if (form.getSubmitButton() != null && form.getSubmitButton().equals("exit")) { ActionForward actionForward = mapping.findForward("financial"); return actionForward; } try { t = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser); // AppLog.trace("ProcessMiscCashReceipts submit ="+form.getSubmitButton()); // --- HANDLE PRINTING A RECEIPT --- if (form.getFormId() != null && form.getFormId().trim().length() > 0 && (!form.getFormId().equals("None"))) { // AppLog.trace("ProcessMiscCashReceipts printing receipt form: "+form.getFormId()); if (FormatNumber.parseInteger(form.getFormId()) < 1) { // AppLog.error("ProcessMiscCashReceipts - No receipt type selected."); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.tables.noselect")); formErrors.add("formId"); t.closeConnection(); return (new ActionForward(mapping.getInput())); } } if (form.getSubmitButton().equals("save")) { dbHistory = new DbHistory(); dbHistory.setNew(); validateData(form, errors); if (errors.isEmpty()) { setHistory(t, sessionUser, dbHistory, form, errors); if (errors.isEmpty()) { t.save(); } else { // AppLog.criticalError("Exception in ProcessMiscCashReceipts.setHistory."); } } else { // AppLog.trace("Validation Errors in ProcessMiscCashReceipts; returning to // MiscCashReceipts form."); } } // --- HANDLE PRINTING A RECEIPT --- if (errors.isEmpty() && FormatNumber.parseInteger(form.getFormId()) > 0) { String crystalFlag = UtilSingleton.getInstance() .getProperty(sessionUser.getConfigID(), "CrystalServer.useReportingService"); String pageName = null; if (crystalFlag != null && "true".equals(crystalFlag)) { CrystalReportManagerBean crystalServerReport = new CrystalReportManagerBean(sessionUser.getConfigID()); pageName = crystalServerReport.printReport( sessionUser, FormatNumber.parseInteger(form.getFormId()), "", "", null, "", Integer.toString(dbHistory.getId()), true); } else { ExportReport crystal = new ExportReport(); crystal.setRecordIdSelParam(dbHistory.getId()); // selection parameter pageName = crystal.printForm( sessionUser, FormatNumber.parseInteger(form.getFormId()), "", "", null, "", request, response, servlet.getServletContext()); } form = new MiscCashReceiptsForm(); setNewForm(request, sessionUser, session, form, errors); form.setPreviewFile(pageName); // AppLog.trace("Setting miscCashReceipts collection arrays into session scope."); session.setAttribute("miscCashReceipts", form); ActionForward actionForward = mapping.findForward("showMiscCashReceipts"); return actionForward; } } catch (PersistenceException pe) { logger.error("Persistence Exception in ProcessMiscCashReceipts.doPerform. " + pe); errors.add( ActionErrors.GLOBAL_ERROR, new ActionError("error.PersistenceException", pe.getCause())); } catch (Exception pe) { logger.error("Exception in ProcessMiscCashReceipts.doPerform. ", pe); errors.add( ActionErrors.GLOBAL_ERROR, new ActionError("error.GeneralException", pe.getMessage())); } finally { if (t != null) { t.closeConnection(); } } // Action Forward Logic ActionForward actionForward = mapping.findForward("showMiscCashReceiptsGlobal"); if (!errors.isEmpty()) { // AppLog.info("ProcessMiscCashReceipts Invoking forward mapping getInput() "); saveErrors(request, errors); request.setAttribute("formErrors", formErrors); actionForward = new ActionForward(mapping.getInput()); } logger.debug("Leaving ProcessMiscCashReceipts."); return actionForward; }