Java Code Examples for org.springframework.context.i18n.LocaleContextHolder#setLocale()

The following examples show how to use org.springframework.context.i18n.LocaleContextHolder#setLocale() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ValidatorTests.java    From spring-init with Apache License 2.0 6 votes vote down vote up
@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);

    assertThat(constraintViolations.size()).isEqualTo(1);
    ConstraintViolation<Person> violation = constraintViolations.iterator().next();
    assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName");
    assertThat(violation.getMessage()).isEqualTo("must not be empty");
}
 
Example 2
Source File: FormattingConversionServiceFactoryBeanTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testDefaultFormattersOn() throws Exception {
	FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean();
	factory.afterPropertiesSet();
	FormattingConversionService fcs = factory.getObject();
	TypeDescriptor descriptor = new TypeDescriptor(TestBean.class.getDeclaredField("pattern"));

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		Object value = fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor);
		assertEquals(15.0, value);
		value = fcs.convert(15.0, descriptor, TypeDescriptor.valueOf(String.class));
		assertEquals("15", value);
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example 3
Source File: MoneyFormattingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testAmountWithNumberFormat5() {
	FormattedMoneyHolder5 bean = new FormattedMoneyHolder5();
	DataBinder binder = new DataBinder(bean);
	binder.setConversionService(conversionService);

	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("amount", "USD 10.50");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("USD 010.500", binder.getBindingResult().getFieldValue("amount"));
	assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d);
	assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode());

	LocaleContextHolder.setLocale(Locale.CANADA);
	binder.bind(propertyValues);
	LocaleContextHolder.setLocale(Locale.US);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("USD 010.500", binder.getBindingResult().getFieldValue("amount"));
	assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d);
	assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode());
}
 
Example 4
Source File: NumberFormattingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.setEmbeddedValueResolver(new StringValueResolver() {
		@Override
		public String resolveStringValue(String strVal) {
			if ("${pattern}".equals(strVal)) {
				return "#,##.00";
			}
			else {
				return strVal;
			}
		}
	});
	conversionService.addFormatterForFieldType(Number.class, new NumberStyleFormatter());
	conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
	LocaleContextHolder.setLocale(Locale.US);
	binder = new DataBinder(new TestBean());
	binder.setConversionService(conversionService);
}
 
Example 5
Source File: DataBinderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testBindingErrorWithCustomFormatter() {
	TestBean tb = new TestBean();
	DataBinder binder = new DataBinder(tb);
	binder.addCustomFormatter(new NumberStyleFormatter());
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1x2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertEquals(new Float(0.0), tb.getMyFloat());
		assertEquals("1x2", binder.getBindingResult().getFieldValue("myFloat"));
		assertTrue(binder.getBindingResult().hasFieldErrors("myFloat"));
		assertEquals("typeMismatch", binder.getBindingResult().getFieldError("myFloat").getCode());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example 6
Source File: DataBinderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testBindingErrorWithFormatterAgainstList() {
	BeanWithIntegerList tb = new BeanWithIntegerList();
	DataBinder binder = new DataBinder(tb);
	FormattingConversionService conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter());
	binder.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("integerList[0]", "1x2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertTrue(tb.getIntegerList().isEmpty());
		assertEquals("1x2", binder.getBindingResult().getFieldValue("integerList[0]"));
		assertTrue(binder.getBindingResult().hasFieldErrors("integerList[0]"));
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example 7
Source File: HttpRequestHandlerServlet.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	Assert.state(this.target != null, "No HttpRequestHandler available");

	LocaleContextHolder.setLocale(request.getLocale());
	try {
		this.target.handleRequest(request, response);
	}
	catch (HttpRequestMethodNotSupportedException ex) {
		String[] supportedMethods = ex.getSupportedMethods();
		if (supportedMethods != null) {
			response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
		}
		response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example 8
Source File: DataBinderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBindingWithCustomFormatter() {
	TestBean tb = new TestBean();
	DataBinder binder = new DataBinder(tb);
	binder.addCustomFormatter(new NumberStyleFormatter(), Float.class);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertEquals(new Float(1.2), tb.getMyFloat());
		assertEquals("1,2", binder.getBindingResult().getFieldValue("myFloat"));

		PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class);
		assertNotNull(editor);
		editor.setValue(new Float(1.4));
		assertEquals("1,4", editor.getAsText());

		editor = binder.getBindingResult().findEditor("myFloat", null);
		assertNotNull(editor);
		editor.setAsText("1,6");
		assertTrue(((Number) editor.getValue()).floatValue() == 1.6f);
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example 9
Source File: DateTimeFormattingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 10
Source File: RequestContextFilter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example 11
Source File: DataBinderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBindingWithFormatterAgainstFields() {
	TestBean tb = new TestBean();
	DataBinder binder = new DataBinder(tb);
	FormattingConversionService conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter());
	binder.setConversionService(conversionService);
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertEquals(new Float(1.2), tb.getMyFloat());
		assertEquals("1,2", binder.getBindingResult().getFieldValue("myFloat"));

		PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class);
		assertNotNull(editor);
		editor.setValue(new Float(1.4));
		assertEquals("1,4", editor.getAsText());

		editor = binder.getBindingResult().findEditor("myFloat", null);
		assertNotNull(editor);
		editor.setAsText("1,6");
		assertEquals(new Float(1.6), editor.getValue());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example 12
Source File: GroovyMarkupConfigurerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveI18nFullLocale() throws Exception {
	LocaleContextHolder.setLocale(Locale.GERMANY);
	URL url = this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "i18n.tpl");
	assertNotNull(url);
	assertThat(url.getPath(), Matchers.containsString("i18n_de_DE.tpl"));
}
 
Example 13
Source File: WebMvcConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void handlerExceptionResolver() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	HandlerExceptionResolverComposite compositeResolver =
			context.getBean("handlerExceptionResolver", HandlerExceptionResolverComposite.class);

	assertEquals(0, compositeResolver.getOrder());
	List<HandlerExceptionResolver> expectedResolvers = compositeResolver.getExceptionResolvers();

	assertEquals(ExceptionHandlerExceptionResolver.class, expectedResolvers.get(0).getClass());
	assertEquals(ResponseStatusExceptionResolver.class, expectedResolvers.get(1).getClass());
	assertEquals(DefaultHandlerExceptionResolver.class, expectedResolvers.get(2).getClass());

	ExceptionHandlerExceptionResolver eher = (ExceptionHandlerExceptionResolver) expectedResolvers.get(0);
	assertNotNull(eher.getApplicationContext());

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(eher);
	List<Object> interceptors = (List<Object>) fieldAccessor.getPropertyValue("responseBodyAdvice");
	assertEquals(1, interceptors.size());
	assertEquals(JsonViewResponseBodyAdvice.class, interceptors.get(0).getClass());

	LocaleContextHolder.setLocale(Locale.ENGLISH);
	try {
		ResponseStatusExceptionResolver rser = (ResponseStatusExceptionResolver) expectedResolvers.get(1);
		MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
		MockHttpServletResponse response = new MockHttpServletResponse();
		rser.resolveException(request, response, context.getBean(TestController.class), new UserAlreadyExistsException());
		assertEquals("User already exists!", response.getErrorMessage());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example 14
Source File: DateFormattingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void setUp(DateFormatterRegistrar registrar) {
	DefaultConversionService.addDefaultConverters(conversionService);
	registrar.registerFormatters(conversionService);

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

	LocaleContextHolder.setLocale(Locale.US);
}
 
Example 15
Source File: GroovyMarkupViewTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private MockHttpServletResponse renderViewWithModel(String viewUrl, Map<String,
		Object> model, Locale locale) throws Exception {

	GroovyMarkupView view = createViewWithUrl(viewUrl);
	MockHttpServletResponse response = new MockHttpServletResponse();
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addPreferredLocale(locale);
	LocaleContextHolder.setLocale(locale);
	view.renderMergedTemplateModel(model, request, response);
	return response;
}
 
Example 16
Source File: SpringSecurityConfig.java    From springboot_security_restful_api with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    Locale locale = localeResolver.resolveLocale((HttpServletRequest) request);
    LocaleContextHolder.setLocale(locale);

    chain.doFilter(request, response);
}
 
Example 17
Source File: FormattingConversionServiceTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Before
public void setUp() {
	formattingService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(formattingService);
	LocaleContextHolder.setLocale(Locale.US);
}
 
Example 18
Source File: NegotiatorControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
@BeforeEach
void beforeMethod() {
  initMocks(this);

  /* Negotiator config mock */
  Query<NegotiatorEntityConfig> query =
      new QueryImpl<NegotiatorEntityConfig>()
          .eq(NegotiatorEntityConfigMetadata.ENTITY, "molgenis_id_1");
  when(dataService.findOne(
          NegotiatorEntityConfigMetadata.NEGOTIATORENTITYCONFIG,
          query,
          NegotiatorEntityConfig.class))
      .thenReturn(negotiatorEntityConfig);

  when(collectionAttr.getName()).thenReturn("collectionAttr");
  when(collectionAttr.getDataType()).thenReturn(AttributeType.STRING);
  doReturn(collectionAttr).when(negotiatorEntityConfig).getEntity(COLLECTION_ID, Attribute.class);

  when(biobackAttr.getName()).thenReturn("biobackAttr");
  when(biobackAttr.getDataType()).thenReturn(AttributeType.STRING);
  doReturn(biobackAttr).when(negotiatorEntityConfig).getEntity(BIOBANK_ID, Attribute.class);

  when(negotiatorEntityConfig.getString(ENABLED_EXPRESSION)).thenReturn("$(enabled).value()");
  when(negotiatorEntityConfig.getNegotiatorConfig()).thenReturn(negotiatorConfig);

  /* get EntityCollection mock */
  when(dataService.getRepository("molgenis_id_1")).thenReturn(repo);
  when(queryRsql.createQuery(repo)).thenReturn(molgenisQuery);
  when(rsqlQueryConverter.convert("*=q=MOLGENIS")).thenReturn(queryRsql);

  LocaleContextHolder.setLocale(Locale.ENGLISH);
  AllPropertiesMessageSource messageSource = new AllPropertiesMessageSource();
  messageSource.addMolgenisNamespaces("dataexplorer");

  negotiatorController =
      new NegotiatorController(
          restTemplate,
          permissionService,
          dataService,
          rsqlQueryConverter,
          jsMagmaScriptEvaluator,
          messageSource);
}
 
Example 19
Source File: GroovyMarkupConfigurerTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test(expected = IOException.class)
public void failMissingTemplate() throws Exception {
	LocaleContextHolder.setLocale(Locale.US);
	this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "missing.tpl");
	Assert.fail();
}
 
Example 20
Source File: JodaTimeFormattingTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
	LocaleContextHolder.setLocale(null);
	JodaTimeContextHolder.setJodaTimeContext(null);
}