类org.springframework.context.MessageSource源码实例Demo

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

源代码1 项目: lams   文件: AbstractMessageSource.java
/**
 * 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;
}
 
/**
 * 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);
}
 
/**
 * 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;
}
 
/**
 * 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;
}
 
源代码5 项目: AsuraFramework   文件: MessageSourceUtil.java
/**
 * 查找错误消息
 *
 * @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);
    }
}
 
源代码6 项目: lams   文件: LoadedMessageSourceService.java
@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;
}
   }
 
源代码7 项目: spring-analysis-note   文件: RequestContext.java
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;
}
 
源代码8 项目: spring-analysis-note   文件: JstlUtils.java
/**
 * 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;
}
 
源代码9 项目: lams   文件: JstlUtils.java
/**
 * 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;
}
 
源代码10 项目: match-trade   文件: JsonResult.java
/**
 * <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;
}
 
源代码11 项目: GreenSummer   文件: SummerXSLTView.java
@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!");
        }
    }
}
 
/**
 * 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;
}
 
源代码13 项目: spring-fu   文件: ApplicationDslTests.java
@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();
}
 
源代码14 项目: java-technology-stack   文件: Service.java
@Override
public void setMessageSource(MessageSource messageSource) {
	if (this.messageSource != null) {
		throw new IllegalArgumentException("MessageSource should not be set twice");
	}
	this.messageSource = messageSource;
}
 
@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource source = new ResourceBundleMessageSource();
    source.setBasename("templated_messages");

    return source;
}
 
@Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean(MessageSource source) {
    MethodInvokingFactoryBean bean = new MethodInvokingFactoryBean();
    bean.setTargetClass(CheckUtil.class);
    bean.setTargetMethod("setSource");
    bean.setArguments(new Object[]{ source });
    return bean;
}
 
源代码17 项目: lams   文件: ResourceBundleThemeSource.java
/**
 * 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;
}
 
源代码18 项目: spring-analysis-note   文件: SimpleTheme.java
/**
 * 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;
}
 
/**
 * 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;
}
 
@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);
}
 
源代码21 项目: java-technology-stack   文件: JstlUtils.java
/**
 * 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);
}
 
@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();
}
 
源代码23 项目: lams   文件: JstlUtils.java
/**
 * 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);
	}
}
 
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender,
        MessageSource messageSource, SpringTemplateEngine templateEngine) {

    this.jHipsterProperties = jHipsterProperties;
    this.javaMailSender = javaMailSender;
    this.messageSource = messageSource;
    this.templateEngine = templateEngine;
}
 
源代码25 项目: spring-analysis-note   文件: JstlUtils.java
/**
 * 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);
	}
}
 
源代码26 项目: spring-analysis-note   文件: JstlUtils.java
/**
 * 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);
}
 
源代码27 项目: java-technology-stack   文件: MessageTag.java
/**
 * 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");
}
 
源代码28 项目: 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;
   }
 
@Bean
public WebErrorHandlers webErrorHandlers(MessageSource messageSource) {
    return WebErrorHandlers.builder(messageSource)
        .withErrorHandlers(new First())
        .withDefaultWebErrorHandler(new Sec())
        .build();
}
 
源代码30 项目: n2o-framework   文件: N2oMessagesConfiguration.java
@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;
}
 
 类方法
 同包方法