@Override protected ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { logger.debug("onSubmit - START"); // used as a container for info/error messages ArrayList<String> infoMessages = new ArrayList<String>(); ArrayList<String> errorMessages = new ArrayList<String>(); ModelAndView mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES); try { boolean isDeleteAction = false; // check if i have deleteAll action if (request.getParameter(ACTION) != null && DELETEALL.equals(request.getParameter(ACTION))) { handleDeleteAll(request, command, infoMessages, errorMessages); isDeleteAction = true; } if (request.getParameter(ACTION) != null && PAGINATION.equals(request.getParameter(ACTION))) { mav = handlePagination(request, errorMessages, command); } else { mav = handleSearch(request, command, errorMessages, isDeleteAction); } } catch (BusinessException bexc) { logger.error(bexc.getMessage(), bexc); errorMessages.add( messageSource.getMessage( SEARCH_ERROR, new Object[] { bexc.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime() }, RequestContextUtils.getLocale(request))); } catch (Exception e) { logger.error("", e); errorMessages.add( messageSource.getMessage( SEARCH_EXCEPTION_ERROR, new Object[] {ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } // setting all messages on response setErrors(request, errorMessages); setMessages(request, infoMessages); mav.addAllObjects(referenceData(request, command, errors)); logger.debug("onSubmit - END"); return mav; }
/** * Utility method for creating a GrailsDataBinder instance * * @param target The target object to bind to * @param objectName The name of the object * @param request A request instance * @return A GrailsDataBinder instance */ public static GrailsDataBinder createBinder( Object target, String objectName, HttpServletRequest request) { GrailsDataBinder binder = createBinder(target, objectName); Locale locale = RequestContextUtils.getLocale(request); registerCustomEditors(binder, locale); return binder; }
@Override protected ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { logger.debug("onSubmit - START"); ModelAndView mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES); Currency currency = (Currency) command; Locale locale = RequestContextUtils.getLocale(request); ArrayList<String> errorMessages = new ArrayList<String>(); ArrayList<String> infoMessages = new ArrayList<String>(); // check if the currency has a currencyId if (currency.getCurrencyId() != -1) { // if I have currencyId, it means that I have "update" action logger.debug("onSubmit - handleUpdate"); mav = handleUpdate(currency, request, locale, errorMessages, infoMessages); } else { // if I don't have currency, it means that I have "add" action logger.debug("onSubmit - handleAdd"); mav = handleAdd(currency, request, locale, errorMessages, infoMessages); } setErrors(request, errorMessages); setMessages(request, infoMessages); mav.addAllObjects(referenceData(request, currency, errors)); logger.debug("onSubmit - END"); return mav; }
@Override protected ModelAndView onSubmit( final HttpServletRequest request, final HttpServletResponse response, final Object command, final BindException errors) throws Exception { final TrackCommand trackCommand = (TrackCommand) command; final String trackingIdString = trackCommand.getTrackingId(); final Cargo cargo = trackingService.track(new TrackingId(trackingIdString)); final Map<String, CargoTrackingViewAdapter> model = new HashMap(); if (cargo != null) { final MessageSource messageSource = getApplicationContext(); final Locale locale = RequestContextUtils.getLocale(request); model.put("cargo", new CargoTrackingViewAdapter(cargo, messageSource, locale)); } else { errors.rejectValue( "trackingId", "cargo.unknown_id", new Object[] {trackCommand.getTrackingId()}, "Unknown tracking id"); } return showForm(request, response, errors, model); }
protected void processAjaxRequest( Form form, HttpServletRequest request, HttpServletResponse response) throws IOException { AjaxResponse ajaxResponse = new AjaxResponse(response); if (form != null) { form.getFormContext().setWriter(response.getWriter()); form.setFormListener(ajaxResponse); if (isEventRequest(request)) { processEventRequest(form, request); } else { processForm(form, request); } form.setFormListener(null); } else { String message = messageSource.getMessage( "error.sessionExpired", null, "Your session has expired", RequestContextUtils.getLocale(request)); ajaxResponse.alert(message); } ajaxResponse.close(); }
@ModelAttribute public void frontUrl(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception { // model.addAttribute("frontUrl", request.getContextPath() + "/resources"); userLoad(model); model.addAttribute("frontUrl", request.getContextPath() + "/resources"); // System.out.println("xDamsController.frontUrl() multiAccount: " + multiAccount); // System.out.println("xDamsController.frontUrl() model.get(\"userBean\"): " + // model.get("userBean")); if (multiAccount && model.get("userBean") != null) { model.addAttribute( "frontUrl", request.getContextPath() + "/resources/" + ((UserBean) model.get("userBean")).getAccountRef()); } // System.out.println("xDamsController.frontUrl() model.get(\"frontUrl\"): " + // model.get("frontUrl")); model.addAttribute("contextPath", request.getContextPath()); String userAgent = ((HttpServletRequest) request).getHeader("User-Agent"); if (userAgent.toLowerCase().contains("msie")) { response.addHeader("X-UA-Compatible", "IE=edge"); } try { Locale locale = RequestContextUtils.getLocale(request); ((UserBean) model.get("userBean")).setLanguage(locale.getLanguage()); } catch (Exception e) { // TODO: handle exception } model.put("realPath", WebUtils.getRealPath(servletContext, "")); }
@Override public ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { String pathInfo = request.getPathInfo(); String model = parseModelName(request); Locale locale = RequestContextUtils.getLocale(request); IModelEditor editor = sahaProjectRegistry.getModelEditor(model); IModelReader reader = sahaProjectRegistry.getModelReader(model); IConfigService config = sahaProjectRegistry.getConfig(model); String view = parseViewName(pathInfo); if (editor != null || view.equals("saha3/manage")) { ModelAndView mav = new ModelAndView(view); mav.addObject("model", model); mav.addObject("lang", locale.getLanguage()); if (config != null) { mav.addObject("aboutLink", config.getAboutLink()); mav.addObject("helpText", SahaHelpManager.getHelpString(view)); } return handleRequest(request, response, reader, editor, config, locale, mav); } else { response.sendRedirect("manage.shtml?model=" + URLEncoder.encode(model, "UTF-8")); return null; /* ModelAndView mav = new ModelAndView(SAHA_TEMPLATE_BASE + "/manage"); mav.addObject("sparqlConfiguration", sahaProjectRegistry.getSPARQLConfig(model)); mav.addObject("model", model); mav.addObject("lang", locale.getLanguage()); return mav; */ } }
/** * Expose the tool attributes, according to corresponding bean property settings. * * <p>Do not override this method unless for further tools driven by bean properties. Override one * of the <code>exposeHelpers</code> methods to add custom helpers. * * @param velocityContext Velocity context that will be passed to the template * @param request current HTTP request * @throws Exception if there's a fatal error while we're adding model attributes * @see #setVelocityFormatterAttribute * @see #setDateToolAttribute * @see #setNumberToolAttribute * @see #exposeHelpers(Map, HttpServletRequest) * @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest, * HttpServletResponse) */ protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception { // Expose generic attributes. if (this.toolAttributes != null) { for (Iterator it = this.toolAttributes.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); String attributeName = (String) entry.getKey(); Class toolClass = (Class) entry.getValue(); try { Object tool = toolClass.newInstance(); initTool(tool, velocityContext); velocityContext.put(attributeName, tool); } catch (Exception ex) { throw new NestedServletException( "Could not instantiate Velocity tool '" + attributeName + "'", ex); } } } // Expose VelocityFormatter attribute. if (this.velocityFormatterAttribute != null) { velocityContext.put(this.velocityFormatterAttribute, new VelocityFormatter(velocityContext)); } // Expose locale-aware DateTool/NumberTool attributes. if (this.dateToolAttribute != null || this.numberToolAttribute != null) { Locale locale = RequestContextUtils.getLocale(request); if (this.dateToolAttribute != null) { velocityContext.put(this.dateToolAttribute, new LocaleAwareDateTool(locale)); } if (this.numberToolAttribute != null) { velocityContext.put(this.numberToolAttribute, new LocaleAwareNumberTool(locale)); } } }
@Override protected Object formBackingObject(HttpServletRequest request) throws Exception { logger.debug("formBackingObject - START"); // used as a container for info/error messages ArrayList<String> errorMessages = new ArrayList<String>(); Currency currency = null; try { // check if i have to edit the currency if (ServletRequestUtils.getIntParameter(request, ID) != null && ServletRequestUtils.getStringParameter(request, IConstant.REQ_ACTION) != null && IConstant.CMD_GET.equals( ServletRequestUtils.getStringParameter(request, IConstant.REQ_ACTION))) { logger.debug("formBackingObject: GET"); // get the currency with the specified currencyId currency = handleGet( ServletRequestUtils.getIntParameter(request, ID).intValue(), errorMessages, request); if (currency == null) { currency = new Currency(); } } else { logger.debug("formBackingObject: ADD"); currency = new Currency(); // setting the organizationId for the new record Integer organizationId = (Integer) ControllerUtils.getInstance().getOrganisationIdFromSession(request); if (organizationId != null) { currency.setOrganizationId(organizationId); } } // if the view will be rendered in a panel we display only some fields request.setAttribute(GET_FROM_PANEL, request.getParameter(GET_FROM_PANEL)); request.setAttribute(FROM_EXCHANGE, request.getParameter(FROM_EXCHANGE)); request.setAttribute(FROM_COST_SHEET, request.getParameter(FROM_COST_SHEET)); request.setAttribute(FROM_TEAM_MEMBER_DETAIL, request.getParameter(FROM_TEAM_MEMBER_DETAIL)); request.setAttribute(FROM_PERSON_DETAIL, request.getParameter(FROM_PERSON_DETAIL)); request.setAttribute(FROM_PROJECT_DETAIL, request.getParameter(FROM_PROJECT_DETAIL)); request.setAttribute(FROM_ACTIVITY_PANEL, request.getParameter(FROM_ACTIVITY_PANEL)); } catch (Exception e) { logger.error("formBackingObject", e); errorMessages.add( messageSource.getMessage( GET_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } logger.debug("formBackingObject - END"); return currency; }
@Override protected ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { OutputStream out = response.getOutputStream(); response.setContentType("text/javascript"); byte[] buffer = getContents(RequestContextUtils.getLocale(request)); out.write(buffer); out.close(); return null; }
/** * Obtains the PropertyEditorRegistry instance. * * @return The PropertyEditorRegistry */ public PropertyEditorRegistry getPropertyEditorRegistry() { final HttpServletRequest servletRequest = getCurrentRequest(); PropertyEditorRegistry registry = (PropertyEditorRegistry) servletRequest.getAttribute(GrailsApplicationAttributes.PROPERTY_REGISTRY); if (registry == null) { registry = new PropertyEditorRegistrySupport(); GrailsDataBinder.registerCustomEditors( this, registry, RequestContextUtils.getLocale(servletRequest)); servletRequest.setAttribute(GrailsApplicationAttributes.PROPERTY_REGISTRY, registry); } return registry; }
protected ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { logger.debug("handleRequestInternal - START "); // used as a container for error messages ArrayList<String> errorMessages = new ArrayList<String>(); ModelAndView mav = new ModelAndView(getView()); // the user that logs in UserAuth userAuth = (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // adding to model the time unit nomenclator mav.addObject(IConstant.NOM_TIME_UNIT, TSContext.getFromContext(IConstant.NOM_TIME_UNIT)); try { // add the organization available currencies List<Currency> currencies = BLCurrency.getInstance().getByOrganizationId(userAuth.getOrganisationId()); if (currencies != null && currencies.size() > 0) { List<IntString> nomCurrencies = new ArrayList<IntString>(); for (Currency currency : currencies) { IntString entry = new IntString(); entry.setValue(currency.getCurrencyId()); entry.setLabel(currency.getName()); nomCurrencies.add(entry); } mav.addObject(ORG_CURRENCIES, nomCurrencies); } // if the view will be rendered in a panel we display only some fields request.setAttribute(GET_FROM_PANEL, request.getParameter(GET_FROM_PANEL)); } catch (BusinessException bexc) { logger.error(bexc.getMessage(), bexc); errorMessages.add( messageSource.getMessage( GET_ORG_CURRENCIES_ERROR, new Object[] { bexc.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime() }, RequestContextUtils.getLocale(request))); } setErrors(request, errorMessages); logger.debug("handleRequestInternal - END "); return mav; }
/** * Gets a Currency with all its components * * @author Coni * @param currencyId * @param errorMessages * @param request * @return */ public Currency handleGet( int currencyId, ArrayList<String> errorMessages, HttpServletRequest request) { logger.debug("handleGet - START"); Currency currency = null; try { currency = BLCurrency.getInstance().getAll(currencyId); } catch (BusinessException be) { logger.error("handleGet", be); errorMessages.add( messageSource.getMessage( GET_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } logger.debug("handleGet - START"); return currency; }
/** * Adds to model required nomenclators * * @author Coni */ @SuppressWarnings("unchecked") protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception { logger.debug("referenceData - start"); Map model = new HashMap(); ArrayList<String> errorMessages = new ArrayList<String>(); try { // adding to model the action from the request String action = ServletRequestUtils.getStringParameter(request, IConstant.REQ_ACTION); model.put(IConstant.REQ_ACTION, action); // put the back url String backUrl = ServletRequestUtils.getStringParameter(request, BACK_URL); String servletPath = request.getServletPath(); String nextBackUrl = URLEncoder.encode( servletPath .substring(1, servletPath.length()) .concat("?") .concat(request.getQueryString()), "UTF-8"); logger.debug("BACK_URL = " + backUrl); logger.debug("NEXT_BACK_URL = " + nextBackUrl); model.put(BACK_URL, backUrl); model.put(NEXT_BACK_URL, nextBackUrl); if (backUrl != null) { model.put(ENCODE_BACK_URL, URLEncoder.encode(backUrl, "UTF-8")); } } catch (Exception e) { logger.error("referenceData", e); errorMessages.add( messageSource.getMessage( GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } setErrors(request, errorMessages); logger.debug("referenceData - end"); return model; }
@Override protected void renderMergedOutputModel( Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { setTimeZoneForDateTimeFilter(); String templateFile = getServletContext().getRealPath(getUrl()); { // ThemeResolver themeResolver = RequestContextUtils // .getThemeResolver(request); // String theme = themeResolver.resolveThemeName(request); // if (logger.isDebugEnabled()) { // logger.debug("Current theme is " + theme); // } // templateFile = theme + File.separator + getUrl(); // templateFile = getServletContext().getRealPath(templateFile); } Locale locale = RequestContextUtils.getLocale(request); response.setContentType(getContentType()); engine.process(templateFile, model, response.getWriter(), locale); }
public Object resolveArgument( MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws IOException { Class<?> paramType = parameter.getParameterType(); if (WebRequest.class.isAssignableFrom(paramType)) { return webRequest; } HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); if (ServletRequest.class.isAssignableFrom(paramType) || MultipartRequest.class.isAssignableFrom(paramType)) { Object nativeRequest = webRequest.getNativeRequest(paramType); if (nativeRequest == null) { throw new IllegalStateException( "Current request is not of type [" + paramType.getName() + "]: " + request); } return nativeRequest; } else if (HttpSession.class.isAssignableFrom(paramType)) { return request.getSession(); } else if (Principal.class.isAssignableFrom(paramType)) { return request.getUserPrincipal(); } else if (Locale.class.equals(paramType)) { return RequestContextUtils.getLocale(request); } else if (InputStream.class.isAssignableFrom(paramType)) { return request.getInputStream(); } else if (Reader.class.isAssignableFrom(paramType)) { return request.getReader(); } else { // should never happen.. Method method = parameter.getMethod(); throw new UnsupportedOperationException( "Unknown parameter type: " + paramType + " in method: " + method); } }
private TransformerHandler createTransformerHandler() { try { TransformerHandlerImpl transformerHandler = (TransformerHandlerImpl) GENERIC_FACTORY.newTransformerHandler(templates); TransformerImpl impl = (TransformerImpl) transformerHandler.getTransformer(); XsltTransformer xslt = impl.getUnderlyingXsltTransformer(); Controller controller = (Controller) xslt.getUnderlyingController(); if (configuration != null) { for (Entry<String, Object> entry : configuration.entrySet()) { String name = entry.getKey(); // is valid XSLT parameter name if (XSLT_PARAMETER_NAME_PATTERN.matcher(name).matches()) { xslt.setParameter(new QName(name), new XdmExternalObject(entry.getValue())); } } } controller.setErrorListener(new TraxErrorListener(LOG, source.toExternalForm())); if (context != null) { xslt.setParameter(CoreConstants.APPLICATION_CONTEXT_PARAM, new XdmExternalObject(context)); } Map<String, Object> model = HttpContextHelper.getModel(parameters); xslt.setParameter(CoreConstants.MODEL_PARAM, new XdmExternalObject(model)); if (parameters != null) try { ServletContext servletContext = HttpContextHelper.getServletContext(parameters); xslt.setParameter( CoreConstants.SERVLET_CONTEXT_PARAM, new XdmExternalObject(servletContext)); HttpServletRequest servletRequest = HttpContextHelper.getRequest(parameters); HttpServletResponse servletResponse = HttpContextHelper.getResponse(parameters); if (servletRequest != null) { controller.setURIResolver(new SaxonResolver(servletRequest, servletResponse)); xslt.setParameter( Message.LOCALE_PARAM, new XdmExternalObject(RequestContextUtils.getLocale(servletRequest))); xslt.setParameter( CoreConstants.SERVLET_REQUEST_PARAM, new XdmExternalObject(servletRequest)); HttpSession session = servletRequest.getSession(false); if (session != null) { xslt.setParameter( CoreConstants.SERVLET_SESSION_PARAM, new XdmExternalObject(session)); } // add support for form binding xslt.setParameter( CoreConstants.REQUEST_CONTEXT_PARAM, new XdmExternalObject( new RequestContext(servletRequest, servletResponse, servletContext, model))); } if (servletResponse != null) { xslt.setParameter( CoreConstants.SERVLET_RESPONSE_PARAM, new XdmExternalObject(servletResponse)); } } catch (IllegalStateException e) { LOG.debug("Not a Servlet request!", e); // @SuppressWarnings({"rawtypes", "unchecked"}) // HashMap<String, Object> model = (HashMap) parameters.get("model"); // // HttpServletRequest servletRequest = new VirtualRequest(); // servletRequest.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, // context); // RequestContext requestContext = new RequestContext(servletRequest, model); // // transformer.setParameter(CoreConstants.REQUEST_CONTEXT_PARAM, requestContext); } return transformerHandler; } catch (TransformerConfigurationException ex) { throw new SetupException("Could not initialize transformer handler.", ex); } }
/** * @author Coni Searches for exchanges * @param request * @param command * @param errorMessages * @param isDeleteAction * @return * @throws BusinessException */ private ModelAndView handleSearch( HttpServletRequest request, Object command, ArrayList<String> errorMessages, boolean isDeleteAction) throws BusinessException { logger.debug("handeSearch - START"); ModelAndView mav = new ModelAndView(getSuccessView()); SearchExchangeBean searchExchangeBean = (SearchExchangeBean) command; List<Exchange> res = null; UserAuth userAuth = (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); DecimalFormat dfReal = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); dfReal.applyPattern("# ### ### ##0.0000"); DecimalFormat dfInt = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); dfInt.applyPattern("# ### ### ###"); try { res = BLExchange.getInstance().getResultsForSearch(searchExchangeBean, isDeleteAction); // set the exchange info panel header name for (Exchange exchange : res) { String headerName = exchange .getFirstCurrency() .getInitials() .concat(" - ") .concat(exchange.getSecondCurrency().getInitials()); String panelHeaderName = ControllerUtils.getInstance().truncateName(headerName, NR_CHARS_PANEL_HEADER); exchange.setPanelHeaderName(panelHeaderName); if ((exchange.getRate() * 10) % 10 != 0) { exchange.setFormattedRate(dfReal.format(exchange.getRate())); } else { exchange.setFormattedRate(dfInt.format(exchange.getRate())); } } mav.addObject(SEARCH_RESULTS, res); } catch (BusinessException be) { logger.error(be.getMessage(), be); mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES); errorMessages.add( messageSource.getMessage( SEARCH_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } catch (Exception e) { logger.error("", e); mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES); errorMessages.add( messageSource.getMessage( SEARCH_EXCEPTION_ERROR, new Object[] {ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } // find the number of pages shown in pagination area ControllerUtils.getInstance().findPagesLimit(searchExchangeBean, PAGES); mav.addObject(SEARCH_EXCHANGE_BEAN, searchExchangeBean); mav.addObject(COMMAND, command); logger.debug("handleSearch - END - res.size=".concat(String.valueOf(res.size()))); return mav; }
/** * Handles the results pagination * * @author Coni * @param request * @param command * @return * @throws BusinessException */ private ModelAndView handlePagination( HttpServletRequest request, ArrayList<String> errorMessages, Object command) throws BusinessException { logger.debug("handlePagination - START"); ModelAndView mav = new ModelAndView(getSuccessView()); SearchExchangeBean searchExchangeBean = (SearchExchangeBean) command; UserAuth userAuth = (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); try { if (request.getParameter(PAGE) != null) { if (NEXT.equals(request.getParameter(PAGE))) { searchExchangeBean.setCurrentPage(searchExchangeBean.getCurrentPage() + 1); } if (PREV.equals(request.getParameter(PAGE))) { searchExchangeBean.setCurrentPage(searchExchangeBean.getCurrentPage() - 1); } if (FIRST.equals(request.getParameter(PAGE))) { searchExchangeBean.setCurrentPage(1); } if (LAST.equals(request.getParameter(PAGE))) { searchExchangeBean.setCurrentPage(searchExchangeBean.getNbrOfPages()); } if (NUMBER.equals(request.getParameter(PAGE))) { if (request.getParameter(PAGE_NBR) != null && !"".equals(request.getParameter(PAGE_NBR))) { searchExchangeBean.setCurrentPage(Integer.parseInt(request.getParameter(PAGE_NBR))); } else { // something is wrong // I will show the first page searchExchangeBean.setCurrentPage(-1); } } } } catch (Exception e) { // something is wrong // I will show the first page logger.error(PAGINATION_ERROR, e); searchExchangeBean.setCurrentPage(-1); } List<Exchange> res = null; try { res = BLExchange.getInstance().getResultsForSearch(searchExchangeBean, false); DecimalFormat dfReal = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); dfReal.applyPattern("# ### ### ##0.0000"); DecimalFormat dfInt = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); dfInt.applyPattern("# ### ### ###"); // set the exchange info panel header name for (Exchange exchange : res) { String headerName = exchange .getFirstCurrency() .getInitials() .concat(" - ") .concat(exchange.getSecondCurrency().getInitials()); String panelHeaderName = ControllerUtils.getInstance().truncateName(headerName, NR_CHARS_PANEL_HEADER); exchange.setPanelHeaderName(panelHeaderName); if ((exchange.getRate() * 10) % 10 != 0) { exchange.setFormattedRate(dfReal.format(exchange.getRate())); } else { exchange.setFormattedRate(dfInt.format(exchange.getRate())); } } mav.addObject(SEARCH_RESULTS, res); } catch (BusinessException be) { logger.error(be.getMessage(), be); mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES); errorMessages.add( messageSource.getMessage( SEARCH_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } catch (Exception e) { logger.error("", e); mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES); errorMessages.add( messageSource.getMessage( SEARCH_ERROR, new Object[] {ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } mav.addObject(SEARCH_RESULTS, res); // find the number of pages shown in pagination area ControllerUtils.getInstance().findPagesLimit(searchExchangeBean, PAGES); mav.addObject(SEARCH_EXCHANGE_BEAN, searchExchangeBean); mav.addObject(COMMAND, command); logger.debug("handlePagination - END"); return mav; }
/** * Deletes exchanges * * @author coni * @param request * @param searchExchangeBean * @throws BusinessException * @throws ClassNotFoundException * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ private void handleDeleteAllSimple( HttpServletRequest request, SearchExchangeBean searchExchangeBean, ArrayList<String> infoMessages, ArrayList<String> errorMessages) throws BusinessException, SecurityException, NoSuchMethodException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { logger.debug("handleDeleteAllSimple - START "); UserAuth userAuth = (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Exchange exchange = null; for (int i = 0; i < searchExchangeBean.getExchangeId().length; i++) { logger.debug("Delete exchange : " + searchExchangeBean.getExchangeId()[i]); boolean isDeleted = true; try { exchange = BLExchange.getInstance().delete(searchExchangeBean.getExchangeId()[i]); } catch (BusinessException be) { logger.error("", be); errorMessages.add( messageSource.getMessage( DELETE_ERROR, new Object[] { be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime() }, RequestContextUtils.getLocale(request))); isDeleted = false; } if (isDeleted) { // send notification String projectName = null; String message = null; Integer projectId = null; if (exchange != null) { if (exchange.getProjectDetail() != null) { Project project = BLProject.getInstance().get(exchange.getProjectDetail().getProjectId(), true); projectId = exchange.getProjectDetail().getProjectId(); if (project != null) { projectName = project.getName(); } message = IConstant.NOTIFICATION_MESSAGE_EXCHANGE_PROJECT_DELETE; } else { projectName = IConstant.KEY.concat(IConstant.FROM_ORGANIZATION); message = IConstant.NOTIFICATION_MESSAGE_EXCHANGE_ORG_DELETE; } } // send a notification regarding the deleting of the exchange sendNotificationExchangeDelete( projectId, exchange.getProjectDetailId(), userAuth.getOrganisationId(), message, new Object[] { exchange.getFirstCurrency().getName(), exchange.getSecondCurrency().getName(), projectName, userAuth.getFirstName().concat(" ").concat(userAuth.getLastName()) }, IConstant.NOTIFICATION_SUBJECT_EXCHANGE_DELETE, new Object[] {null}, IConstant.NOTIFICATION_SETTING_EXCHANGE_DELETE); infoMessages.add( messageSource.getMessage( DELETE_SUCCESS, new Object[] { exchange .getFirstCurrency() .getInitials() .concat(" - ") .concat(exchange.getSecondCurrency().getInitials()) }, RequestContextUtils.getLocale(request))); // add the new audit event only if the user is not AdminIT try { if (!userAuth.isAdminIT()) { if (exchange.getProjectDetailId() == null) { BLAudit.getInstance() .add( IConstant.AUDIT_EVENT_EXCHANGE_DELETE_TYPE, userAuth.getFirstName(), userAuth.getLastName(), messageSource.getMessage( IConstant.AUDIT_EVENT_EXCHANGE_FOR_ORG_DELETE_MESSAGE, new Object[] { exchange.getFirstCurrency().getName(), exchange.getSecondCurrency().getName() }, new Locale("en")), messageSource.getMessage( IConstant.AUDIT_EVENT_EXCHANGE_FOR_ORG_DELETE_MESSAGE, new Object[] { exchange.getFirstCurrency().getName(), exchange.getSecondCurrency().getName() }, new Locale("ro")), ControllerUtils.getInstance().getOrganisationIdFromSession(request), userAuth.getPersonId()); } else { Project project = BLProject.getInstance().get(exchange.getProjectId(), true); BLAudit.getInstance() .add( IConstant.AUDIT_EVENT_EXCHANGE_DELETE_TYPE, userAuth.getFirstName(), userAuth.getLastName(), messageSource.getMessage( IConstant.AUDIT_EVENT_EXCHANGE_FOR_PROJECT_DELETE_MESSAGE, new Object[] { exchange.getFirstCurrency().getName(), exchange.getSecondCurrency().getName(), project.getName() }, new Locale("en")), messageSource.getMessage( IConstant.AUDIT_EVENT_EXCHANGE_FOR_PROJECT_DELETE_MESSAGE, new Object[] { exchange.getFirstCurrency().getName(), exchange.getSecondCurrency().getName(), project.getName() }, new Locale("ro")), ControllerUtils.getInstance().getOrganisationIdFromSession(request), userAuth.getPersonId()); } } } catch (Exception exc) { logger.error("", exc); } } } logger.debug("handleDeleteAllSimple - END "); }
@Override protected ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse result) throws Exception { logger.debug("handleRequestInternal - START"); // used for info/error messages ArrayList<String> infoMessages = new ArrayList<String>(); ArrayList<String> errorMessages = new ArrayList<String>(); ModelAndView mav = new ModelAndView(); try { Integer moduleId = ServletRequestUtils.getIntParameter(request, MODULE_ID); logger.debug("Module id: ".concat(moduleId.toString())); mav.addObject(MODULE_ID, moduleId); if (moduleId != null) { logger.debug("are module id"); // get all available permissions for a module List<Permission> permissions = BLPermission.getInstance().getPermissionByModule(moduleId); mav.addObject(ALL_PERMISSIONS, permissions); Set<Permission> newPermissions = new HashSet<Permission>(); if (moduleId != -1) { Permission permission = BLPermission.getInstance().getDefaultPermissionByModule(moduleId); newPermissions.add(permission); } mav.addObject(PERMISSIONS, newPermissions); Module module = null; try { module = BLModule.getInstance().get(moduleId); } catch (BusinessException be) { logger.error("", be); errorMessages.add( messageSource.getMessage( MODULE_GET_ERROR, new Object[] { be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime() }, RequestContextUtils.getLocale(request))); } catch (Exception e) { logger.error("", e); errorMessages.add( messageSource.getMessage( GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } if (module != null) { String moduleName = module.getName(); mav.addObject(SELECTED_MODULE_NAME, moduleName); } } } catch (ServletRequestBindingException e) { logger.error("handleRequestInternal", e); errorMessages.add( messageSource.getMessage( GET_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } // Publish messages/errors setMessages(request, infoMessages); setErrors(request, errorMessages); logger.debug("handleRequestInternal - END"); return mav; }
public static String inspect(HttpServletRequest request) { TextTable sRequestAttributes = new TextTable("Special [R] Attributes#Value", TextTable.ALIGN_CENTER); TextTable ttRequestAttributes = new TextTable("Attr [R]#Value", TextTable.ALIGN_CENTER); TextTable ttRequestParameters = new TextTable("Param [R]#Value", TextTable.ALIGN_CENTER); TextTable ttSessionAttributes = new TextTable("Attr [S]#Value", TextTable.ALIGN_CENTER); StringBuffer sb = new StringBuffer(); Enumeration<String> enumElemente = null; String value = null; String valueOriginal = null; String attr = null; // AFISEAZA ATRIBUTELE SPECIALE ALE REQUESTULUI if (AFISEAZA_ATRIBUTE_SPECIALE_REQUEST) { sRequestAttributes.addRow( "LOCALE".concat("#").concat(RequestContextUtils.getLocale(request).toString()), TextTable.ALIGN_LEFT); sRequestAttributes.addRow( "URL".concat("#").concat(request.getRequestURI()), TextTable.ALIGN_LEFT); sRequestAttributes.addRow( "QS" .concat("#") .concat((request.getQueryString() != null ? request.getQueryString() : "")), TextTable.ALIGN_LEFT); sRequestAttributes.addRow( "METHOD".concat("#").concat(request.getMethod()), TextTable.ALIGN_LEFT); sb.append(sRequestAttributes.getTable()); } // AFISEAZA ATRIBUTELE REQUEST if (AFISEAZA_ATRIBUTE_REQUEST) { enumElemente = request.getAttributeNames(); while (enumElemente.hasMoreElements()) { attr = enumElemente.nextElement(); valueOriginal = request.getAttribute(attr).toString(); if (valueOriginal.length() > MAX_LENGTH) { value = valueOriginal.substring(0, MAX_LENGTH); } else { value = valueOriginal; } ttRequestAttributes.addRow(attr.concat("#").concat(value), TextTable.ALIGN_LEFT); } sb.append(ttRequestAttributes.getTable()); } // AFISEAZA PARAMETRII REQUEST if (AFISEAZA_PARAMETRII_REQUEST) { String[] valuesOriginal = null; enumElemente = request.getParameterNames(); while (enumElemente.hasMoreElements()) { attr = (String) enumElemente.nextElement(); valuesOriginal = request.getParameterValues(attr); // daca sunt mai multe cu acelasi nume if (valuesOriginal != null) { for (int i = 0; i < valuesOriginal.length; i++) { if (valuesOriginal[i].length() > MAX_LENGTH) { value = valuesOriginal[i].substring(0, MAX_LENGTH); } else { value = valuesOriginal[i]; } ttRequestParameters.addRow(attr.concat("#").concat(value), TextTable.ALIGN_LEFT); } } else { valueOriginal = request.getParameter(attr).toString(); if (valueOriginal.length() > MAX_LENGTH) { value = valueOriginal.substring(0, MAX_LENGTH); } else { value = valueOriginal; } ttRequestParameters.addRow(attr.concat("#").concat(value), TextTable.ALIGN_LEFT); } } sb.append(ttRequestParameters.getTable()); } // AFISEAZA ATRIBUTELE SESIUNII if (AFISEAZA_ATRIBUTE_SESIUNE) { HttpSession ses = request.getSession(); enumElemente = ses.getAttributeNames(); while (enumElemente.hasMoreElements()) { attr = (String) enumElemente.nextElement(); valueOriginal = request.getSession().getAttribute(attr).toString(); if (valueOriginal.length() > MAX_LENGTH) { value = valueOriginal.substring(0, MAX_LENGTH); } else { value = valueOriginal; } ttSessionAttributes.addRow(attr.concat("#").concat(value), TextTable.ALIGN_LEFT); } ttSessionAttributes.addRow( "SESSION ID ".concat("#").concat(request.getSession().getId()), TextTable.ALIGN_LEFT); sb.append(ttSessionAttributes.getTable()); } return sb.toString(); }
@Override protected Map referenceData(HttpServletRequest request, Object command, Errors errors) { logger.debug("referenceData - START"); Map map = new HashMap(); ArrayList<String> errorMessages = new ArrayList<String>(); UserAuth userAuth = (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); try { // adding to model the results per page for search results map.put( IConstant.NOM_RESULTS_PER_PAGE, TSContext.getFromContext(IConstant.NOM_RESULTS_PER_PAGE)); } catch (Exception e) { logger.error("referenceData", e); errorMessages.add( messageSource.getMessage( GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } try { // add the organization available currencies List<Currency> currencies = BLCurrency.getInstance().getByOrganizationId(userAuth.getOrganisationId()); if (currencies != null) { List<IntString> nomCurrencies = new ArrayList<IntString>(); for (Currency currency : currencies) { IntString entry = new IntString(); entry.setValue(currency.getCurrencyId()); entry.setLabel(currency.getName()); nomCurrencies.add(entry); } map.put(ORG_CURRENCIES, nomCurrencies); } } catch (BusinessException bexc) { logger.error(bexc.getMessage(), bexc); errorMessages.add( messageSource.getMessage( GET_ORG_CURRENCIES_ERROR, new Object[] { bexc.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime() }, RequestContextUtils.getLocale(request))); } try { // adding the user's available project for search; // if the user has the USER_ALL role, all its organization's projects will be available List<Project> projects = null; if (userAuth.hasAuthority(PermissionConstant.getInstance().getTS_ExchangeSearchAll())) { projects = BLProject.getInstance().getAllProjects(userAuth.getOrganisationId(), true); } else { projects = BLProject.getInstance().getProjectsByManager(userAuth.getPersonId(), true, true); } map.put(USER_PROJECTS, projects); if (projects != null && projects.size() > 0) { map.put(IS_PM_FOR_AT_LEAST_ONE_PROJECT, new Boolean(true)); } else { map.put(IS_PM_FOR_AT_LEAST_ONE_PROJECT, new Boolean(false)); } } catch (BusinessException be) { logger.error(be.getMessage(), be); errorMessages.add( messageSource.getMessage( GET_USER_PROJECTS_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils.getLocale(request))); } setErrors(request, errorMessages); logger.debug("referenceData - END"); return map; }
@RequestMapping(method = RequestMethod.GET) public ModelAndView MessageRenderController(HttpServletRequest request) { Locale locale = RequestContextUtils.getLocale(request); ResourceBundle resourceBundle = ResourceBundle.getBundle("messages", locale); return new ModelAndView(ModuleWebConstants.MESSAGE_PAGE, "keys", resourceBundle.getKeys()); }