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:DateLocaleServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    //Get the client's Locale
    Locale locale = request.getLocale();
    ResourceBundle bundle = ResourceBundle.getBundle("i18n.WelcomeBundle", locale);
    String welcome = bundle.getString("Welcome");
    String date = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT, locale).format(new Date());

    //Display the locale
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>" + welcome + "</title></head><body>");

    out.println("<h2>" + bundle.getString("Hello") + " " + bundle.getString("and") + " " + welcome + "</h2>");

    out.println(date + "<br /><br />");

    java.util.Enumeration e = bundle.getKeys();
    while (e.hasMoreElements()) {

        out.println((String) e.nextElement());
        out.println("<br /><br />");

    }/*from   ww  w  .  ja v a  2  s.com*/

    out.println("Locale: ");
    out.println(locale.getLanguage() + "_" + locale.getCountry());

    out.println("</body></html>");

}

From source file:de.eod.jliki.users.servlets.CaptchaValidator.java

/**
 * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
 * {@inheritDoc}//from   w  ww.ja  v  a2s.  c o  m
 */
@Override
public final void validate(final FacesContext context, final UIComponent component, final Object value) {
    final HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    final String sessionId = request.getSession().getId();
    final Locale sessionLocale = request.getLocale();
    final String val = StringUtils.strip((String) value);

    if (!CaptchaService.getInstance().validateResponseForID(sessionId, val)) {
        throw new ValidatorException(Messages.createFacesMessage(FacesMessage.SEVERITY_ERROR,
                "user.register.captcha.mismatch", sessionLocale));
    }
}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Get a locale from cookie, if present. The default request locale otherwise.
 *
 * @param request The request to get the locale for.
 * @return The cookie locale, if present. The default request locale otherwise.
 *//*from ww  w  .j ava 2s  .c  o m*/
public static String getLocale(HttpServletRequest request) {
    ArgumentNotValid.checkNotNull(request, "request");
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (c.getName().equals("locale")) {
                return c.getValue();
            }
        }
    }
    return request.getLocale().toString();
}

From source file:fr.paris.lutece.plugins.uploadimage.web.UploadimageApp.java

/**
 * Returns the content of the page uploadimage.
 *
 * @param request//w w w  . j ava  2s.  c  om
 *         The HTTP request
 * @return The view
 */
@View(value = VIEW_HOME, defaultView = true)
public XPage viewHome(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<>();
    return getXPage(TEMPLATE_XPAGE, request.getLocale(), model);
}

From source file:LocaleSessionServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    HttpSession userSession = request.getSession();
    if (userSession.isNew()) {
        userSession.setAttribute("userLocale", request.getLocale());
    }//from   ww w  . jav a  2s  .  c  om
}

From source file:com.commerce4j.storefront.controllers.ProfileController.java

@SuppressWarnings("unchecked")
public ModelAndView register(HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("register");

    // user localization
    java.util.Locale locale = request.getLocale();
    String iso3country = locale.getISO3Country();
    if (StringUtils.isNotEmpty(iso3country)) {
        if (logger.isDebugEnabled())
            logger.debug(iso3country);/*from  www . j  a  va 2  s . c o m*/
        mav.addObject("iso3country", iso3country);
    }

    String sql = "Select * From c4j_countries Order By country_name";
    List countries = getJdbcTemplate().queryForList(sql);
    mav.addObject("countries", countries);

    return mav;
}

From source file:LocaleInformationServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    Locale userPreferredLocale = request.getLocale();
    Enumeration userPreferredLocales = request.getLocales();

    out.println("Preferred Locale: " + userPreferredLocale.toString());
    out.println("");
    out.print("Preferred Locales: ");

    while (userPreferredLocales.hasMoreElements()) {
        userPreferredLocale = (Locale) userPreferredLocales.nextElement();
        out.print(userPreferredLocale.toString() + ", ");
    }//from  w w w.  ja  v  a2s.c  o m
    out.println();
    out.println("");
}

From source file:eu.eidas.node.utils.EidasNodeErrorUtil.java

private static void generateSamlResponse(final HttpServletRequest request, AbstractEIDASException exc,
        IEIDASSession eidasSession, String spUrl) {
    ISERVICESAMLService serviceSamlService = ApplicationContextProvider.getApplicationContext()
            .getBean(ISERVICESAMLService.class);
    if (serviceSamlService == null) {
        return;// w ww .  jav a 2 s.c  om
    }
    if (exc.getUserErrorCode() != null) {
        exc.setErrorMessage("");
    }
    String samlSubStatusCode = getSamlSubStatusCode(exc);
    String errorMessage = exc.getErrorMessage();
    if (!isErrorCodeAllowedForSamlGeneration(exc)) {
        if (exc.getUserErrorCode() != null && isErrorCodeAllowedForSamlGeneration(exc.getUserErrorCode())) {
            errorMessage = resolveMessage(exc.getUserErrorMessage(), exc.getUserErrorCode(),
                    request.getLocale());
            samlSubStatusCode = getSamlSubStatusCode(exc.getUserErrorCode());
        } else {
            return;
        }
    }

    final EIDASAuthnRequest authData = (EIDASAuthnRequest) eidasSession
            .get(EIDASParameters.AUTH_REQUEST.toString());
    if (authData == null) {
        LOG.info("ERROR : no authData found during the generation of the error message");
    }
    byte[] samlToken = serviceSamlService.generateErrorAuthenticationResponse(authData,
            getSamlStatusCode(request), samlSubStatusCode, errorMessage, request.getRemoteAddr(), true);
    exc.setSamlTokenFail(EIDASUtil.encodeSAMLToken(samlToken));
    eidasSession.put(EIDASParameters.ERROR_REDIRECT_URL.toString(), spUrl);

}

From source file:org.owasp.webgoat.service.LabelService.java

/**
 * Fetches labels for given language//from   w  ww  .j a  v  a2  s.  c o m
 * If no language is provided, the language is determined from the request headers
 * Otherwise, fall back to default language
 *
 * @param lang the language to fetch labels for (optional)
 * @return a map of labels
 * @throws Exception
 */
@GetMapping(path = URL_LABELS_MVC, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Map<String, String>> fetchLabels(
        @RequestParam(value = "lang", required = false) String lang, HttpServletRequest request) {
    Locale locale;
    if (StringUtils.isEmpty(lang)) {
        log.debug("No language provided, determining from request headers");
        locale = request.getLocale();
        if (locale != null) {
            log.debug("Locale set to {}", locale);
        }
    } else {
        locale = Locale.forLanguageTag(lang);
        log.debug("Language provided: {} leads to Locale: {}", lang, locale);
    }
    return new ResponseEntity<>(labelProvider.getLabels(locale), HttpStatus.OK);
}

From source file:com.portal.security.controller.JCaptchaController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String captchaId = request.getSession().getId();
    BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale());

    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    ImageIO.write(challenge, "jpeg", response.getOutputStream());

    /*//w  w  w. j a v a2s. c  om
     * byte[] captchaChallengeAsJpeg = null; ByteArrayOutputStream jpegOutputStream = new
     * ByteArrayOutputStream();
     * 
     * JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
     * jpegEncoder.encode(challenge);
     * 
     * captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); ServletOutputStream
     * responseOutputStream = response.getOutputStream();
     * 
     * responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush();
     * responseOutputStream.close();
     */
    return null;
}