类org.springframework.context.i18n.LocaleContextHolder源码实例Demo

下面列出了怎么用org.springframework.context.i18n.LocaleContextHolder的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: wallride   文件: AtomFeedView.java
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");
	}
 
源代码2 项目: spring-analysis-note   文件: DataBinderTests.java
@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();
	}
}
 
@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());
}
 
@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());
}
 
源代码5 项目: data-prep   文件: AppSettingsAPI.java
/**
 * 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();
    };
}
 
@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);
			});
}
 
@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);
			});
}
 
源代码8 项目: java-technology-stack   文件: DataBinderTests.java
@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();
	}
}
 
源代码9 项目: fredbet   文件: MatchResultController.java
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;
}
 
@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());
}
 
/**
 * 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);
	}
}
 
/**
 * 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();
}
 
@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();
	}
}
 
/**
 * 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);
  }
}
 
源代码15 项目: spring4-understanding   文件: DataBinderTests.java
@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();
	}
}
 
/**
 * 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();
}
 
源代码17 项目: heimdall   文件: GlobalExceptionHandler.java
/**
 * 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;
}
 
源代码18 项目: molgenis   文件: JobUtils.java
/**
 * 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();
}
 
源代码19 项目: spring-analysis-note   文件: DataBinderTests.java
@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();
	}
}
 
源代码20 项目: spring-analysis-note   文件: DataBinderTests.java
@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();
	}
}
 
/**
* 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";
  }
 
@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"));
}
 
源代码23 项目: fredbet   文件: RankingController.java
@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);
}
 
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);
}
 
源代码25 项目: lams   文件: OutputFactory.java
/**
    * 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;
   }
 
@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()));
}
 
源代码27 项目: spring-analysis-note   文件: DateFormattingTests.java
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);
}
 
源代码28 项目: spring-analysis-note   文件: FrameworkServlet.java
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);
	}
}
 
@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"));
}
 
@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"));
}
 
 同包方法