1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.vfs.util;
18
19 import java.text.MessageFormat;
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.MissingResourceException;
23 import java.util.ResourceBundle;
24
25 /***
26 * Formats messages.
27 *
28 * @author <a href="mailto:adammurdoch@apache.org">Adam Murdoch</a>
29 * @version $Revision: 480428 $ $Date: 2006-11-29 07:15:24 +0100 (Mi, 29 Nov 2006) $
30 */
31 public class Messages
32 {
33 /***
34 * Map from message code to MessageFormat object for the message.
35 */
36 private static Map messages = new HashMap();
37 private static ResourceBundle resources;
38
39 private Messages()
40 {
41 }
42
43 /***
44 * Formats a message.
45 *
46 * @param code The message code.
47 * @return The formatted message.
48 */
49 public static String getString(final String code)
50 {
51 return getString(code, new Object[0]);
52 }
53
54 /***
55 * Formats a message.
56 *
57 * @param code The message code.
58 * @param param The message parameter.
59 * @return The formatted message.
60 */
61 public static String getString(final String code, final Object param)
62 {
63 return getString(code, new Object[]{param});
64 }
65
66 /***
67 * Formats a message.
68 *
69 * @param code The message code.
70 * @param params The message parameters.
71 * @return The formatted message.
72 */
73 public static String getString(final String code, final Object[] params)
74 {
75 try
76 {
77 if (code == null)
78 {
79 return null;
80 }
81
82 final MessageFormat msg = findMessage(code);
83 return msg.format(params);
84 }
85 catch (final MissingResourceException mre)
86 {
87 return "Unknown message with code \"" + code + "\".";
88 }
89 }
90
91 /***
92 * Locates a message by its code.
93 */
94 private static synchronized MessageFormat findMessage(final String code)
95 throws MissingResourceException
96 {
97
98 MessageFormat msg = (MessageFormat) messages.get(code);
99 if (msg != null)
100 {
101 return msg;
102 }
103
104
105 if (resources == null)
106 {
107 resources = ResourceBundle.getBundle("org.apache.commons.vfs.Resources");
108 }
109 final String msgText = resources.getString(code);
110 msg = new MessageFormat(msgText);
111 messages.put(code, msg);
112 return msg;
113 }
114 }