// SEC-3013
  @Test
  public void germanSystemLocaleWithEnglishLocaleContextHolder() {
    Locale beforeSystem = Locale.getDefault();
    Locale.setDefault(Locale.GERMAN);

    Locale beforeHolder = LocaleContextHolder.getLocale();
    LocaleContextHolder.setLocale(Locale.US);

    MessageSourceAccessor msgs = SpringSecurityMessageSource.getAccessor();
    assertThat("Access is denied")
        .isEqualTo(msgs.getMessage("AbstractAccessDecisionManager.accessDenied", "Ooops"));

    // Revert to original Locale
    Locale.setDefault(beforeSystem);
    LocaleContextHolder.setLocale(beforeHolder);
  }
 protected void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   final Locale locale = localeResolver.resolveLocale(request);
   LocaleContextHolder.setLocale(locale);
   ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
   RequestContextHolder.setRequestAttributes(requestAttributes);
   try {
     super.service(
         new HttpServletRequestWrapper(request) {
           @Override
           public Locale getLocale() {
             return locale;
           }
         },
         response);
   } finally {
     if (!locale.equals(LocaleContextHolder.getLocale())) {
       if (logger.isDebugEnabled()) {
         logger.debug("locale changed, updating locale resolver");
       }
       localeResolver.setLocale(request, response, LocaleContextHolder.getLocale());
     }
     LocaleContextHolder.resetLocaleContext();
     RequestContextHolder.resetRequestAttributes();
   }
 }
 private void initContextHolders(
     HttpServletRequest request, ServletRequestAttributes requestAttributes) {
   LocaleContextHolder.setLocale(request.getLocale(), this.threadContextInheritable);
   RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
   if (logger.isDebugEnabled()) {
     logger.debug("Bound request context to thread: " + request);
   }
 }
 @Test
 public void localeViewResolution() throws Exception {
   LocaleContextHolder.setLocale(Locale.FRENCH);
   registerAndRefreshContext();
   MockHttpServletResponse response = render("includes", Locale.FRENCH);
   String result = response.getContentAsString();
   assertThat(result, containsString("voila"));
   assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8"));
 }
  @Test
  public void testReplacableLookup() {
    // Change Locale to English
    Locale before = LocaleContextHolder.getLocale();
    LocaleContextHolder.setLocale(Locale.FRENCH);

    // Cause a message to be generated
    MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
    assertThat("Le jeton nonce est compromis FOOBAR")
        .isEqualTo(
            messages.getMessage(
                "DigestAuthenticationFilter.nonceCompromised",
                new Object[] {"FOOBAR"},
                "ERROR - FAILED TO LOOKUP"));

    // Revert to original Locale
    LocaleContextHolder.setLocale(before);
  }
Esempio n. 6
0
 /**
  * Set the locale of the current request (if there is one) into Spring's LocaleContextHolder.
  *
  * @param code The code to execute while the locale is set
  * @return the result of the code block
  */
 private static <T> T withRequestLocale(Supplier<T> code) {
   try {
     LocaleContextHolder.setLocale(Http.Context.current().lang().toLocale());
   } catch (Exception e) {
     // Just continue (Maybe there is no context or some internal error in LocaleContextHolder).
     // System default locale will be used.
   }
   try {
     return code.get();
   } finally {
     LocaleContextHolder.resetLocaleContext(); // Clean up ThreadLocal
   }
 }
  private void setUp(DateTimeFormatterRegistrar registrar) {
    conversionService = new FormattingConversionService();
    DefaultConversionService.addDefaultConverters(conversionService);
    registrar.registerFormatters(conversionService);

    DateTimeBean bean = new DateTimeBean();
    bean.getChildren().add(new DateTimeBean());
    binder = new DataBinder(bean);
    binder.setConversionService(conversionService);

    LocaleContextHolder.setLocale(Locale.US);
    DateTimeContext context = new DateTimeContext();
    context.setTimeZone(ZoneId.of("-05:00"));
    DateTimeContextHolder.setDateTimeContext(context);
  }
  @Test
  public void shouldNotValidateWhenFirstNameEmpty() {

    LocaleContextHolder.setLocale(Locale.ENGLISH);
    Person person = new Person();
    person.setFirstName("");
    person.setLastName("smith");

    Validator validator = createValidator();
    Set<ConstraintViolation<Person>> constraintViolations = validator.validate(person);

    Assert.assertEquals(1, constraintViolations.size());
    ConstraintViolation<Person> violation = constraintViolations.iterator().next();
    assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName");
    assertThat(violation.getMessage()).isEqualTo("may not be empty");
  }
Esempio n. 9
0
  /**
   * This method looks for a "locale" request parameter. If it finds one, it sets it as the
   * preferred locale and also configures it to work with JSTL.
   *
   * @param request the current request
   * @param response the current response
   * @param chain the chain
   * @throws IOException when something goes wrong
   * @throws ServletException when a communication failure happens
   */
  @SuppressWarnings("unchecked")
  public void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    String locale = request.getParameter("locale");
    Locale preferredLocale = null;

    if (locale != null) {
      int indexOfUnderscore = locale.indexOf('_');
      if (indexOfUnderscore != -1) {
        String language = locale.substring(0, indexOfUnderscore);
        String country = locale.substring(indexOfUnderscore + 1);
        preferredLocale = new Locale(language, country);
      } else {
        preferredLocale = new Locale(locale);
      }
    }

    HttpSession session = request.getSession(false);

    if (session != null) {
      if (preferredLocale == null) {
        preferredLocale = (Locale) session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
      } else {
        session.setAttribute(Constants.PREFERRED_LOCALE_KEY, preferredLocale);
        Config.set(session, Config.FMT_LOCALE, preferredLocale);
      }

      if (preferredLocale != null && !(request instanceof LocaleRequestWrapper)) {
        request = new LocaleRequestWrapper(request, preferredLocale);
        LocaleContextHolder.setLocale(preferredLocale);
      }
    }

    String theme = request.getParameter("theme");
    if (theme != null && request.isUserInRole(Constants.ADMIN_ROLE)) {
      Map<String, Object> config = (Map) getServletContext().getAttribute(Constants.CONFIG);
      config.put(Constants.CSS_THEME, theme);
    }

    chain.doFilter(request, response);

    // Reset thread-bound LocaleContext.
    LocaleContextHolder.setLocaleContext(null);
  }
Esempio n. 10
0
  @Test
  public void testInternationalization() throws Exception {
    final List<Locale> locales =
        new ArrayList<Locale>() {

          private static final long serialVersionUID = 1L;

          {
            add(Locale.US);
            add(Locale.GERMANY);
            add(Locale.FRANCE);
            add(Locale.CHINA);
            add(Locale.ITALY);
          }
        };

    for (final Locale locale : locales) {
      LocaleContextHolder.setLocale(locale);
      testConvertStringToDate();
      testConvertDateToString();
      testConvertStringToTimestamp();
      testConvertTimestampToString();
    }
  }
 @After
 public void tearDown() {
   LocaleContextHolder.setLocale(null);
   DateTimeContextHolder.setDateTimeContext(null);
 }