org.springframework.context.NoSuchMessageException Java Examples

The following examples show how to use org.springframework.context.NoSuchMessageException. 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: MessageCodesResolver.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * プロパティ名を解決します。
 * @param key リソース検索キー
 * @return プロパティ名
 */
protected static String resolve(String key) {
    String msg = Rs.find(key);
    if (key.equals(msg)) {
        if (DOMAIN_SUFFIXES != null) {
            for (String suffix : DOMAIN_SUFFIXES) {
                String replaceKey = key.replace(suffix, "");
                try {
                    msg = find(replaceKey);
                } catch (NoSuchMessageException e) {
                    L.debug(Strings.substitute(R.getString("D-MESSAGE_RESOLVER#0001"), Maps.hash("replaceKey", replaceKey)));
                    continue;
                }
            }
        }
    }
    return msg;
}
 
Example #2
Source File: ResourceBundleMessageSourceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testReloadableResourceBundleMessageSourceWithInappropriateDefaultCharset() {
	ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource();
	ms.setBasename("org/springframework/context/support/messages");
	ms.setDefaultEncoding("unicode");
	Properties fileCharsets = new Properties();
	fileCharsets.setProperty("org/springframework/context/support/messages_de", "unicode");
	ms.setFileEncodings(fileCharsets);
	ms.setFallbackToSystemLocale(false);
	try {
		ms.getMessage("code1", null, Locale.ENGLISH);
		fail("Should have thrown NoSuchMessageException");
	}
	catch (NoSuchMessageException ex) {
		// expected
	}
}
 
Example #3
Source File: ResourceBundleMessageSourceTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testReloadableResourceBundleMessageSourceWithInappropriateEnglishCharset() {
	ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource();
	ms.setBasename("org/springframework/context/support/messages");
	ms.setFallbackToSystemLocale(false);
	Properties fileCharsets = new Properties();
	fileCharsets.setProperty("org/springframework/context/support/messages", "unicode");
	ms.setFileEncodings(fileCharsets);
	try {
		ms.getMessage("code1", null, Locale.ENGLISH);
		fail("Should have thrown NoSuchMessageException");
	}
	catch (NoSuchMessageException ex) {
		// expected
	}
}
 
Example #4
Source File: StaticMessageSourceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void messageSourceResolvable() {
	// first code valid
	String[] codes1 = new String[] {"message.format.example3", "message.format.example2"};
	MessageSourceResolvable resolvable1 = new DefaultMessageSourceResolvable(codes1, null, "default");
	assertTrue("correct message retrieved", MSG_TXT3_US.equals(sac.getMessage(resolvable1, Locale.US)));

	// only second code valid
	String[] codes2 = new String[] {"message.format.example99", "message.format.example2"};
	MessageSourceResolvable resolvable2 = new DefaultMessageSourceResolvable(codes2, null, "default");
	assertTrue("correct message retrieved", MSG_TXT2_US.equals(sac.getMessage(resolvable2, Locale.US)));

	// no code valid, but default given
	String[] codes3 = new String[] {"message.format.example99", "message.format.example98"};
	MessageSourceResolvable resolvable3 = new DefaultMessageSourceResolvable(codes3, null, "default");
	assertTrue("correct message retrieved", "default".equals(sac.getMessage(resolvable3, Locale.US)));

	// no code valid, no default
	String[] codes4 = new String[] {"message.format.example99", "message.format.example98"};
	MessageSourceResolvable resolvable4 = new DefaultMessageSourceResolvable(codes4);

	exception.expect(NoSuchMessageException.class);
	sac.getMessage(resolvable4, Locale.US);
}
 
Example #5
Source File: AbstractMessageSource.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public final String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
	String[] codes = resolvable.getCodes();
	if (codes != null) {
		for (String code : codes) {
			String message = getMessageInternal(code, resolvable.getArguments(), locale);
			if (message != null) {
				return message;
			}
		}
	}
	String defaultMessage = getDefaultMessage(resolvable, locale);
	if (defaultMessage != null) {
		return defaultMessage;
	}
	throw new NoSuchMessageException(!ObjectUtils.isEmpty(codes) ? codes[codes.length - 1] : "", locale);
}
 
Example #6
Source File: ResourceBundleMessageSourceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testReloadableResourceBundleMessageSourceWithInappropriateDefaultCharset() {
	ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource();
	ms.setBasename("org/springframework/context/support/messages");
	ms.setDefaultEncoding("unicode");
	Properties fileCharsets = new Properties();
	fileCharsets.setProperty("org/springframework/context/support/messages_de", "unicode");
	ms.setFileEncodings(fileCharsets);
	ms.setFallbackToSystemLocale(false);
	try {
		ms.getMessage("code1", null, Locale.ENGLISH);
		fail("Should have thrown NoSuchMessageException");
	}
	catch (NoSuchMessageException ex) {
		// expected
	}
}
 
Example #7
Source File: BindStatus.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Extract the error messages from the ObjectError list.
 */
private String[] initErrorMessages() throws NoSuchMessageException {
	if (this.errorMessages == null) {
		if (this.objectErrors != null) {
			this.errorMessages = new String[this.objectErrors.size()];
			for (int i = 0; i < this.objectErrors.size(); i++) {
				ObjectError error = this.objectErrors.get(i);
				this.errorMessages[i] = this.requestContext.getMessage(error, this.htmlEscape);
			}
		}
		else {
			this.errorMessages = new String[0];
		}
	}
	return this.errorMessages;
}
 
Example #8
Source File: XmlWebApplicationContextTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void withoutMessageSource() throws Exception {
	MockServletContext sc = new MockServletContext("");
	XmlWebApplicationContext wac = new XmlWebApplicationContext();
	wac.setParent(root);
	wac.setServletContext(sc);
	wac.setNamespace("testNamespace");
	wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"});
	wac.refresh();
	try {
		wac.getMessage("someMessage", null, Locale.getDefault());
		fail("Should have thrown NoSuchMessageException");
	}
	catch (NoSuchMessageException ex) {
		// expected;
	}
	String msg = wac.getMessage("someMessage", null, "default", Locale.getDefault());
	assertTrue("Default message returned", "default".equals(msg));
}
 
Example #9
Source File: StaticMessageSourceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void messageSourceResolvable() {
	// first code valid
	String[] codes1 = new String[] {"message.format.example3", "message.format.example2"};
	MessageSourceResolvable resolvable1 = new DefaultMessageSourceResolvable(codes1, null, "default");
	assertTrue("correct message retrieved", MSG_TXT3_US.equals(sac.getMessage(resolvable1, Locale.US)));

	// only second code valid
	String[] codes2 = new String[] {"message.format.example99", "message.format.example2"};
	MessageSourceResolvable resolvable2 = new DefaultMessageSourceResolvable(codes2, null, "default");
	assertTrue("correct message retrieved", MSG_TXT2_US.equals(sac.getMessage(resolvable2, Locale.US)));

	// no code valid, but default given
	String[] codes3 = new String[] {"message.format.example99", "message.format.example98"};
	MessageSourceResolvable resolvable3 = new DefaultMessageSourceResolvable(codes3, null, "default");
	assertTrue("correct message retrieved", "default".equals(sac.getMessage(resolvable3, Locale.US)));

	// no code valid, no default
	String[] codes4 = new String[] {"message.format.example99", "message.format.example98"};
	MessageSourceResolvable resolvable4 = new DefaultMessageSourceResolvable(codes4);

	exception.expect(NoSuchMessageException.class);
	sac.getMessage(resolvable4, Locale.US);
}
 
Example #10
Source File: AbstractMessageSource.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public final String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
	String[] codes = resolvable.getCodes();
	if (codes != null) {
		for (String code : codes) {
			String message = getMessageInternal(code, resolvable.getArguments(), locale);
			if (message != null) {
				return message;
			}
		}
	}
	String defaultMessage = getDefaultMessage(resolvable, locale);
	if (defaultMessage != null) {
		return defaultMessage;
	}
	throw new NoSuchMessageException(!ObjectUtils.isEmpty(codes) ? codes[codes.length - 1] : "", locale);
}
 
Example #11
Source File: BindStatus.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Extract the error messages from the ObjectError list.
 */
private String[] initErrorMessages() throws NoSuchMessageException {
	if (this.errorMessages == null) {
		if (this.objectErrors != null) {
			this.errorMessages = new String[this.objectErrors.size()];
			for (int i = 0; i < this.objectErrors.size(); i++) {
				ObjectError error = this.objectErrors.get(i);
				this.errorMessages[i] = this.requestContext.getMessage(error, this.htmlEscape);
			}
		}
		else {
			this.errorMessages = new String[0];
		}
	}
	return this.errorMessages;
}
 
Example #12
Source File: I18nTransformUtil.java    From scaffold-cloud with MIT License 6 votes vote down vote up
/**
 * @param object    需要被转换的对象 需要有i18nNid属性 存储标识
 * @param fieldName 需要被转换的字段名
 * @param <T>       泛型
 * @return 原对象转换后
 */
public static <T> T transForm(T object, String fieldName) {
    Object i18nId = ReflectUtil.getFieldValue(object, "i18nNid");
    MessageSource messageSource = SpringContextHolder.getBean("messageSource");
    if (Objects.nonNull(i18nId)) {
        String name = null;
        try {
            name = messageSource.getMessage(i18nId.toString(), null, LocaleContextHolder.getLocale());
            if (StrUtil.isNotBlank(name)) {
                if(name.equals(i18nId)){
                    log.warn("i18n:{}对应的国际化配置在数据库不存在,请检查!", i18nId);
                }else{
                    ReflectUtil.setFieldValue(object, fieldName, name);
                }
            }else{
                log.warn("获取的国际化属性{}不合法,i18nNid:{},语言:{}", fieldName, i18nId, LocaleContextHolder.getLocale());
            }
        } catch (NoSuchMessageException e) {
            log.error("NoSuchMessageException=> 国际化属性{}不合法,i18nNid:{},语言:{}", fieldName, i18nId, LocaleContextHolder.getLocale());
        }
    } else {
        log.warn("存在不合法的i18nId");
    }
    return object;
}
 
Example #13
Source File: JsonObjectUtils.java    From disconf with Apache License 2.0 6 votes vote down vote up
/**
 * 参数错误: Field
 *
 * @param errors
 *
 * @return
 */
public static JsonObjectBase buildFieldError(Map<String, String> errors, Map<String, Object[]> argsMap,
                                             ErrorCode statusCode) {

    JsonObjectError json = new JsonObjectError();
    json.setStatus(statusCode.getCode());

    for (String str : errors.keySet()) {

        try {
            json.addFieldError(str, contextReader.getMessage(errors.get(str), argsMap.get(str)));
        } catch (NoSuchMessageException e) {
            json.addFieldError(str, errors.get(str));
        }
    }

    LOG.info(json.toString());

    return json;
}
 
Example #14
Source File: MessageService.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * @see org.springframework.context.support.MessageSourceAccessor#getMessage(java.lang.String, java.lang.String)
    * @param key
    * @param defaultMessage
    * @return
    */
   public String getMessage(String key, String defaultMessage) {
String message = defaultMessage;
try {
    message = messageSource.getMessage(key, null, defaultMessage, LocaleContextHolder.getLocale());
} catch (NoSuchMessageException e) {
    message = defaultMessage;
}
return message;
   }
 
Example #15
Source File: AbstractMessageSource.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public final String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException {
	String msg = getMessageInternal(code, args, locale);
	if (msg != null) {
		return msg;
	}
	String fallback = getDefaultMessage(code);
	if (fallback != null) {
		return fallback;
	}
	throw new NoSuchMessageException(code, locale);
}
 
Example #16
Source File: AbstractMessageSource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException {
	String msg = getMessageInternal(code, args, locale);
	if (msg != null) {
		return msg;
	}
	String fallback = getDefaultMessage(code);
	if (fallback != null) {
		return fallback;
	}
	throw new NoSuchMessageException(code, locale);
}
 
Example #17
Source File: LanguageService.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** @deprecated Use {@link MessageSourceHolder} and {@link LocaleContextHolder} instead */
@Deprecated
public static Optional<String> formatMessage(String code, Object[] arguments) {
  try {
    return Optional.of(getMessageSource().getMessage(code, arguments, getLocale()));
  } catch (NoSuchMessageException ex) {
    return Optional.empty();
  }
}
 
Example #18
Source File: ConsoleExceptionUtils.java    From pgptool with GNU General Public License v3.0 5 votes vote down vote up
private static Object tryFindTranslation(String fieldToken, Locale locale) {
	try {
		return ac().getMessage(fieldToken, null, locale);
	} catch (NoSuchMessageException nfe) {
		try {
			return ac().getMessage("term." + fieldToken, null, locale);
		} catch (NoSuchMessageException nfe2) {
			return fieldToken;
		}
	}
}
 
Example #19
Source File: GlobalMessageSource.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
public String getNameByCode(String code) {
    try {
        return getMessage(code, null, Locale.getDefault());
    } catch (NoSuchMessageException e) {
        log.warn("name by code '" + code + "' not found in package " + namesPackage);
        return code;
    }
}
 
Example #20
Source File: MessageSourceResourceBundle.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This implementation resolves the code in the MessageSource.
 * Returns {@code null} if the message could not be resolved.
 */
@Override
protected Object handleGetObject(String key) {
	try {
		return this.messageSource.getMessage(key, null, this.locale);
	}
	catch (NoSuchMessageException ex) {
		return null;
	}
}
 
Example #21
Source File: DelegatingMessageSource.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
	if (this.parentMessageSource != null) {
		return this.parentMessageSource.getMessage(resolvable, locale);
	}
	else {
		if (resolvable.getDefaultMessage() != null) {
			return renderDefaultMessage(resolvable.getDefaultMessage(), resolvable.getArguments(), locale);
		}
		String[] codes = resolvable.getCodes();
		String code = (codes != null && codes.length > 0 ? codes[0] : "");
		throw new NoSuchMessageException(code, locale);
	}
}
 
Example #22
Source File: SpringContextHelper.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the message translation for a code, in the {@link Locale} of the
 * current request.
 * 
 * @param pageContext of the current request.
 * @param code to get the message
 * @return the translated message
 * @throws JspException if there is an error getting the message
 */
public String resolveMessage(PageContext pageContext, String code)
        throws JspException {
    RequestContext requestContext = getRequestContext(pageContext);
    if (requestContext == null) {
        throw new JspTagException("No corresponding RequestContext found");
    }
    MessageSource messageSource = requestContext.getMessageSource();
    if (messageSource == null) {
        throw new JspTagException("No corresponding MessageSource found");
    }

    String resolvedCode = ExpressionEvaluationUtils.evaluateString("code",
            code, pageContext);

    if (resolvedCode != null) {
        // We have no fallback text to consider.
        try {
            return messageSource.getMessage(resolvedCode, null,
                    requestContext.getLocale());
        }
        catch (NoSuchMessageException e) {
            LOG.warn("Unable to get message with code " + resolvedCode, e);
        }
    }

    return resolvedCode;
}
 
Example #23
Source File: DelegatingMessageSource.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException {
	if (this.parentMessageSource != null) {
		return this.parentMessageSource.getMessage(code, args, locale);
	}
	else {
		throw new NoSuchMessageException(code, locale);
	}
}
 
Example #24
Source File: BindStatus.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extract the error messages from the ObjectError list.
 */
private void initErrorMessages() throws NoSuchMessageException {
	if (this.errorMessages == null) {
		this.errorMessages = new String[this.objectErrors.size()];
		for (int i = 0; i < this.objectErrors.size(); i++) {
			ObjectError error = this.objectErrors.get(i);
			this.errorMessages[i] = this.requestContext.getMessage(error, this.htmlEscape);
		}
	}
}
 
Example #25
Source File: EntityPropertiesServiceSpringImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public String getPropertyMessage(String key, Object[] args, Locale locale) {
    String msg;
    try {
        msg = getMessage(key, args, locale);
    } catch (NoSuchMessageException e) {
        throw new MissingResourceException("Cannot find key ("+key+"): " + e.getMessage(), 
                SpringMessageBundle.class.getName(), key);
    }
    return msg;
}
 
Example #26
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 #27
Source File: MessageSourceResourceBundle.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * This implementation resolves the code in the MessageSource.
 * Returns {@code null} if the message could not be resolved.
 */
@Override
@Nullable
protected Object handleGetObject(String key) {
	try {
		return this.messageSource.getMessage(key, null, this.locale);
	}
	catch (NoSuchMessageException ex) {
		return null;
	}
}
 
Example #28
Source File: DelegatingMessageSource.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
	if (this.parentMessageSource != null) {
		return this.parentMessageSource.getMessage(resolvable, locale);
	}
	else {
		if (resolvable.getDefaultMessage() != null) {
			return renderDefaultMessage(resolvable.getDefaultMessage(), resolvable.getArguments(), locale);
		}
		String[] codes = resolvable.getCodes();
		String code = (codes != null && codes.length > 0 ? codes[0] : null);
		throw new NoSuchMessageException(code, locale);
	}
}
 
Example #29
Source File: ThreadSafeClassPathXmlApplicationContext.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException {
    lock.readLock().lock();
    try {
        return configurableApplicationContext.getMessage(code, args, locale);
    } finally {
        lock.readLock().unlock();
    }
}
 
Example #30
Source File: MessageService.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * @see org.springframework.context.support.MessageSourceAccessor#getMessage(java.lang.String)
    * @param key
    * @return
    */
   public String getMessage(String key) {
String message;
try {
    message = messageSource.getMessage(key, null, LocaleContextHolder.getLocale());
} catch (NoSuchMessageException e) {
    message = "??" + key + "??";
}
return message;
   }