Java Code Examples for org.springframework.context.MessageSource

The following examples show how to use org.springframework.context.MessageSource. 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: lams   Source File: AbstractMessageSource.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Try to retrieve the given message from the parent {@code MessageSource}, if any.
 * @param code the code to lookup up, such as 'calculator.noRateSet'
 * @param args array of arguments that will be filled in for params
 * within the message
 * @param locale the locale in which to do the lookup
 * @return the resolved message, or {@code null} if not found
 * @see #getParentMessageSource()
 */
protected String getMessageFromParent(String code, Object[] args, Locale locale) {
	MessageSource parent = getParentMessageSource();
	if (parent != null) {
		if (parent instanceof AbstractMessageSource) {
			// Call internal method to avoid getting the default code back
			// in case of "useCodeAsDefaultMessage" being activated.
			return ((AbstractMessageSource) parent).getMessageInternal(code, args, locale);
		}
		else {
			// Check parent MessageSource, returning null if not found there.
			return parent.getMessage(code, args, null, locale);
		}
	}
	// Not found in parent either.
	return null;
}
 
Example 2
/**
 * To initialize the {@link WebErrorHandlers} instance with a code-to-message translator, a
 * non-empty collection of {@link WebErrorHandler} implementations and an optional fallback
 * error handler.
 *
 * <p>This constructor is meant to be called by {@link WebErrorHandlersBuilder#build()} method.
 *
 * @param messageSource                 The code to message translator.
 * @param webErrorHandlers              Collection of {@link WebErrorHandler} implementations.
 * @param defaultWebErrorHandler        Fallback web error handler.
 * @param exceptionRefiner              Possibly can refine exceptions before handling them.
 * @param exceptionLogger               Logs exceptions.
 * @param webErrorHandlerPostProcessors Executes additional actions on HttpError.
 * @param fingerprintProvider           Calculates fingerprint of error message.
 * @param errorsProperties              Configuration properties bean.
 * @throws NullPointerException     When one of the required parameters is null.
 * @throws IllegalArgumentException When the collection of implementations is empty.
 */
WebErrorHandlers(@NonNull MessageSource messageSource,
                 @NonNull List<WebErrorHandler> webErrorHandlers,
                 @Nullable WebErrorHandler defaultWebErrorHandler,
                 @NonNull ExceptionRefiner exceptionRefiner,
                 @NonNull ExceptionLogger exceptionLogger,
                 @NonNull List<WebErrorHandlerPostProcessor> webErrorHandlerPostProcessors,
                 @NonNull FingerprintProvider fingerprintProvider,
                 @NonNull ErrorsProperties errorsProperties) {
    this.errorsProperties = requireNonNull(errorsProperties);
    this.messageSource = new TemplateAwareMessageSource(
        requireNonNull(messageSource, "We need a MessageSource implementation to message translation"));
    this.webErrorHandlers = requireAtLeastOneHandler(webErrorHandlers);
    if (defaultWebErrorHandler != null) this.defaultWebErrorHandler = defaultWebErrorHandler;
    this.exceptionRefiner = requireNonNull(exceptionRefiner);
    this.exceptionLogger = requireNonNull(exceptionLogger);
    this.webErrorHandlerPostProcessors = requireNonNull(webErrorHandlerPostProcessors);
    this.fingerprintProvider = requireNonNull(fingerprintProvider);
}
 
Example 3
Source Project: spring-analysis-note   Source File: AbstractMessageSource.java    License: MIT License 6 votes vote down vote up
/**
 * Try to retrieve the given message from the parent {@code MessageSource}, if any.
 * @param code the code to lookup up, such as 'calculator.noRateSet'
 * @param args array of arguments that will be filled in for params
 * within the message
 * @param locale the locale in which to do the lookup
 * @return the resolved message, or {@code null} if not found
 * @see #getParentMessageSource()
 */
@Nullable
protected String getMessageFromParent(String code, @Nullable Object[] args, Locale locale) {
	MessageSource parent = getParentMessageSource();
	if (parent != null) {
		if (parent instanceof AbstractMessageSource) {
			// Call internal method to avoid getting the default code back
			// in case of "useCodeAsDefaultMessage" being activated.
			return ((AbstractMessageSource) parent).getMessageInternal(code, args, locale);
		}
		else {
			// Check parent MessageSource, returning null if not found there.
			// Covers custom MessageSource impls and DelegatingMessageSource.
			return parent.getMessage(code, args, null, locale);
		}
	}
	// Not found in parent either.
	return null;
}
 
Example 4
Source Project: spring-analysis-note   Source File: ResourceBundleThemeSource.java    License: MIT License 6 votes vote down vote up
/**
 * This implementation returns a SimpleTheme instance, holding a
 * ResourceBundle-based MessageSource whose basename corresponds to
 * the given theme name (prefixed by the configured "basenamePrefix").
 * <p>SimpleTheme instances are cached per theme name. Use a reloadable
 * MessageSource if themes should reflect changes to the underlying files.
 * @see #setBasenamePrefix
 * @see #createMessageSource
 */
@Override
@Nullable
public Theme getTheme(String themeName) {
	Theme theme = this.themeCache.get(themeName);
	if (theme == null) {
		synchronized (this.themeCache) {
			theme = this.themeCache.get(themeName);
			if (theme == null) {
				String basename = this.basenamePrefix + themeName;
				MessageSource messageSource = createMessageSource(basename);
				theme = new SimpleTheme(themeName, messageSource);
				initParent(theme);
				this.themeCache.put(themeName, theme);
				if (logger.isDebugEnabled()) {
					logger.debug("Theme created: name '" + themeName + "', basename [" + basename + "]");
				}
			}
		}
	}
	return theme;
}
 
Example 5
Source Project: AsuraFramework   Source File: MessageSourceUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 查找错误消息
 *
 * @param source
 * @param code
 * @param params
 * @param defaultMsg
 *
 * @return
 */
public static String getChinese(MessageSource source, String code, Object[] params, String defaultMsg) {
    if (Check.isNull(source)) {
        throw new IllegalArgumentException("message source is null");
    }
    if (Check.isNullOrEmpty(code)) {
        throw new IllegalArgumentException("code is empty");
    }
    //如果没有object 默认设置为空数组
    if (Check.isNull(params)) {
        params = new Object[]{};
    }
    if (Check.isNullOrEmpty(defaultMsg)) {
        return source.getMessage(code, params, Locale.SIMPLIFIED_CHINESE);
    } else {
        return source.getMessage(code, params, defaultMsg, Locale.SIMPLIFIED_CHINESE);
    }
}
 
Example 6
@Override
   public MessageSource getMessageService(String messageFilename) {
if (messageFilename != null) {
    MessageSource ms = messageServices.get(messageFilename);
    if (ms == null) {
	ResourceBundleMessageSource rbms = (ResourceBundleMessageSource) beanFactory
		.getBean(LOADED_MESSAGE_SOURCE_BEAN);
	rbms.setBasename(messageFilename);
	messageServices.put(messageFilename, rbms);
	ms = rbms;
    }
    return ms;
} else {
    return null;
}
   }
 
Example 7
Source Project: spring-analysis-note   Source File: RequestContext.java    License: MIT License 6 votes vote down vote up
public RequestContext(ServerWebExchange exchange, Map<String, Object> model, MessageSource messageSource,
		@Nullable RequestDataValueProcessor dataValueProcessor) {

	Assert.notNull(exchange, "ServerWebExchange is required");
	Assert.notNull(model, "Model is required");
	Assert.notNull(messageSource, "MessageSource is required");
	this.exchange = exchange;
	this.model = model;
	this.messageSource = messageSource;

	LocaleContext localeContext = exchange.getLocaleContext();
	Locale locale = localeContext.getLocale();
	this.locale = (locale != null ? locale : Locale.getDefault());
	TimeZone timeZone = (localeContext instanceof TimeZoneAwareLocaleContext ?
			((TimeZoneAwareLocaleContext) localeContext).getTimeZone() : null);
	this.timeZone = (timeZone != null ? timeZone : TimeZone.getDefault());

	this.defaultHtmlEscape = null;  // TODO
	this.dataValueProcessor = dataValueProcessor;
}
 
Example 8
Source Project: spring-analysis-note   Source File: JstlUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Checks JSTL's "javax.servlet.jsp.jstl.fmt.localizationContext"
 * context-param and creates a corresponding child message source,
 * with the provided Spring-defined MessageSource as parent.
 * @param servletContext the ServletContext we're running in
 * (to check JSTL-related context-params in {@code web.xml})
 * @param messageSource the MessageSource to expose, typically
 * the ApplicationContext of the current DispatcherServlet
 * @return the MessageSource to expose to JSTL; first checking the
 * JSTL-defined bundle, then the Spring-defined MessageSource
 * @see org.springframework.context.ApplicationContext
 */
public static MessageSource getJstlAwareMessageSource(
		@Nullable ServletContext servletContext, MessageSource messageSource) {

	if (servletContext != null) {
		String jstlInitParam = servletContext.getInitParameter(Config.FMT_LOCALIZATION_CONTEXT);
		if (jstlInitParam != null) {
			// Create a ResourceBundleMessageSource for the specified resource bundle
			// basename in the JSTL context-param in web.xml, wiring it with the given
			// Spring-defined MessageSource as parent.
			ResourceBundleMessageSource jstlBundleWrapper = new ResourceBundleMessageSource();
			jstlBundleWrapper.setBasename(jstlInitParam);
			jstlBundleWrapper.setParentMessageSource(messageSource);
			return jstlBundleWrapper;
		}
	}
	return messageSource;
}
 
Example 9
Source Project: lams   Source File: JstlUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks JSTL's "javax.servlet.jsp.jstl.fmt.localizationContext"
 * context-param and creates a corresponding child message source,
 * with the provided Spring-defined MessageSource as parent.
 * @param servletContext the ServletContext we're running in
 * (to check JSTL-related context-params in {@code web.xml})
 * @param messageSource the MessageSource to expose, typically
 * the ApplicationContext of the current DispatcherServlet
 * @return the MessageSource to expose to JSTL; first checking the
 * JSTL-defined bundle, then the Spring-defined MessageSource
 * @see org.springframework.context.ApplicationContext
 */
public static MessageSource getJstlAwareMessageSource(
		ServletContext servletContext, MessageSource messageSource) {

	if (servletContext != null) {
		String jstlInitParam = servletContext.getInitParameter(Config.FMT_LOCALIZATION_CONTEXT);
		if (jstlInitParam != null) {
			// Create a ResourceBundleMessageSource for the specified resource bundle
			// basename in the JSTL context-param in web.xml, wiring it with the given
			// Spring-defined MessageSource as parent.
			ResourceBundleMessageSource jstlBundleWrapper = new ResourceBundleMessageSource();
			jstlBundleWrapper.setBasename(jstlInitParam);
			jstlBundleWrapper.setParentMessageSource(messageSource);
			return jstlBundleWrapper;
		}
	}
	return messageSource;
}
 
Example 10
Source Project: match-trade   Source File: JsonResult.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>返回失败,无数据</p>
 * @param BindingResult
 * @return JsonResult
 */
public JsonResult<T> error(BindingResult result, MessageSource messageSource) {
    StringBuffer msg = new StringBuffer();
    // 获取错位字段集合
    List<FieldError> fieldErrors = result.getFieldErrors();
    // 获取本地locale,zh_CN
    Locale currentLocale = LocaleContextHolder.getLocale();
    for (FieldError fieldError : fieldErrors) {
        // 获取错误信息
        String errorMessage = messageSource.getMessage(fieldError, currentLocale);
        // 添加到错误消息集合内
        msg.append(fieldError.getField() + ":" + errorMessage + " ");
    }
    this.setCode(CODE_FAILED);
    this.setMsg(msg.toString());
    this.setData(null);
    return this;
}
 
Example 11
@Override
public void setMessageSource(MessageSource messageSource) {
    this.messageSource = messageSource;
    if (this.messageSource instanceof ApplicationContext) {
        XsltConfiguration xsltConfiguration = ((ApplicationContext) this.messageSource).getBean(XsltConfiguration.class);
        if (xsltConfiguration != null) {
            mediaType = xsltConfiguration.getMediaType();
            devMode = xsltConfiguration.isDevMode();
            parameterPreffix = xsltConfiguration.getParameterPreffix();
            GenericKeyedObjectPoolConfig gop = new GenericKeyedObjectPoolConfig();
            gop.setMaxTotal(xsltConfiguration.getPoolsMaxPerKey() * XsltConfiguration.TOTAL_FACTOR);
            gop.setMinIdlePerKey((int) (xsltConfiguration.getPoolsMaxPerKey() / XsltConfiguration.MIN_IDLE_FACTOR));
            gop.setMaxIdlePerKey((int) (xsltConfiguration.getPoolsMaxPerKey() / XsltConfiguration.MAX_IDLE_FACTOR));
            gop.setMaxTotalPerKey(xsltConfiguration.getPoolsMaxPerKey());
            gop.setTestOnBorrow(false);
            gop.setMaxWaitMillis(10_000);
            log.info("Pool of unmarshallers initialised with concurrency {}", gop.getMaxTotalPerKey());
            marshallerPool = new GenericKeyedObjectPool<>(new MarshallerFactory(), gop);
        } else {
            throw new IllegalArgumentException("No XsltConfiguration bean found!");
        }
    }
}
 
Example 12
Source Project: java-technology-stack   Source File: ResourceBundleThemeSource.java    License: MIT License 6 votes vote down vote up
/**
 * This implementation returns a SimpleTheme instance, holding a
 * ResourceBundle-based MessageSource whose basename corresponds to
 * the given theme name (prefixed by the configured "basenamePrefix").
 * <p>SimpleTheme instances are cached per theme name. Use a reloadable
 * MessageSource if themes should reflect changes to the underlying files.
 * @see #setBasenamePrefix
 * @see #createMessageSource
 */
@Override
@Nullable
public Theme getTheme(String themeName) {
	Theme theme = this.themeCache.get(themeName);
	if (theme == null) {
		synchronized (this.themeCache) {
			theme = this.themeCache.get(themeName);
			if (theme == null) {
				String basename = this.basenamePrefix + themeName;
				MessageSource messageSource = createMessageSource(basename);
				theme = new SimpleTheme(themeName, messageSource);
				initParent(theme);
				this.themeCache.put(themeName, theme);
				if (logger.isDebugEnabled()) {
					logger.debug("Theme created: name '" + themeName + "', basename [" + basename + "]");
				}
			}
		}
	}
	return theme;
}
 
Example 13
Source Project: spring-fu   Source File: ApplicationDslTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void createAnEmptyApplicationAndCheckMessageSource() {
	var app = application(a -> {});
	var context = app.run();
	assertFalse(context instanceof ReactiveWebServerApplicationContext);
	var messageSource = context.getBean(MessageSource.class);
	assertEquals("Spring Fu!", messageSource.getMessage("sample.message", null, Locale.getDefault()));
	context.close();
}
 
Example 14
Source Project: java-technology-stack   Source File: Service.java    License: MIT License 5 votes vote down vote up
@Override
public void setMessageSource(MessageSource messageSource) {
	if (this.messageSource != null) {
		throw new IllegalArgumentException("MessageSource should not be set twice");
	}
	this.messageSource = messageSource;
}
 
Example 15
@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource source = new ResourceBundleMessageSource();
    source.setBasename("templated_messages");

    return source;
}
 
Example 16
Source Project: distributed-transaction-process   Source File: UtilConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean(MessageSource source) {
    MethodInvokingFactoryBean bean = new MethodInvokingFactoryBean();
    bean.setTargetClass(CheckUtil.class);
    bean.setTargetMethod("setSource");
    bean.setArguments(new Object[]{ source });
    return bean;
}
 
Example 17
/**
 * Create a MessageSource for the given basename,
 * to be used as MessageSource for the corresponding theme.
 * <p>Default implementation creates a ResourceBundleMessageSource.
 * for the given basename. A subclass could create a specifically
 * configured ReloadableResourceBundleMessageSource, for example.
 * @param basename the basename to create a MessageSource for
 * @return the MessageSource
 * @see org.springframework.context.support.ResourceBundleMessageSource
 * @see org.springframework.context.support.ReloadableResourceBundleMessageSource
 */
protected MessageSource createMessageSource(String basename) {
	ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
	messageSource.setBasename(basename);
	if (this.defaultEncoding != null) {
		messageSource.setDefaultEncoding(this.defaultEncoding);
	}
	if (this.fallbackToSystemLocale != null) {
		messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
	}
	if (this.beanClassLoader != null) {
		messageSource.setBeanClassLoader(this.beanClassLoader);
	}
	return messageSource;
}
 
Example 18
Source Project: spring-analysis-note   Source File: SimpleTheme.java    License: MIT License 5 votes vote down vote up
/**
 * Create a SimpleTheme.
 * @param name the name of the theme
 * @param messageSource the MessageSource that resolves theme messages
 */
public SimpleTheme(String name, MessageSource messageSource) {
	Assert.notNull(name, "Name must not be null");
	Assert.notNull(messageSource, "MessageSource must not be null");
	this.name = name;
	this.messageSource = messageSource;
}
 
Example 19
Source Project: spring-analysis-note   Source File: ResourceBundleThemeSource.java    License: MIT License 5 votes vote down vote up
/**
 * Create a MessageSource for the given basename,
 * to be used as MessageSource for the corresponding theme.
 * <p>Default implementation creates a ResourceBundleMessageSource.
 * for the given basename. A subclass could create a specifically
 * configured ReloadableResourceBundleMessageSource, for example.
 * @param basename the basename to create a MessageSource for
 * @return the MessageSource
 * @see org.springframework.context.support.ResourceBundleMessageSource
 * @see org.springframework.context.support.ReloadableResourceBundleMessageSource
 */
protected MessageSource createMessageSource(String basename) {
	ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
	messageSource.setBasename(basename);
	if (this.defaultEncoding != null) {
		messageSource.setDefaultEncoding(this.defaultEncoding);
	}
	if (this.fallbackToSystemLocale != null) {
		messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
	}
	if (this.beanClassLoader != null) {
		messageSource.setBeanClassLoader(this.beanClassLoader);
	}
	return messageSource;
}
 
Example 20
@Test
public void testBeanAutowiredWithAnnotationConfigEnabled() {
	GenericApplicationContext context = new GenericApplicationContext();
	context.registerBeanDefinition("myBf", new RootBeanDefinition(StaticListableBeanFactory.class));
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setBeanNameGenerator(new TestBeanNameGenerator());
	int beanCount = scanner.scan(BASE_PACKAGE);
	assertEquals(12, beanCount);
	context.refresh();

	FooServiceImpl fooService = context.getBean("fooService", FooServiceImpl.class);
	StaticListableBeanFactory myBf = (StaticListableBeanFactory) context.getBean("myBf");
	MessageSource ms = (MessageSource) context.getBean("messageSource");
	assertTrue(fooService.isInitCalled());
	assertEquals("bar", fooService.foo(123));
	assertEquals("bar", fooService.lookupFoo(123));
	assertSame(context.getDefaultListableBeanFactory(), fooService.beanFactory);
	assertEquals(2, fooService.listableBeanFactory.size());
	assertSame(context.getDefaultListableBeanFactory(), fooService.listableBeanFactory.get(0));
	assertSame(myBf, fooService.listableBeanFactory.get(1));
	assertSame(context, fooService.resourceLoader);
	assertSame(context, fooService.resourcePatternResolver);
	assertSame(context, fooService.eventPublisher);
	assertSame(ms, fooService.messageSource);
	assertSame(context, fooService.context);
	assertEquals(1, fooService.configurableContext.length);
	assertSame(context, fooService.configurableContext[0]);
	assertSame(context, fooService.genericContext);
}
 
Example 21
Source Project: java-technology-stack   Source File: JstlUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Exposes JSTL-specific request attributes specifying locale
 * and resource bundle for JSTL's formatting and message tags,
 * using Spring's locale and MessageSource.
 * @param requestContext the context for the current HTTP request,
 * including the ApplicationContext to expose as MessageSource
 */
public static void exposeLocalizationContext(RequestContext requestContext) {
	Config.set(requestContext.getRequest(), Config.FMT_LOCALE, requestContext.getLocale());
	TimeZone timeZone = requestContext.getTimeZone();
	if (timeZone != null) {
		Config.set(requestContext.getRequest(), Config.FMT_TIME_ZONE, timeZone);
	}
	MessageSource messageSource = getJstlAwareMessageSource(
			requestContext.getServletContext(), requestContext.getMessageSource());
	LocalizationContext jstlContext = new SpringLocalizationContext(messageSource, requestContext.getRequest());
	Config.set(requestContext.getRequest(), Config.FMT_LOCALIZATION_CONTEXT, jstlContext);
}
 
Example 22
@Test
public void testMessageSourceAware() {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_WILDCARD);
	MessageSource messageSource = (MessageSource) ctx.getBean("messageSource");
	Service service1 = (Service) ctx.getBean("service");
	assertEquals(ctx, service1.getMessageSource());
	Service service2 = (Service) ctx.getBean("service2");
	assertEquals(ctx, service2.getMessageSource());
	AutowiredService autowiredService1 = (AutowiredService) ctx.getBean("autowiredService");
	assertEquals(messageSource, autowiredService1.getMessageSource());
	AutowiredService autowiredService2 = (AutowiredService) ctx.getBean("autowiredService2");
	assertEquals(messageSource, autowiredService2.getMessageSource());
	ctx.close();
}
 
Example 23
Source Project: lams   Source File: JstlUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Exposes JSTL-specific request attributes specifying locale
 * and resource bundle for JSTL's formatting and message tags,
 * using Spring's locale and MessageSource.
 * @param request the current HTTP request
 * @param messageSource the MessageSource to expose,
 * typically the current ApplicationContext (may be {@code null})
 * @see #exposeLocalizationContext(RequestContext)
 */
public static void exposeLocalizationContext(HttpServletRequest request, MessageSource messageSource) {
	Locale jstlLocale = RequestContextUtils.getLocale(request);
	Config.set(request, Config.FMT_LOCALE, jstlLocale);
	TimeZone timeZone = RequestContextUtils.getTimeZone(request);
	if (timeZone != null) {
		Config.set(request, Config.FMT_TIME_ZONE, timeZone);
	}
	if (messageSource != null) {
		LocalizationContext jstlContext = new SpringLocalizationContext(messageSource, request);
		Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, jstlContext);
	}
}
 
Example 24
Source Project: Full-Stack-Development-with-JHipster   Source File: MailService.java    License: MIT License 5 votes vote down vote up
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender,
        MessageSource messageSource, SpringTemplateEngine templateEngine) {

    this.jHipsterProperties = jHipsterProperties;
    this.javaMailSender = javaMailSender;
    this.messageSource = messageSource;
    this.templateEngine = templateEngine;
}
 
Example 25
Source Project: spring-analysis-note   Source File: JstlUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Exposes JSTL-specific request attributes specifying locale
 * and resource bundle for JSTL's formatting and message tags,
 * using Spring's locale and MessageSource.
 * @param request the current HTTP request
 * @param messageSource the MessageSource to expose,
 * typically the current ApplicationContext (may be {@code null})
 * @see #exposeLocalizationContext(RequestContext)
 */
public static void exposeLocalizationContext(HttpServletRequest request, @Nullable MessageSource messageSource) {
	Locale jstlLocale = RequestContextUtils.getLocale(request);
	Config.set(request, Config.FMT_LOCALE, jstlLocale);
	TimeZone timeZone = RequestContextUtils.getTimeZone(request);
	if (timeZone != null) {
		Config.set(request, Config.FMT_TIME_ZONE, timeZone);
	}
	if (messageSource != null) {
		LocalizationContext jstlContext = new SpringLocalizationContext(messageSource, request);
		Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, jstlContext);
	}
}
 
Example 26
Source Project: spring-analysis-note   Source File: JstlUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Exposes JSTL-specific request attributes specifying locale
 * and resource bundle for JSTL's formatting and message tags,
 * using Spring's locale and MessageSource.
 * @param requestContext the context for the current HTTP request,
 * including the ApplicationContext to expose as MessageSource
 */
public static void exposeLocalizationContext(RequestContext requestContext) {
	Config.set(requestContext.getRequest(), Config.FMT_LOCALE, requestContext.getLocale());
	TimeZone timeZone = requestContext.getTimeZone();
	if (timeZone != null) {
		Config.set(requestContext.getRequest(), Config.FMT_TIME_ZONE, timeZone);
	}
	MessageSource messageSource = getJstlAwareMessageSource(
			requestContext.getServletContext(), requestContext.getMessageSource());
	LocalizationContext jstlContext = new SpringLocalizationContext(messageSource, requestContext.getRequest());
	Config.set(requestContext.getRequest(), Config.FMT_LOCALIZATION_CONTEXT, jstlContext);
}
 
Example 27
Source Project: java-technology-stack   Source File: MessageTag.java    License: MIT License 5 votes vote down vote up
/**
 * Resolve the specified message into a concrete message String.
 * The returned message String should be unescaped.
 */
protected String resolveMessage() throws JspException, NoSuchMessageException {
	MessageSource messageSource = getMessageSource();

	// Evaluate the specified MessageSourceResolvable, if any.
	if (this.message != null) {
		// We have a given MessageSourceResolvable.
		return messageSource.getMessage(this.message, getRequestContext().getLocale());
	}

	if (this.code != null || this.text != null) {
		// We have a code or default text that we need to resolve.
		Object[] argumentsArray = resolveArguments(this.arguments);
		if (!this.nestedArguments.isEmpty()) {
			argumentsArray = appendArguments(argumentsArray, this.nestedArguments.toArray());
		}

		if (this.text != null) {
			// We have a fallback text to consider.
			String msg = messageSource.getMessage(
					this.code, argumentsArray, this.text, getRequestContext().getLocale());
			return (msg != null ? msg : "");
		}
		else {
			// We have no fallback text to consider.
			return messageSource.getMessage(
					this.code, argumentsArray, getRequestContext().getLocale());
		}
	}

	throw new JspTagException("No resolvable message");
}
 
Example 28
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 29
@Bean
public WebErrorHandlers webErrorHandlers(MessageSource messageSource) {
    return WebErrorHandlers.builder(messageSource)
        .withErrorHandlers(new First())
        .withDefaultWebErrorHandler(new Sec())
        .build();
}
 
Example 30
Source Project: n2o-framework   Source File: N2oMessagesConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean("n2oMessageSource")
@ConditionalOnMissingBean(name = "n2oMessageSource")
public MessageSource n2oMessageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setDefaultEncoding(encoding.name());
    messageSource.setCacheSeconds(cacheSeconds);
    messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
            StringUtils.trimAllWhitespace(basename)));
    messageSource.addBasenames("n2o_messages", "n2o_content");
    return messageSource;
}