01: package com.icesoft.faces.utils;
02:
03: import java.text.MessageFormat;
04: import java.util.Locale;
05: import java.util.MissingResourceException;
06: import java.util.ResourceBundle;
07:
08: import org.apache.commons.logging.Log;
09: import org.apache.commons.logging.LogFactory;
10:
11: import javax.faces.application.FacesMessage;
12: import javax.faces.context.FacesContext;
13:
14: /**
15: * This class has been designed, so the custom components can get
16: * facesMessages either from the icefaces' ResourceBundle or an
17: * application's resourceBundle. The location of ice's messages.properties
18: * is under com.icesoft.faces.resources package.
19: */
20:
21: public class MessageUtils {
22: private static Log log = LogFactory.getLog(MessageUtils.class);
23: private static String DETAIL_SUFFIX = "_detail";
24: private static int SUMMARY = 0;
25: private static int DETAIL = 1;
26: private static String ICE_MESSAGES_BUNDLE = "com.icesoft.faces.resources.messages";
27:
28: public static FacesMessage getMessage(FacesContext context,
29: String messageId) {
30: return getMessage(context, messageId, null);
31: }
32:
33: public static FacesMessage getMessage(FacesContext facesContext,
34: String messageId, Object params[]) {
35: String messageInfo[] = new String[2];
36:
37: Locale locale = facesContext.getViewRoot().getLocale();
38: String bundleName = facesContext.getApplication()
39: .getMessageBundle();
40: //see if the message has been overridden by the application
41: if (bundleName != null) {
42: try {
43: loadMessageInfo(bundleName, locale, messageId,
44: messageInfo);
45: } catch (Exception e) {
46: log.warn(e + ", using " + ICE_MESSAGES_BUNDLE);
47: }
48: }
49: //if not overridden then check in Icefaces message bundle.
50: if (messageInfo[SUMMARY] == null && messageInfo[DETAIL] == null) {
51: loadMessageInfo(ICE_MESSAGES_BUNDLE, locale, messageId,
52: messageInfo);
53: }
54: if (params != null) {
55: MessageFormat format;
56: for (int i = 0; i < messageInfo.length; i++) {
57: if (messageInfo[i] != null) {
58: format = new MessageFormat(messageInfo[i], locale);
59: messageInfo[i] = format.format(params);
60: }
61: }
62: }
63: return new FacesMessage(messageInfo[SUMMARY],
64: messageInfo[DETAIL]);
65: }
66:
67: private static void loadMessageInfo(String bundleName,
68: Locale locale, String messageId, String[] messageInfo) {
69: ResourceBundle bundle = ResourceBundle.getBundle(bundleName,
70: locale, getClassLoader(bundleName));
71: try {
72: messageInfo[SUMMARY] = bundle.getString(messageId);
73: messageInfo[DETAIL] = bundle.getString(messageId
74: + DETAIL_SUFFIX);
75: } catch (MissingResourceException e) {
76: }
77: }
78:
79: private static ClassLoader getClassLoader(Object fallback) {
80: ClassLoader classLoader = Thread.currentThread()
81: .getContextClassLoader();
82: if (classLoader == null) {
83: classLoader = fallback.getClass().getClassLoader();
84: }
85: return classLoader;
86: }
87: }
|