Java Code Examples for org.springframework.context.MessageSource#getMessage()

The following examples show how to use org.springframework.context.MessageSource#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractMessageSource.java    From lams with 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
Source File: JsonResult.java    From match-trade with 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 3
Source File: MessageSourceUtil.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * 查找错误消息
 *
 * @param source
 * @param code
 * @param params
 * @param defaultMsg
 *
 * @return
 */
public static int getIntMessage(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[]{};
    }
    String message = null;

    if (Check.isNullOrEmpty(defaultMsg)) {
        message = source.getMessage(code, params, Locale.SIMPLIFIED_CHINESE);
    } else {
        message = source.getMessage(code, params, defaultMsg, Locale.SIMPLIFIED_CHINESE);
    }
    if (Check.isNullOrEmpty(message)) {
        throw new NumberFormatException("message is empty");
    } else {
        return Integer.valueOf(message);
    }
}
 
Example 4
Source File: MessageSourceUtil.java    From AsuraFramework with 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 5
Source File: ValidatorDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // 1. 创建 Validator
    Validator validator = new UserValidator();
    // 2. 判断是否支持目标对象的类型
    User user = new User();
    System.out.println("user 对象是否被 UserValidator 支持检验:" + validator.supports(user.getClass()));
    // 3. 创建 Errors 对象
    Errors errors = new BeanPropertyBindingResult(user, "user");
    validator.validate(user, errors);

    // 4. 获取 MessageSource 对象
    MessageSource messageSource = createMessageSource();

    // 5. 输出所有的错误文案
    for (ObjectError error : errors.getAllErrors()) {
        String message = messageSource.getMessage(error.getCode(), error.getArguments(), Locale.getDefault());
        System.out.println(message);
    }
}
 
Example 6
Source File: MessageSourceUtil.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * 查找错误消息
 *
 * @param source
 * @param code
 * @param params
 * @param defaultMsg
 * @return
 */
public static int getIntMessage(MessageSource source, String code, Object[] params, String defaultMsg) {
    if (Check.NuNObj(source)) {
        throw new IllegalArgumentException("message source is null");
    }
    if (Check.NuNStrStrict(code)) {
        throw new IllegalArgumentException("code is empty");
    }
    //如果没有object 默认设置为空数组
    if (Check.NuNObj(params)) {
        params = new Object[]{};
    }
    String message = null;

    if (Check.NuNStrStrict(defaultMsg)) {
        message = source.getMessage(code, params, Locale.SIMPLIFIED_CHINESE);
    } else {
        message = source.getMessage(code, params, defaultMsg, Locale.SIMPLIFIED_CHINESE);
    }
    if (Check.NuNStrStrict(message)) {
        throw new NumberFormatException("message is empty");
    } else {
        return Integer.valueOf(message);
    }
}
 
Example 7
Source File: AbstractMessageSource.java    From java-technology-stack with 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 8
Source File: LearningDesignService.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
   public String internationaliseActivityTitle(Long learningLibraryID) {

ToolActivity templateActivity = (ToolActivity) activityDAO.getTemplateActivityByLibraryID(learningLibraryID);

if (templateActivity != null) {
    Locale locale = LocaleContextHolder.getLocale();
    String languageFilename = templateActivity.getLanguageFile();
    if (languageFilename != null) {
	MessageSource toolMessageSource = toolActMessageService.getMessageService(languageFilename);
	if (toolMessageSource != null) {
	    String title = toolMessageSource.getMessage(Activity.I18N_TITLE, null, templateActivity.getTitle(),
		    locale);
	    if (title != null && title.trim().length() > 0) {
		return title;
	    }
	} else {
	    log.warn("Unable to internationalise the library activity " + templateActivity.getTitle()
		    + " message file " + templateActivity.getLanguageFile()
		    + ". Activity Message source not available");
	}
    }
}

if (templateActivity.getTitle() != null && templateActivity.getTitle().trim().length() > 0) {
    return templateActivity.getTitle();
} else {
    return "Untitled"; // should never get here - just return something in case there is a bug. A blank title affect the layout of the main page
}
   }
 
Example 9
Source File: OutputFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Get the I18N description for this key. If the tool has supplied a messageService, then this is used to look up
    * the key and hence get the text. Otherwise if the tool has supplied a I18N languageFilename then it is accessed
    * via the shared toolActMessageService. If neither are supplied or the key is not found, then any "." in the name
    * are converted to space and this is used as the return value.
    *
    * This is normally used to get the description for a definition, in whic case the key should be in the format
    * output.desc.[definition name], key = definition name and addPrefix = true. For example a definition name of
    * "learner.mark" becomes output.desc.learner.mark.
    *
    * If you want to use this to get an arbitrary string from the I18N files, then set addPrefix = false and the
    * output.desc will not be added to the beginning.
    */
   protected String getI18NText(String key, boolean addPrefix) {
String translatedText = null;

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

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

return translatedText;
   }
 
Example 10
Source File: MessageTag.java    From lams with GNU General Public License v2.0 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();
	if (messageSource == null) {
		throw new JspTagException("No corresponding MessageSource found");
	}

	// 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.
			return messageSource.getMessage(
					this.code, argumentsArray, this.text, getRequestContext().getLocale());
		}
		else {
			// We have no fallback text to consider.
			return messageSource.getMessage(
					this.code, argumentsArray, getRequestContext().getLocale());
		}
	}

	// All we have is a specified literal text.
	return this.text;
}
 
Example 11
Source File: Patch0016FixWorkspacePublicFolder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String getI18nMessage(Connection conn) throws MigrationException {
// get spring bean
ApplicationContext context = new ClassPathXmlApplicationContext("org/lamsfoundation/lams/messageContext.xml");
MessageService messageService = (MessageService) context.getBean("commonMessageService");

// get server locale
String defaultLocale = "en_AU";
String getDefaultLocaleStmt = "select config_value from lams_configuration where config_key='ServerLanguage'";
try {
    PreparedStatement query = conn.prepareStatement(getDefaultLocaleStmt);
    ResultSet results = query.executeQuery();
    while (results.next()) {
	defaultLocale = results.getString("config_value");
    }
} catch (Exception e) {
    throw new MigrationException("Problem running update; ", e);
}

String[] tokenisedLocale = defaultLocale.split("_");
Locale locale = new Locale(tokenisedLocale[0], tokenisedLocale[1]);

// get i18n'd message for text 'run sequences'
MessageSource messageSource = messageService.getMessageSource();
String i18nMessage = messageSource.getMessage("public.folder.name", null, locale);

if (i18nMessage != null && i18nMessage.startsWith("???")) {
    // default to English if not present
    return "Public Folder";
}
return i18nMessage;
   }
 
Example 12
Source File: I18nTransformUtil.java    From scaffold-cloud with MIT License 5 votes vote down vote up
/**
 * 根据model.name以及当前语言获取到对应的值
 * @param i18nName
 * @return
 */
public static String transFormString(String i18nName){
    MessageSource messageSource = SpringContextHolder.getBean("messageSource");
    String source = messageSource.getMessage(i18nName, null, LocaleContextHolder.getLocale());
    if(source.equals(i18nName)){
        log.warn("i18n:{}对应的国际化配置在数据库不存在,请检查!", i18nName);
    }
    return source;
}
 
Example 13
Source File: MessageTag.java    From spring-analysis-note with 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 14
Source File: Patch0012FixWorkspaceNames.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String getI18nMessage(Connection conn) throws MigrationException {
// get spring bean
ApplicationContext context = new ClassPathXmlApplicationContext("org/lamsfoundation/lams/messageContext.xml");
MessageService messageService = (MessageService) context.getBean("commonMessageService");

// get server locale
String defaultLocale = "en_AU";
String getDefaultLocaleStmt = "select config_value from lams_configuration where config_key='ServerLanguage'";
try {
    PreparedStatement query = conn.prepareStatement(getDefaultLocaleStmt);
    ResultSet results = query.executeQuery();
    while (results.next()) {
	defaultLocale = results.getString("config_value");
    }
} catch (Exception e) {
    throw new MigrationException("Problem running update; ", e);
}

String[] tokenisedLocale = defaultLocale.split("_");
Locale locale = new Locale(tokenisedLocale[0], tokenisedLocale[1]);

// get i18n'd message for text 'run sequences'
MessageSource messageSource = messageService.getMessageSource();
String i18nMessage = messageSource.getMessage("runsequences.folder.name", new Object[] { "" }, locale);

if (i18nMessage != null && i18nMessage.startsWith("???")) {
    // default to English if not present
    return " Run Sequences";
}
return i18nMessage;
   }
 
Example 15
Source File: CleanstoneServer.java    From Cleanstone with MIT License 4 votes vote down vote up
public static String getMessageOfLocale(String id, Locale locale, Object... args) {
    MessageSource source = getInstance().getMessageSource();
    String defaultMessage = locale == DEFAULT_LOCALE ? null : source.getMessage(id, args, DEFAULT_LOCALE);
    String message = source.getMessage(id, args, defaultMessage, locale);
    return message != null ? message : "Error: Cannot find message with id " + id;
}
 
Example 16
Source File: MessageUtils.java    From ruoyiplus with MIT License 2 votes vote down vote up
/**
 * 根据消息键和参数 获取消息 委托给spring messageSource
 *
 * @param code 消息键
 * @param args 参数
 * @return
 */
public static String message(String code, Object... args)
{
    MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
    return messageSource.getMessage(code, args, null);
}
 
Example 17
Source File: MessageUtils.java    From RuoYi with Apache License 2.0 2 votes vote down vote up
/**
 * 根据消息键和参数 获取消息 委托给spring messageSource
 *
 * @param code 消息键
 * @param args 参数
 * @return 国际化翻译值
 */
public static String message(String code, Object... args) {
    MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
    return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}
 
Example 18
Source File: MessageUtils.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * 根据消息键和参数 获取消息 委托给spring messageSource
 *
 * @param code 消息键
 * @param args 参数
 */
public static String message(String code, Object... args)
{
    MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
    return messageSource.getMessage(code, args, null);
}
 
Example 19
Source File: MessageUtils.java    From RuoYi-Vue with MIT License 2 votes vote down vote up
/**
 * 根据消息键和参数 获取消息 委托给spring messageSource
 *
 * @param code 消息键
 * @param args 参数
 * @return 获取国际化翻译值
 */
public static String message(String code, Object... args)
{
    MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
    return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}
 
Example 20
Source File: MessageUtils.java    From supplierShop with MIT License 2 votes vote down vote up
/**
 * 根据消息键和参数 获取消息 委托给spring messageSource
 *
 * @param code 消息键
 * @param args 参数
 * @return 获取国际化翻译值
 */
public static String message(String code, Object... args)
{
    MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
    return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}