List of usage examples for javax.servlet.http HttpServletRequest getLocale
public Locale getLocale();
Locale
that the client will accept content in, based on the Accept-Language header. From source file:alpha.portal.webapp.controller.PasswordHintController.java
/** * Handle request.//from w ww . j a va 2s . co m * * @param request * the request * @return the model and view * @throws Exception * the exception */ @RequestMapping(method = RequestMethod.GET) public ModelAndView handleRequest(final HttpServletRequest request) throws Exception { this.log.debug("entering 'handleRequest' method..."); final String username = request.getParameter("username"); final MessageSourceAccessor text = new MessageSourceAccessor(this.messageSource, request.getLocale()); // ensure that the username has been sent if (username == null) { this.log.warn("Username not specified, notifying user that it's a required field."); request.setAttribute("error", text.getMessage("errors.required", text.getMessage("user.username"))); return new ModelAndView("login"); } this.log.debug("Processing Password Hint..."); // look up the user's information try { final User user = this.userManager.getUserByUsername(username); final StringBuffer msg = new StringBuffer(); msg.append("Your password hint is: ").append(user.getPasswordHint()); msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(request)); this.message.setTo(user.getEmail()); final String subject = '[' + text.getMessage("webapp.name") + "] " + text.getMessage("user.passwordHint"); this.message.setSubject(subject); this.message.setText(msg.toString()); this.mailEngine.send(this.message); this.saveMessage(request, text.getMessage("login.passwordHint.sent", new Object[] { username, user.getEmail() })); } catch (final UsernameNotFoundException e) { this.log.warn(e.getMessage()); this.saveError(request, text.getMessage("login.passwordHint.error", new Object[] { username })); } catch (final MailException me) { this.log.warn(me.getMessage()); this.saveError(request, me.getCause().getLocalizedMessage()); } return new ModelAndView(new RedirectView(request.getContextPath())); }
From source file:fr.paris.lutece.plugins.extend.modules.feedback.web.component.FeedbackResourceExtenderComponent.java
/** * {@inheritDoc}//from w ww.ja v a2 s.com */ @Override public void doSaveConfig(HttpServletRequest request, IExtenderConfig config) throws ExtendErrorException { FeedbackExtenderConfig feedbackConfig = (FeedbackExtenderConfig) config; if (feedbackConfig.getIdMailingList() == -1) { throw new ExtendErrorException( I18nService.getLocalizedString(Messages.MANDATORY_FIELDS, request.getLocale())); } _configService.update(config); }
From source file:eu.eidas.node.service.ServiceExceptionHandlerServlet.java
private void prepareErrorMessage(AbstractEIDASException exception, HttpServletRequest request) { if (exception.getMessage() == null) { LOG.info("BUSINESS EXCEPTION : An error occurred on EidasNode! Couldn't get Exception message."); } else {// ww w . ja v a 2 s . c o m String errorMessage = EidasNodeErrorUtil.resolveMessage(exception.getErrorMessage(), exception.getErrorCode(), request.getLocale()); if (errorMessage != null) { exception.setErrorMessage(errorMessage); } if (StringUtils.isBlank(exception.getSamlTokenFail())) { EidasNodeErrorUtil.prepareSamlResponseFail(request, exception, EidasNodeErrorUtil.ErrorSource.PROXYSERVICE); LOG.info("BUSINESS EXCEPTION : ", errorMessage); } else { LOG.info("BUSINESS EXCEPTION : ", exception.getMessage()); } } }
From source file:org.wallride.web.support.BlogLanguageLocaleResolver.java
@Override public Locale resolveLocale(HttpServletRequest request) { BlogLanguage blogLanguage = (BlogLanguage) request .getAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE); if (blogLanguage == null) { Blog blog = blogService.getBlogById(Blog.DEFAULT_ID); blogLanguage = blog.getLanguage(blog.getDefaultLanguage()); }//from ww w. ja va2 s . c o m return (blogLanguage != null) ? Locale.forLanguageTag(blogLanguage.getLanguage()) : request.getLocale(); }
From source file:it.cilea.osd.jdyna.controller.TypedFormBoxController.java
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { H object = (H) command;// w ww. ja va 2 s. c o m String tabId = request.getParameter("tabId"); applicationService.saveOrUpdate(getBoxClass(), object); saveMessage(request, getText("action.box.edited", new Object[] { object.getShortName() }, request.getLocale())); String shortName = Utils.getAdminSpecificPath(request, null); return new ModelAndView(getSuccessView() + "?path=" + shortName + "&id=" + object.getId()); }
From source file:net.sf.appstatus.web.pages.StatusPage.java
public void doGetJSON(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException, IOException { setup(resp, "application/json"); ServletOutputStream os = resp.getOutputStream(); int statusCode = 200; List<ICheckResult> results = webHandler.getAppStatus().checkAll(req.getLocale()); for (ICheckResult r : results) { if (r.isFatal()) { resp.setStatus(500);/*from w w w . ja v a 2 s . c o m*/ statusCode = 500; break; } } os.write("{".getBytes(ENCODING)); os.write(("\"code\" : " + statusCode + ",").getBytes(ENCODING)); os.write(("\"status\" : {").getBytes(ENCODING)); boolean first = true; for (ICheckResult r : results) { if (!first) { os.write((",").getBytes(ENCODING)); } os.write(("\"" + r.getProbeName() + "\" : " + r.getCode()).getBytes(ENCODING)); if (first) { first = false; } } os.write("}".getBytes(ENCODING)); os.write("}".getBytes(ENCODING)); }
From source file:net.paoding.rose.web.instruction.ViewInstruction.java
@Override public void doRender(Invocation inv) throws Exception { String name = resolvePlaceHolder(this.name, inv); ViewDispatcher viewResolver = getViewDispatcher(inv); String viewPath = getViewPath((InvocationBean) inv, name); if (viewPath != null) { HttpServletRequest request = inv.getRequest(); HttpServletResponse response = inv.getResponse(); ///*from w ww .j a v a 2s. c om*/ View view = viewResolver.resolveViewName(inv, viewPath, request.getLocale()); if (!Thread.interrupted()) { inv.addModel(ROSE_INVOCATION, inv); view.render(inv.getModel().getAttributes(), request, response); } else { logger.info("interrupted"); } } }
From source file:com.aurel.track.user.LogoffAction.java
/** * This method is automatically called if the associated action is * triggered./*from ww w. java 2 s .c o m*/ */ private String execute2(boolean checkForMobile) throws Exception { Boolean ready = (Boolean) ServletActionContext.getServletContext().getAttribute(ApplicationStarter.READY); if (ready == null || ready.booleanValue() == false) { return "loading"; } TPersonBean user = null; if (session != null) { user = (TPersonBean) session.get(Constants.USER_KEY); } HttpServletRequest request = ServletActionContext.getRequest(); HttpSession httpSession = request.getSession(); Locale locale = request.getLocale(); if (locale == null) { locale = Locale.getDefault(); } if (user != null) { locale = user.getLocale(); } // Process this users logoff LogoffBL.doLogoff(session, httpSession, locale); StringBuilder sb = LogoffBL.createInitData(httpSession, checkForMobile, request, isMobileApplication, mobileApplicationVersionNo, locale); initData = sb.toString(); if (ApplicationBean.getInstance().getInstallProblem() != null) { String extJSLocale = LocaleHandler.getExistingExtJSLocale(locale); httpSession.setAttribute("EXTJSLOCALE", extJSLocale); List<String> errors = ApplicationBean.getInstance().getInstallProblem(); setActionErrors(errors); return ERROR; } BanProcessor bp = BanProcessor.getBanProcessor(); if (bp.isBanned(request.getRemoteAddr())) { clearFieldErrors(); accessLogger.info("LOGON: Access attempt from banned IP " + request.getRemoteAddr() + " at " + new Date().toString()); return "banned"; } if (isMobileApplication) { if (logOutMobile) { StringBuilder sbMobile = new StringBuilder(); sbMobile.append("{"); JSONUtility.appendBooleanValue(sbMobile, "success", true, true); sbMobile.append("}"); JSONUtility.encodeJSON(ServletActionContext.getResponse(), sbMobile.toString()); } else { ServletActionContext.getResponse().addHeader("Access-Control-Allow-Origin", "*"); JSONUtility.encodeJSON(ServletActionContext.getResponse(), sb.toString()); } return null; } if (mayBeMobile) { return "successMobile"; } return SUCCESS; }
From source file:com.google.code.jcaptcha4struts2.core.actions.JCaptchaImageAction.java
/** * Action execution logic, which generates the Captcha Image Stream and sets the JPEG encoded * byte stream to captchaImage field./* ww w . j a va 2 s .c om*/ * <p> * Subsequent to invocation of this method, the generated captcha is available through * {@link #getCaptchaImage()} method. * * @return action forward string * * @throws Exception */ public String execute() { ByteArrayOutputStream imageOut = new ByteArrayOutputStream(); HttpServletRequest request = ServletActionContext.getRequest(); // Captcha Id is the session ID String captchaId = request.getSession().getId(); if (LOG.isDebugEnabled()) { LOG.debug("Generating Captcha Image for SessionID : " + captchaId); } // Generate Captcha Image BufferedImage image = getImageCaptchaService().getImageChallengeForID(captchaId, request.getLocale()); // Encode to JPEG Stream try { ImageIO.write(image, IMAGE_FORMAT, imageOut); } catch (IOException e) { LOG.error("Unable to JPEG encode the Captcha Image due to IOException", e); throw new IllegalArgumentException("Unable to JPEG encode the Captcha Image", e); } // Get byte[] for image captchaImage = imageOut.toByteArray(); return SUCCESS; }
From source file:io.adeptj.runtime.servlet.ToolsServlet.java
/** * Renders tools page.//from w ww . j a v a 2 s. c o m */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { Bundle[] bundles = BundleContextHolder.getInstance().getBundleContext().getBundles(); long startTime = ManagementFactory.getRuntimeMXBean().getStartTime(); MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); TemplateEngines.getDefault().render(TemplateContext.builder().request(req).response(resp) .template(TOOLS_TEMPLATE).locale(req.getLocale()) .contextObject(ContextObject.newContextObject().put("username", req.getRemoteUser()) .put("sysProps", System.getProperties().entrySet()).put("totalBundles", bundles.length) .put("bundles", bundles) .put("runtime", JAVA_RUNTIME_NAME + "(build " + JAVA_RUNTIME_VERSION + ")") .put("jvm", JAVA_VM_NAME + "(build " + JAVA_VM_VERSION + ", " + JAVA_VM_INFO + ")") .put("startTime", Date.from(Instant.ofEpochMilli(startTime))) .put("upTime", Times.format(startTime)) .put("maxMemory", FileUtils.byteCountToDisplaySize(memoryMXBean.getHeapMemoryUsage().getMax())) .put("usedMemory", FileUtils.byteCountToDisplaySize(memoryMXBean.getHeapMemoryUsage().getUsed())) .put("processors", Runtime.getRuntime().availableProcessors())) .build()); }