Example usage for org.springframework.context MessageSource getMessage

List of usage examples for org.springframework.context MessageSource getMessage

Introduction

In this page you can find the example usage for org.springframework.context MessageSource getMessage.

Prototype

String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException;

Source Link

Document

Try to resolve the message.

Usage

From source file:com.spring.tutorial.messages.App.java

public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext(
            "com/spring/tutorial/messages/applicationContext.xml");
    MessageSource ms = ctx.getBean(MessageSource.class);
    //Message resolution
    String success = ms.getMessage("msg.success", null, Locale.getDefault());
    String successEN = ms.getMessage("msg.success", null, Locale.ENGLISH);
    String successFR = ms.getMessage("msg.success", null, Locale.FRENCH);
    String successDE = ms.getMessage("msg.success", null, Locale.GERMAN);
    //Message resolution and i18n
    String label = ms.getMessage("lbl.result", null, Locale.getDefault());
    //Not necessary to pass the locale
    String error = ms.getMessage("err.failure", null, null);
    //Non-existent message (if the call does not specify, the default message argument,
    //and the message code does not exist, an exception will be thrown)
    String nonExistent = ms.getMessage("my.message", null, "Not found, defaults to this message", null);
    LOGGER.info("Success message (es - the default): " + success);
    LOGGER.info("Success message (en): " + successEN);
    LOGGER.info("Success message (fr): " + successFR);
    LOGGER.info("Success message (de) defaults to local language: " + successDE);
    LOGGER.info("Label text: " + label);
    LOGGER.info("Error message: " + error);
    LOGGER.info("Non-existent message (defaults to message specified as argument): " + nonExistent);
    ((ClassPathXmlApplicationContext) ctx).close();
}

From source file:info.jtrac.util.ItemUtils.java

private static String fmt(String key, MessageSource messageSource, Locale locale) {
    try {/* w w  w . j  av  a2 s  . c o m*/
        return messageSource.getMessage("item_view." + key, null, locale);
    } catch (Exception e) {
        return "???item_view." + key + "???";
    }
}

From source file:net.solarnetwork.node.runtime.JobSettingSpecifierProvider.java

private static boolean hasMessage(MessageSource source, String key) {
    if (source == null) {
        return false;
    }/* w  w w  . j  a  v  a 2s  . c  om*/
    try {
        source.getMessage(key, null, Locale.getDefault());
        return true;
    } catch (NoSuchMessageException e) {
        return false;
    }
}

From source file:com.benfante.taglib.frontend.utils.FlashHelper.java

public static String getAccumulatedMessages(String mainMessage, List<String> accumulatedMessages,
        MessageSource messageSource, Locale locale) {
    StringBuilder sb = new StringBuilder();
    if (messageSource == null) {
        messageSource = new StaticMessageSource();
        ((StaticMessageSource) messageSource).setUseCodeAsDefaultMessage(true);
    }//from  w ww  .  jav a  2 s  . c  om
    if (locale == null) {
        locale = DEFAULT_LOCALE;
    }
    if (StringUtils.hasText(mainMessage)) {
        sb.append(messageSource.getMessage(mainMessage, null, locale));
    }
    if (accumulatedMessages != null && !accumulatedMessages.isEmpty()) {
        sb.append("<ul>");
        for (String message : accumulatedMessages) {
            if (StringUtils.hasText(message)) {
                sb.append("<li>").append(messageSource.getMessage(message, null, locale)).append("</li>");
            }
        }
        sb.append("</ul>");
    }
    return sb.toString();
}

From source file:cn.org.once.cstack.utils.MessageUtils.java

public static Message writeAfterThrowingApplicationMessage(Exception e, User user, String type,
        MessageSource messageSource, Locale locale) {
    Message message = new Message();
    String body = "";
    message.setType(Message.ERROR);// w  w w.  j av  a 2  s.c  o m
    message.setAuthor(user);

    switch (type) {
    case "CREATE":
        body = messageSource.getMessage("app.create.error", null, locale);
        break;
    case "UPDATE":
        body = "Error update application - " + e.getLocalizedMessage();
        break;
    case "DELETE":
        body = "Error delete application - " + e.getLocalizedMessage();
        break;
    case "START":
        body = "Error start application - " + e.getLocalizedMessage();
        break;
    case "STOP":
        body = "Error stop application - " + e.getLocalizedMessage();
        break;
    case "RESTART":
        body = "Error restart application - " + e.getLocalizedMessage();
        break;

    default:
        body = "Error : unkown error";
        break;
    }
    message.setEvent(body);

    return message;
}

From source file:jetx.ext.springmvc.SpringMvcFunctions.java

/**
 * ??//from   ww w. j a  va  2s .c  o m
 */
public static List<String> fieldErrors(JetPageContext ctx, String fieldName) {

    Errors errors = FunctionUtils.findErrors(ctx.getContext());
    if (errors == null) {
        return EMPTY_STRING_LIST;
    }

    List<FieldError> fes = errors.getFieldErrors(fieldName);
    List<String> msgs = new ArrayList<String>(0);

    for (FieldError fe : fes) {
        String[] codes = fe.getCodes();
        String defaultMsg = fe.getDefaultMessage();
        Object[] args = fe.getArguments();
        Locale locale = getLocale(ctx);
        MessageSource ms = getMessageSource(ctx);

        if (codes == null || codes.length == 0 || ms == null) {
            msgs.add(defaultMsg);
        } else {
            String msg = null;
            for (int i = 0; i < codes.length; i++) {
                try {
                    msg = ms.getMessage(codes[i], args, locale);
                } catch (NoSuchMessageException e) {
                    // 
                }
                if (msg == null) {
                    msg = defaultMsg;
                }
            }
            msgs.add(msg);
        }
    }
    return Collections.unmodifiableList(msgs);
}

From source file:jetx.ext.springmvc.SpringMvcFunctions.java

/**
 * ??//from w  ww .  j ava 2s  . c  om
 */
public static List<String> globalErrors(JetPageContext ctx) {

    Errors errors = FunctionUtils.findErrors(ctx.getContext());
    if (errors == null) {
        return EMPTY_STRING_LIST;
    }

    List<ObjectError> oes = errors.getGlobalErrors();
    List<String> msgs = new ArrayList<String>(0);

    for (ObjectError oe : oes) {
        String[] codes = oe.getCodes();
        String defaultMsg = oe.getDefaultMessage();
        Object[] args = oe.getArguments();
        Locale locale = getLocale(ctx);
        MessageSource ms = getMessageSource(ctx);

        if (codes == null || codes.length == 0 || ms == null) {
            msgs.add(defaultMsg);
        } else {
            String msg = null;
            for (int i = 0; i < codes.length; i++) {
                try {
                    msg = ms.getMessage(codes[i], args, locale);
                } catch (NoSuchMessageException e) {
                    // 
                }
                if (msg == null) {
                    msg = defaultMsg;
                }
            }
            msgs.add(msg);
        }
    }
    return Collections.unmodifiableList(msgs);
}

From source file:org.terasoluna.gfw.common.message.ResultMessageUtils.java

/**
 * resolve message text of <code>ResultMessage</code><br>
 * <ol>//from   ww w .j a  v  a  2s  . co m
 * <li>if <code>ResultMessage</code> has message code, try to resolve message using it
 * <ol>
 * <li>if there is no message for that code, try to use text of <code>ResultMessage</code>.</li>
 * <li>if there is no text, throw {@link NoSuchMessageException}</li>
 * </ol>
 * </li>
 * <li>return text of <code>ResultMessage</code> even if it is <code>null</code></li>
 * </ol>
 * @param message result message to resolve (must not be <code>null</code>)
 * @param messageSource message source (must not be <code>null</code>)
 * @param locale locate to resolve message (must not be <code>null</code>)
 * @return message text (must not be <code>null</code>)
 * @throws NoSuchMessageException if message is not found and no default text is given
 * @throws IllegalArgumentException if message or messageSoruce or locale is <code>null</code>
 */
public static String resolveMessage(ResultMessage message, MessageSource messageSource, Locale locale)
        throws NoSuchMessageException {
    Assert.notNull(messageSource, "messageSource must not be null!");
    Assert.notNull(message, "message must not be null!");
    Assert.notNull(locale, "locale must not be null!");

    String msg;
    String code = message.getCode();
    if (code != null) {
        // try to resolve from code at first.
        try {
            msg = messageSource.getMessage(code, message.getArgs(), locale);
        } catch (NoSuchMessageException e) {
            String text = message.getText();
            if (text != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("messege is not found under code '" + code + "' for '" + locale + "'. use '"
                            + text + "' instead", e);
                }
                // if ResultMessage has a text, then use it.
                msg = text;
            } else {
                // otherwise throw exception
                throw e;
            }
        }
    } else {
        msg = message.getText();
    }
    return msg;
}

From source file:org.kmnet.com.fw.common.message.ResultMessageUtils.java

/**
 * resolve message text of <code>ResultMessage</code><br>
 * <ol>/*  w  w w  .j  ava  2 s.co m*/
 * <li>if <code>ResultMessage</code> has message code, try to resolve message using it
 * <ol>
 * <li>if there is no message for that code, try to use text of <code>ResultMessage</code>.</li>
 * <li>if there is no text, throw {@link NoSuchMessageException}</li>
 * </ol>
 * </li>
 * <li>return text of <code>ResultMessage</code> even if it is <code>null</code></li>
 * </ol>
 * @param message result message to resolve (must not be <code>null</code>)
 * @param messageSource message source (must not be <code>null</code>)
 * @param locale locate to resolve message (must not be <code>null</code>)
 * @return message text (must not be <code>null</code>)
 * @throws NoSuchMessageException if message is not found and no default text is given
 * @throws IllegalArgumentException if message or messageSoruce or locale is <code>null</code>
 */
public static String resolveMessage(ResultMessage message, MessageSource messageSource, Locale locale)
        throws NoSuchMessageException {

    Assert.notNull(messageSource, "messageSource must not be null!");
    Assert.notNull(message, "message must not be null!");
    Assert.notNull(locale, "locale must not be null!");

    String msg = null;
    String code = message.getCode();
    if (code != null) {
        // try to resolve from code at first.
        try {
            msg = messageSource.getMessage(code, message.getArgs(), locale);
        } catch (NoSuchMessageException e) {
            String text = message.getText();
            if (text != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("messege is not found under code '" + code + "' for '" + locale + "'. use '"
                            + text + "' instead", e);
                }
                // if ResultMessage has a text, then use it.
                msg = text;
            } else {
                // otherwise throw exception
                throw e;
            }
        }
    } else {
        msg = message.getText();
    }
    return msg;
}

From source file:org.sakaiproject.iclicker.tool.ToolController.java

public static void addMessage(PageContext context, String key, String messageKey, Object... args) {
    if (context == null || key == null) {
        throw new IllegalArgumentException(
                "context (" + context + ") and key (" + key + ") must both not be null");
    }//from   ww w. ja va 2s. c  o  m
    if (messageKey != null && !"".equals(messageKey)) {
        // get the message from messageSource if possible
        MessageSource ms = (MessageSource) context.findAttribute("messageSource");
        Locale locale = context.getRequest().getLocale();
        String message;
        try {
            message = ms.getMessage(messageKey, args, locale);
        } catch (NoSuchMessageException e) {
            message = "{{INVALID KEY:" + messageKey + "}}";
        }
        addMessage(context, key, message);
    }
}