Example usage for javax.servlet.http HttpServletRequest getLocale

List of usage examples for javax.servlet.http HttpServletRequest getLocale

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getLocale.

Prototype

public Locale getLocale();

Source Link

Document

Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.

Usage

From source file:org.frat.common.exception.ExceptionResolver.java

@Override
public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final Exception ex) {
    if (WebUtil.isAjaxRequest(request)) {
        try {/*w ww .  ja  v a2s.  c om*/
            String formId = request.getHeader(ApplicationConstant.X_FORM_ID);
            Locale locale = request.getLocale();
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json;charset=UTF-8");
            ResultDto error = getErrorDto(ex, handler, formId, locale);
            if (error.isNonBizError()) {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            } else {
                response.setStatus(HttpStatus.OK.value());
            }
            PrintWriter writer = response.getWriter();
            objectMapper.writeValue(response.getWriter(), error);
            writer.flush();
        } catch (IOException ie) {
            LOGGER.error("Failed to serialize the object to json for exception handling.", ie);
        }
        return new ModelAndView();
    } else {
        response.setContentType("text/html;charset=UTF-8");
        ModelAndView mav = new ModelAndView();
        mav.addObject("errorMessage", ExceptionUtils.getStackTrace(ex));
        if (ex instanceof AuthorizationException) {
            LOGGER.warn("AuthorizationException handled (non-ajax style):", ex);
            mav.setViewName("error/access_denied");
        } else {
            LOGGER.error("Unknown exception handled (non-ajax style):", ex);
            mav.setViewName("error/404");
        }
        return mav;
    }
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.SignupController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(User user, BindingResult errors, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (request.getParameter("cancel") != null) {
        return getCancelView();
    }/*  w  w  w  .  j  a v a2s. c  om*/

    if (log.isDebugEnabled()) {
        log.debug("entering 'onSubmit' method...");
    }
    Locale locale = request.getLocale();

    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    try {
        this.getUserManager().saveUser(user);
    } catch (AccessDeniedException ade) {
        // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
        log.warn(ade.getMessage());
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    } catch (UserExistsException e) {
        errors.rejectValue("username", "errors.existing.user",
                new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

        // redisplay the unencrypted passwords
        user.setPassword(user.getConfirmPassword());
        return "signup";
    }

    saveMessage(request, getText("user.registered", user.getUsername(), locale));
    request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getConfirmPassword(), user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send user an e-mail
    if (log.isDebugEnabled()) {
        log.debug("Sending user '" + user.getUsername() + "' an account information e-mail");
    }

    // Send an account information e-mail
    message.setSubject(getText("signup.email.subject", locale));

    try {
        sendUserMessage(user, getText("signup.email.message", locale), RequestUtil.getAppURL(request));
    } catch (MailException me) {
        saveError(request, me.getMostSpecificCause().getMessage());
    }

    return getSuccessView();
}

From source file:it.cilea.osd.jdyna.controller.ATabsController.java

protected ModelAndView handleDelete(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    String tabId = request.getParameter("id");
    Integer paramTypeTabId = Integer.valueOf(tabId);
    try {//from   ww  w  .jav  a  2 s . com
        applicationService.delete(tabsClass, paramTypeTabId);
        saveMessage(request, getText("action.tab.deleted", request.getLocale()));
    } catch (Exception e) {
        saveMessage(request, getText("action.tab.deleted.noSuccess", request.getLocale()));
    }
    return new ModelAndView(getListView() + "?path=" + Utils.getAdminSpecificPath(request, null), model);
}

From source file:cn.powerdash.libsystem.common.exception.ExceptionResolver.java

@Override
public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final Exception ex) {
    if (WebUtil.isAjaxRequest(request)) {
        try {/*from  www .  j  a v  a  2s. co m*/
            String formId = request.getHeader(ApplicationConstant.X_FORM_ID);
            Locale locale = request.getLocale();
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json;charset=UTF-8");
            ResultDto<?> error = getErrorDto(ex, handler, formId, locale);
            if (error.isNonBizError()) {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            } else {
                response.setStatus(HttpStatus.OK.value());
            }
            PrintWriter writer = response.getWriter();
            objectMapper.writeValue(response.getWriter(), error);
            writer.flush();
        } catch (IOException ie) {
            LOGGER.error("Failed to serialize the object to json for exception handling.", ie);
        }
        return new ModelAndView();
    } else {
        response.setContentType("text/html;charset=UTF-8");
        ModelAndView mav = new ModelAndView();
        mav.addObject("errorMessage", ExceptionUtils.getStackTrace(ex));
        if (ex instanceof AuthorizationException) {
            LOGGER.warn("AuthorizationException handled (non-ajax style):", ex);
            mav.setViewName("error/access_denied");
        } else {
            LOGGER.error("Unknown exception handled (non-ajax style):", ex);
            mav.setViewName("error/404");
        }
        return mav;
    }
}

From source file:com.jaspersoft.jasperserver.war.control.SchedulerController.java

public ModelAndView main(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("modules/reportScheduling/main");
    mav.addObject("timezone", TimeZoneContextHolder.getTimeZone().getID());
    mav.addObject("isPro", isProVersion());
    mav.addObject("userTimezones", timezones.getTimeZones(request.getLocale()));

    mav.addObject("enableSaveToHostFS", getEnableSaveToHostFS());
    mav.addObject("enableDataSnapshot", getEnableDataSnapshot());

    return mav;/*from  w  w  w .  j a v a  2  s.  co m*/
}

From source file:com.hrhih.dispatcher.HrhihJakartaMultiPartRequest.java

protected void setLocale(HttpServletRequest request) {
    if (defaultLocale == null) {
        defaultLocale = request.getLocale();
    }
}

From source file:net.sf.appstatus.web.pages.RadiatorPage.java

public void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp)
        throws UnsupportedEncodingException, IOException {

    // Setup response
    resp.setContentType("text/html");
    resp.setCharacterEncoding("UTF-8");

    // Get Health checks
    List<ICheckResult> results = webHandler.getAppStatus().checkAll(req.getLocale());
    int status = STATUS_OK;
    for (ICheckResult r : results) {

        if (r.getCode() != ICheckResult.OK && !r.isFatal() && status == STATUS_OK) {
            status = STATUS_WARN;/*from w ww. j  a  v  a 2s .  c  om*/
        }

        if (r.getCode() != ICheckResult.OK && r.isFatal()) {
            status = STATUS_ERROR;
            break;
        }
    }

    String btnClass = "btn-success";
    if (status == STATUS_WARN) {
        btnClass = "btn-warning";
    }

    if (status == STATUS_ERROR) {
        btnClass = "btn-danger";
    }

    // Get batchs status.
    IBatchManager manager = webHandler.getAppStatus().getBatchManager();

    String batchStatus = " progress-success ";
    String active = StringUtils.EMPTY;
    int width = 0;

    if (manager != null) {
        batchStatus = manager.getErrorBatches().size() > 0 ? " progress-danger " : " progress-success ";
        active = manager.getRunningBatches().size() > 0 ? " progress-striped active " : "";
        width = manager.getRunningBatches().size() + manager.getFinishedBatches().size() > 0 ? 100 : 0;
    }

    Writer w = resp.getWriter();
    w.append("<html>");
    w.append("<head>");
    w.append("<meta http-equiv=\"refresh\" content=\"60;\">");
    w.append("<link href=\"?resource=appstatus.css\" rel=\"stylesheet\">");
    w.append("</head>");
    w.append("<body style=\"background: #000; text-align: center; padding-top: 5%;\">");
    w.append("<p style=\"color: #fff; font-size: 200%;\" >" + webHandler.getApplicationName() + "</p>");
    w.append("<p style=\" padding-top: 10%;\"><a href=\"?p=status\" target=\"_blank\" class=\"btn btn-large "
            + btnClass + "\" >Status</a></p>");
    w.append("<div class=\"progress " + batchStatus + active
            + "\" style=\"margin-top: 5%; width: 90%; margin-left: 5%; margin-right: 5%;\">  <div class=\"bar\" style=\"width: "
            + width + "%;\"></div></div>");
    w.append("</body></html>");
}

From source file:fr.paris.lutece.plugins.directory.web.DoRemoveAsynchronousFile.java

/**
 * Removes the uploaded fileItem. <br />
 * This method is called by the JSP//from   w ww  .ja v a  2s . c  o  m
 * <b>jsp/site/plugins/directory/DoRemoveFile.jsp</b>
 * because this method is also used in front office in other module
 * (module-workflow-editrecord).
 * @param request the request
 * @return JSON
 * @category CALLED_BY_JS (directoryupload.js)
 */
public String doRemoveAsynchronousUploadedFile(HttpServletRequest request) {
    String strSessionId = request.getSession().getId();
    String strIdEntry = request.getParameter(PARAMETER_ID_ENTRY);
    String strFieldIndex = request.getParameter(PARAMETER_FIELD_INDEX);
    String strErrorMessage = I18nService.getLocalizedString(PROPERTY_MESSAGE_ERROR_REMOVING_FILE,
            request.getLocale());

    if (StringUtils.isBlank(strIdEntry) || StringUtils.isBlank(strFieldIndex)) {
        return JSONUtils.buildJsonError(strErrorMessage).toString();
    }

    // parse json
    JSON jsonFieldIndexes = JSONSerializer.toJSON(strFieldIndex);

    if (!jsonFieldIndexes.isArray()) {
        return JSONUtils.buildJsonError(strErrorMessage).toString();
    }

    JSONArray jsonArrayFieldIndexers = (JSONArray) jsonFieldIndexes;
    int[] tabFieldIndex = new int[jsonArrayFieldIndexers.size()];

    for (int nIndex = 0; nIndex < jsonArrayFieldIndexers.size(); nIndex++) {
        try {
            tabFieldIndex[nIndex] = Integer.parseInt(jsonArrayFieldIndexers.getString(nIndex));
        } catch (NumberFormatException nfe) {
            return JSONUtils.buildJsonError(strErrorMessage).toString();
        }
    }

    // inverse order (removing using index - remove greater first to keep order)
    Arrays.sort(tabFieldIndex);
    ArrayUtils.reverse(tabFieldIndex);

    for (int nFieldIndex : tabFieldIndex) {
        DirectoryAsynchronousUploadHandler.getHandler().removeFileItem(strIdEntry, strSessionId, nFieldIndex);
    }

    return JSONUtils.buildJsonSuccess(strIdEntry, strSessionId).toString();
}

From source file:org.bpmscript.web.TemplateController.java

/**
 * Gets the sitemesh HTMLPage and passes that information to the right view
 * along with the following parameters:/*from  w ww .  j  a v  a 2s. c  o  m*/
 * 
 * <ul>
 * <li>base - the context path</li>
 * <li>locale - the locale for the page</li>
 * <li>req - the http request</li>
 * <li>res - the http response</li>
 * </ul>
 */
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    HTMLPage htmlPage = (HTMLPage) request.getAttribute(RequestConstants.PAGE);

    Map<String, Object> context = new HashMap<String, Object>(templateModel);

    context.put("base", request.getContextPath());
    context.put("locale", request.getLocale());

    // For backwards compatability with apps that used the old VelocityDecoratorServlet
    // that extended VelocityServlet instead of VelocityViewServlet
    context.put("req", request);
    context.put("res", response);

    if (htmlPage == null) {
        context.put("title", "Title?");
        context.put("body", "<p>Body?</p>");
        context.put("head", "<!-- head -->");
    } else {
        context.put("title", OutputConverter.convert(htmlPage.getTitle()));
        {
            StringWriter buffer = new StringWriter();
            htmlPage.writeBody(OutputConverter.getWriter(buffer));
            context.put("body", buffer.toString());
        }
        {
            StringWriter buffer = new StringWriter();
            htmlPage.writeHead(OutputConverter.getWriter(buffer));
            context.put("head", buffer.toString());
        }
        context.put("page", htmlPage);
        Factory factory = Factory.getInstance(new Config(new ServletConfig() {
            public ServletContext getServletContext() {
                return TemplateController.this.getServletContext();
            }

            public String getInitParameter(String name) {
                return null;
            }

            public String getServletName() {
                return null;
            }

            public Enumeration<?> getInitParameterNames() {
                return null;
            }
        }));
        Decorator decorator = factory.getDecoratorMapper().getDecorator(request, htmlPage);
        context.put("decorator", decorator);
    }
    return new ModelAndView(getViewName(), context);
}

From source file:cn.vlabs.duckling.vwb.ui.servlet.AbstractLoginServlet.java

private void redirectToUmt(HttpServletRequest request, HttpServletResponse response, String viewUrl)
        throws IOException, ServletException {
    Oauth oauth = new Oauth(properties);
    int siteId = getVwbcontext(request).getSiteId();
    VWBContainer container = VWBContainerImpl.findContainer();
    Locale locale = request.getLocale();
    String language = locale.getLanguage() + "_" + locale.getCountry();
    if (!locale.equals(Locale.CHINA)) {
        language = Locale.US.getLanguage() + "_" + Locale.US.getCountry();
    }//from  w  w w  .j ava 2s .  com
    if (StringUtils.isEmpty(language)) {
        language = container.getSiteConfig().getProperty(siteId, KeyConstants.SITE_LANGUAGE);
    }

    try {
        String redirectUrl = oauth.getAuthorizeURL(request) + "&state=" + URLEncoder.encode(viewUrl, "UTF-8")
                + "&locale=" + language;
        response.sendRedirect(redirectUrl);
    } catch (UMTOauthConnectException e) {
        throw new ServletException(e);
    }
}