org.springframework.context.i18n.LocaleContextHolder Java Examples

The following examples show how to use org.springframework.context.i18n.LocaleContextHolder. 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: DefaultRenderingResponseBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	MediaType contentType = exchange.getResponse().getHeaders().getContentType();
	Locale locale = LocaleContextHolder.getLocale(exchange.getLocaleContext());
	Stream<ViewResolver> viewResolverStream = context.viewResolvers().stream();

	return Flux.fromStream(viewResolverStream)
			.concatMap(viewResolver -> viewResolver.resolveViewName(name(), locale))
			.next()
			.switchIfEmpty(Mono.error(() ->
					new IllegalArgumentException("Could not resolve view with name '" + name() + "'")))
			.flatMap(view -> {
				List<MediaType> mediaTypes = view.getSupportedMediaTypes();
				return view.render(model(),
						contentType == null && !mediaTypes.isEmpty() ? mediaTypes.get(0) : contentType,
						exchange);
			});
}
 
Example #2
Source File: MoneyFormattingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAmountWithNumberFormat1() {
	FormattedMoneyHolder1 bean = new FormattedMoneyHolder1();
	DataBinder binder = new DataBinder(bean);
	binder.setConversionService(conversionService);

	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("amount", "$10.50");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("$10.50", 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("$10.50", binder.getBindingResult().getFieldValue("amount"));
	assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d);
	assertEquals("CAD", bean.getAmount().getCurrency().getCurrencyCode());
}
 
Example #3
Source File: MoneyFormattingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testAmountAndUnit() {
	MoneyHolder bean = new MoneyHolder();
	DataBinder binder = new DataBinder(bean);
	binder.setConversionService(conversionService);

	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("amount", "USD 10.50");
	propertyValues.add("unit", "USD");
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	assertEquals("USD10.50", binder.getBindingResult().getFieldValue("amount"));
	assertEquals("USD", binder.getBindingResult().getFieldValue("unit"));
	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("USD10.50", binder.getBindingResult().getFieldValue("amount"));
	assertEquals("USD", binder.getBindingResult().getFieldValue("unit"));
	assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d);
	assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode());
}
 
Example #4
Source File: DataBinderTests.java    From java-technology-stack 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 #5
Source File: DefaultRenderingResponseBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	MediaType contentType = exchange.getResponse().getHeaders().getContentType();
	Locale locale = LocaleContextHolder.getLocale(exchange.getLocaleContext());
	Stream<ViewResolver> viewResolverStream = context.viewResolvers().stream();

	return Flux.fromStream(viewResolverStream)
			.concatMap(viewResolver -> viewResolver.resolveViewName(name(), locale))
			.next()
			.switchIfEmpty(Mono.error(() ->
					new IllegalArgumentException("Could not resolve view with name '" + name() + "'")))
			.flatMap(view -> {
				List<MediaType> mediaTypes = view.getSupportedMediaTypes();
				return view.render(model(),
						contentType == null && !mediaTypes.isEmpty() ? mediaTypes.get(0) : contentType,
						exchange);
			});
}
 
Example #6
Source File: DataBinderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testBindingErrorWithFormatterAgainstFields() {
	TestBean tb = new TestBean();
	DataBinder binder = new DataBinder(tb);
	binder.initDirectFieldAccess();
	FormattingConversionService conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter());
	binder.setConversionService(conversionService);
	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"));
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example #7
Source File: SimpleHttpInvokerRequestExecutor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Prepare the given HTTP connection.
 * <p>The default implementation specifies POST as method,
 * "application/x-java-serialized-object" as "Content-Type" header,
 * and the given content length as "Content-Length" header.
 * @param connection the HTTP connection to prepare
 * @param contentLength the length of the content to send
 * @throws IOException if thrown by HttpURLConnection methods
 * @see java.net.HttpURLConnection#setRequestMethod
 * @see java.net.HttpURLConnection#setRequestProperty
 */
protected void prepareConnection(HttpURLConnection connection, int contentLength) throws IOException {
	if (this.connectTimeout >= 0) {
		connection.setConnectTimeout(this.connectTimeout);
	}
	if (this.readTimeout >= 0) {
		connection.setReadTimeout(this.readTimeout);
	}

	connection.setDoOutput(true);
	connection.setRequestMethod(HTTP_METHOD_POST);
	connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, getContentType());
	connection.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, Integer.toString(contentLength));

	LocaleContext localeContext = LocaleContextHolder.getLocaleContext();
	if (localeContext != null) {
		Locale locale = localeContext.getLocale();
		if (locale != null) {
			connection.setRequestProperty(HTTP_HEADER_ACCEPT_LANGUAGE, locale.toLanguageTag());
		}
	}

	if (isAcceptGzipEncoding()) {
		connection.setRequestProperty(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
	}
}
 
Example #8
Source File: MatchResultController.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
private MatchResultCommand toMatchResultCommand(Match match) {
    MatchResultCommand matchResultCommand = new MatchResultCommand();
    matchResultCommand.setMatchId(match.getId());
    matchResultCommand.setGroupMatch(match.isGroupMatch());

    final Locale locale = LocaleContextHolder.getLocale();
    final Team teamOne = match.getTeamOne();
    final Team teamTwo = match.getTeamTwo();
    matchResultCommand.setTeamNameOne(teamOne.getNameTranslated(messageSourceUtil, locale));
    matchResultCommand.setIconPathTeamOne(teamOne.getIconPathBig());
    matchResultCommand.setTeamNameTwo(teamTwo.getNameTranslated(messageSourceUtil, locale));
    matchResultCommand.setIconPathTeamTwo(teamTwo.getIconPathBig());

    matchResultCommand.setTeamResultOne(match.getGoalsTeamOne());
    matchResultCommand.setTeamResultTwo(match.getGoalsTeamTwo());
    matchResultCommand.setPenaltyWinnerOne(match.isPenaltyWinnerOne());
    return matchResultCommand;
}
 
Example #9
Source File: AtomFeedView.java    From wallride with Apache License 2.0 6 votes vote down vote up
protected void buildFeedMetadata(
			Map<String, Object> model,
			Feed feed,
			HttpServletRequest request) {
		Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
		String language = LocaleContextHolder.getLocale().getLanguage();

		feed.setTitle(blog.getTitle(language));
		Content info = new Content();
		info.setValue(blog.getTitle(language));
		feed.setInfo(info);

		ArrayList<Link> links = new ArrayList<>();
		Link link = new Link();
		UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
		link.setHref(builder.buildAndExpand().toUriString());
		links.add(link);
		feed.setOtherLinks(links);
//		feed.setIcon("http://" + settings.getAsString(Setting.Key.SITE_URL) + "resources/default/img/favicon.ico");
	}
 
Example #10
Source File: AppSettingsAPI.java    From data-prep with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the app settings to configure frontend components
 */
@RequestMapping(value = "/api/settings", method = GET)
@ApiOperation(value = "Get the app settings", produces = APPLICATION_JSON_VALUE)
@Timed
@PublicAPI
public Callable<AppSettings>
        getSettings(@RequestHeader(name = HttpHeaders.ACCEPT_LANGUAGE, required = false) String language) {
    return () -> {
        if (StringUtils.isBlank(language)) {
            final Locale userLocale = security.getLocale();
            final Locale previous = LocaleContextHolder.getLocale();
            LocaleContextHolder.setLocale(userLocale);
            LOGGER.info("No request locale, locale changed from {} to {}.", previous, userLocale);
        }
        return context.getBean(AppSettingsService.class).getSettings();
    };
}
 
Example #11
Source File: MoneyFormattingTests.java    From spring4-understanding with Apache License 2.0 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 #12
Source File: RequestContextListener.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void requestDestroyed(ServletRequestEvent requestEvent) {
	ServletRequestAttributes attributes = null;
	Object reqAttr = requestEvent.getServletRequest().getAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE);
	if (reqAttr instanceof ServletRequestAttributes) {
		attributes = (ServletRequestAttributes) reqAttr;
	}
	RequestAttributes threadAttributes = RequestContextHolder.getRequestAttributes();
	if (threadAttributes != null) {
		// We're assumably within the original request thread...
		LocaleContextHolder.resetLocaleContext();
		RequestContextHolder.resetRequestAttributes();
		if (attributes == null && threadAttributes instanceof ServletRequestAttributes) {
			attributes = (ServletRequestAttributes) threadAttributes;
		}
	}
	if (attributes != null) {
		attributes.requestCompleted();
	}
}
 
Example #13
Source File: ResponseStatusExceptionResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Template method that handles {@link ResponseStatus @ResponseStatus} annotation.
 * <p>The default implementation sends a response error using
 * {@link HttpServletResponse#sendError(int)} or
 * {@link HttpServletResponse#sendError(int, String)} if the annotation has a
 * {@linkplain ResponseStatus#reason() reason} and then returns an empty ModelAndView.
 * @param responseStatus the annotation
 * @param request current HTTP request
 * @param response current HTTP response
 * @param handler the executed handler, or {@code null} if none chosen at the
 * time of the exception (for example, if multipart resolution failed)
 * @param ex the exception that got thrown during handler execution or the
 * exception that has the ResponseStatus annotation if found on the cause.
 * @return a corresponding ModelAndView to forward to, or {@code null}
 * for default processing
 */
protected ModelAndView resolveResponseStatus(ResponseStatus responseStatus, HttpServletRequest request,
		HttpServletResponse response, Object handler, Exception ex) throws Exception {

	int statusCode = responseStatus.code().value();
	String reason = responseStatus.reason();
	if (this.messageSource != null) {
		reason = this.messageSource.getMessage(reason, null, reason, LocaleContextHolder.getLocale());
	}
	if (!StringUtils.hasLength(reason)) {
		response.sendError(statusCode);
	}
	else {
		response.sendError(statusCode, reason);
	}
	return new ModelAndView();
}
 
Example #14
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 #15
Source File: DateFormattingTests.java    From spring-analysis-note with MIT License 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 #16
Source File: StartPageFeedsController.java    From podcastpedia-web with MIT License 5 votes vote down vote up
/**
 * Returns a list of top rated podcasts to be generated as an rss feed.
 * Request comes from start page. 
 * 
 * @param model
 * @return
 */
@RequestMapping("most_popular.rss")
public String getTopRatedPodcastsRssFeed(Model model) {
	
	Locale locale = LocaleContextHolder.getLocale();
    
    model.addAttribute("list_of_podcasts", getTopRatedPodcastsForLocale(locale));
    model.addAttribute("feed_title", messageSource.getMessage("podcasts.most_popular.feed_title", null, locale));
    model.addAttribute("feed_description", messageSource.getMessage("podcasts.most_popular.feed_description", null, locale));
    model.addAttribute("feed_link", configService.getValue("HOST_AND_PORT_URL"));
    model.addAttribute("HOST_AND_PORT_URL", configService.getValue("HOST_AND_PORT_URL"));
    
    return "topRatedPodcastsRssFeedView";
}
 
Example #17
Source File: JobUtils.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Clear the security context and locale context if the job was run in another thread. This
 * prevents accidental use of the contexts when a thread is reused. Furthermore this prevents
 * memory leaks by clearing thread-local values.
 *
 * @param callingThreadId identifier of the thread that requested execution (might be the same as
 *     the execution thread)
 */
public static void cleanupAfterRunJob(long callingThreadId) {
  if (Thread.currentThread().getId() == callingThreadId) {
    return;
  }

  SecurityContextHolder.clearContext();
  LocaleContextHolder.resetLocaleContext();
}
 
Example #18
Source File: ComLogonServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String getHelpLanguage(ComAdmin admin) {
	if (admin == null) {
		return getHelpLanguage(LocaleContextHolder.getLocale().getLanguage());
	} else {
		return getHelpLanguage(admin.getAdminLang().trim().toLowerCase());
	}
}
 
Example #19
Source File: ResponseStatusExceptionResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Apply the resolved status code and reason to the response.
 * <p>The default implementation sends a response error using
 * {@link HttpServletResponse#sendError(int)} or
 * {@link HttpServletResponse#sendError(int, String)} if there is a reason
 * and then returns an empty ModelAndView.
 * @param statusCode the HTTP status code
 * @param reason the associated reason (may be {@code null} or empty)
 * @param response current HTTP response
 * @since 5.0
 */
protected ModelAndView applyStatusAndReason(int statusCode, @Nullable String reason, HttpServletResponse response)
		throws IOException {

	if (!StringUtils.hasLength(reason)) {
		response.sendError(statusCode);
	}
	else {
		String resolvedReason = (this.messageSource != null ?
				this.messageSource.getMessage(reason, null, reason, LocaleContextHolder.getLocale()) :
				reason);
		response.sendError(statusCode, resolvedReason);
	}
	return new ModelAndView();
}
 
Example #20
Source File: SpringletsDataArgumentResolversAutoConfigurationTest.java    From springlets with Apache License 2.0 5 votes vote down vote up
@After
public void close() {
  LocaleContextHolder.resetLocaleContext();
  if (this.context != null) {
    this.context.close();
  }
}
 
Example #21
Source File: FrameworkServlet.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void initContextHolders(HttpServletRequest request,
		@Nullable LocaleContext localeContext, @Nullable RequestAttributes requestAttributes) {

	if (localeContext != null) {
		LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);
	}
	if (requestAttributes != null) {
		RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
	}
}
 
Example #22
Source File: OutputFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Get the I18N description for this key. If the tool has supplied a messageService, then this is used to look up
    * the key and hence get the text. Otherwise if the tool has supplied a I18N languageFilename then it is accessed
    * via the shared toolActMessageService. If neither are supplied or the key is not found, then any "." in the name
    * are converted to space and this is used as the return value.
    *
    * This is normally used to get the description for a definition, in whic case the key should be in the format
    * output.desc.[definition name], key = definition name and addPrefix = true. For example a definition name of
    * "learner.mark" becomes output.desc.learner.mark.
    *
    * If you want to use this to get an arbitrary string from the I18N files, then set addPrefix = false and the
    * output.desc will not be added to the beginning.
    */
   protected String getI18NText(String key, boolean addPrefix) {
String translatedText = null;

MessageSource tmpMsgSource = getMsgSource();
if (tmpMsgSource != null) {
    if (addPrefix) {
	key = KEY_PREFIX + key;
    }
    Locale locale = LocaleContextHolder.getLocale();
    try {
	translatedText = tmpMsgSource.getMessage(key, null, locale);
    } catch (NoSuchMessageException e) {
	log.warn("Unable to internationalise the text for key " + key
		+ " as no matching key found in the msgSource");
    }
} else {
    log.warn("Unable to internationalise the text for key " + key
	    + " as no matching key found in the msgSource. The tool's OutputDefinition factory needs to set either (a) messageSource or (b) loadedMessageSourceService and languageFilename.");
}

if (translatedText == null || translatedText.length() == 0) {
    translatedText = key.replace('.', ' ');
}

return translatedText;
   }
 
Example #23
Source File: GroovyMarkupConfigurerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveI18nPartialLocale() throws Exception {
	LocaleContextHolder.setLocale(Locale.FRANCE);
	URL url = this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "i18n.tpl");
	assertNotNull(url);
	assertThat(url.getPath(), Matchers.containsString("i18n_fr.tpl"));
}
 
Example #24
Source File: JodaTimeFormattingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testJodaTimePatternsForStyle() {
	System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("SS", LocaleContextHolder.getLocale()));
	System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("MM", LocaleContextHolder.getLocale()));
	System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("LL", LocaleContextHolder.getLocale()));
	System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("FF", LocaleContextHolder.getLocale()));
}
 
Example #25
Source File: DataBinderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testBindingWithFormatter() {
	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);
	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 #26
Source File: RequestContextFilter.java    From lams with GNU General Public License v2.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 #27
Source File: RequestContextListener.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void requestInitialized(ServletRequestEvent requestEvent) {
	if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
		throw new IllegalArgumentException(
				"Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
	}
	HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
	ServletRequestAttributes attributes = new ServletRequestAttributes(request);
	request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
	LocaleContextHolder.setLocale(request.getLocale());
	RequestContextHolder.setRequestAttributes(attributes);
}
 
Example #28
Source File: ExcelExportController.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@GetMapping(value = "/ranking", produces = CONTENT_TYPE_EXCEL)
public ResponseEntity<byte[]> exportRanking() {
    final String fileName = "ranking.xlsx";
    byte[] fileContent = this.reportService.exportRankingToExcel(LocaleContextHolder.getLocale());
    if (fileContent == null) {
        return ResponseEntity.notFound().build();
    }

    return createResponseEntity(fileName, fileContent);
}
 
Example #29
Source File: FormattingConversionService.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return "";
	}
	if (!sourceType.isAssignableTo(this.printerObjectType)) {
		source = this.conversionService.convert(source, sourceType, this.printerObjectType);
	}
	return this.printer.print(source, LocaleContextHolder.getLocale());
}
 
Example #30
Source File: JodaTimeFormattingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testJodaTimePatternsForStyle() {
	System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("SS", LocaleContextHolder.getLocale()));
	System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("MM", LocaleContextHolder.getLocale()));
	System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("LL", LocaleContextHolder.getLocale()));
	System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("FF", LocaleContextHolder.getLocale()));
}