Java Code Examples for org.springframework.context.i18n.LocaleContextHolder

The following examples show how to use org.springframework.context.i18n.LocaleContextHolder. These examples are extracted from open source projects. 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 Project: wallride   Source File: AtomFeedView.java    License: 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 2
Source Project: spring-analysis-note   Source File: DataBinderTests.java    License: 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 3
Source Project: java-technology-stack   Source File: MoneyFormattingTests.java    License: 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 Project: spring-analysis-note   Source File: MoneyFormattingTests.java    License: 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 5
Source Project: data-prep   Source File: AppSettingsAPI.java    License: 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 6
@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 7
@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 8
Source Project: java-technology-stack   Source File: DataBinderTests.java    License: 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 9
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 10
@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 11
/**
 * 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 12
/**
 * 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 13
@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 14
/**
 * Adds a new task.
 * @param brokerDefinition broker definition
 * @return broker info of the newly created broker
 */
@RequestMapping(value = "/rest/harvester/brokers", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BrokerResponse> createBroker(@RequestBody EntityDefinition brokerDefinition) {
  try {
    LOG.debug(String.format("POST /rest/harvester/brokers <-- %s", brokerDefinition));
    return new ResponseEntity<>(BrokerResponse.createFrom(engine.getBrokersService().createBroker(brokerDefinition, LocaleContextHolder.getLocale())), HttpStatus.OK);
  } catch (DataProcessorException ex) {
    LOG.error(String.format("Error creating broker: %s", brokerDefinition), ex);
    return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
  }
}
 
Example 15
Source Project: spring4-understanding   Source File: DataBinderTests.java    License: Apache License 2.0 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 16
/**
 * 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 17
Source Project: heimdall   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method that captures all the {@link BindExceptionInfo} exceptions.
 *
 * @param response
 * {@link HttpServletResponse}
 * @param request
 * {@link HttpServletRequest}
 * @param exception
 * {@link BindExceptionInfo}
 * @return {@link BindExceptionInfo}.
 */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
public @ResponseBody BindExceptionInfo validationBindException(HttpServletResponse response, HttpServletRequest request, BindException exception) {

     BindExceptionInfo bindException = new BindExceptionInfo();
     List<BindError> errors = new ArrayList<>();
     List<ObjectError> objectsError = exception.getBindingResult().getAllErrors();

     objectsError.forEach(objectError -> {
          FieldError fieldError = (FieldError) objectError;

          String message = null;

          try {

               String code = fieldError.getCodes()[0];
               message = messageSource.getMessage(code, null, LocaleContextHolder.getLocale());
          } catch (Exception e) {

               message = null;
          }

          bindException.timestamp = LocalDateTime.now();
          bindException.status = 400;
          bindException.exception = "BindExceptionPIER";

          BindError error = bindException.new BindError();
          error.defaultMessage = message != null ? message : fieldError.getDefaultMessage();
          error.objectName = fieldError.getObjectName();
          error.field = fieldError.getField();
          error.code = fieldError.getCode();

          errors.add(error);
     });

     bindException.erros = errors;

     return bindException;
}
 
Example 18
Source Project: molgenis   Source File: JobUtils.java    License: 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 19
Source Project: spring-analysis-note   Source File: DataBinderTests.java    License: MIT License 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 20
Source Project: spring-analysis-note   Source File: DataBinderTests.java    License: MIT License 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 21
Source Project: podcastpedia-web   Source File: StartPageFeedsController.java    License: MIT License 5 votes vote down vote up
/**
* Returns top rated list of podcasts to be generated as an atom feed.  
* Request comes from start page. 
* 
* @param request
* @param model
* @return
*/
  @RequestMapping("most_popular.atom")
  public String getTopRatedPodcastsAtomFeed(WebRequest request, Model model) {
  	Locale locale = LocaleContextHolder.getLocale();
      model.addAttribute("list_of_podcasts", getTopRatedPodcastsForLocale(locale));
      model.addAttribute("feed_id", "tag:podcastpedia.org,2013-04-30:most_popular");
      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 "topRatedPodcastsAtomFeedView";
  }
 
Example 22
@Test
public void resolveI18nFullLocale() throws Exception {
	LocaleContextHolder.setLocale(Locale.GERMANY);
	URL url = this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "i18n.tpl");
	Assert.assertNotNull(url);
	Assert.assertThat(url.getPath(), Matchers.containsString("i18n_de_DE.tpl"));
}
 
Example 23
@GetMapping(value = "/pdf", produces = CONTENT_TYPE_PDF)
public ResponseEntity<byte[]> exportAllBets() {
    final String fileName = createFilename();
    byte[] fileContent = this.rankingService.exportBetsToPdf(LocaleContextHolder.getLocale());
    if (fileContent == null) {
        return ResponseEntity.notFound().build();
    }

    return createResponseEntity(fileName, fileContent);
}
 
Example 24
Source Project: java-technology-stack   Source File: DateTimeFormattingTests.java    License: MIT License 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 25
Source Project: lams   Source File: OutputFactory.java    License: 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 26
Source Project: spring-analysis-note   Source File: JodaTimeFormattingTests.java    License: 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 27
Source Project: spring-analysis-note   Source File: DateFormattingTests.java    License: 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 28
Source Project: spring-analysis-note   Source File: FrameworkServlet.java    License: 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 29
Source Project: spring-analysis-note   Source File: GroovyMarkupConfigurerTests.java    License: 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 30
Source Project: spring-analysis-note   Source File: GroovyMarkupConfigurerTests.java    License: 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"));
}