1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.millscript.millscript;
22
23 import java.text.MessageFormat;
24 import java.util.Locale;
25 import java.util.MissingResourceException;
26 import java.util.ResourceBundle;
27
28 /**
29 * This class is intended to handle internationalisation for any messages
30 * MillScript produces.
31 */
32 public final class Resources {
33
34 /**
35 * The resource bundle containing all the unformatted messages for the
36 * current locale.
37 */
38 private static ResourceBundle messages;
39
40 /**
41 * Hidden constructor.
42 */
43 private Resources() {
44 }
45
46 /**
47 * Loads the resource bundle for the current locale, reverting to a
48 * <code>UK</code> locale if nothing else is available.
49 */
50 private static void loadMessages() {
51
52 try {
53 messages = ResourceBundle.getBundle(
54 "org/millscript/millscript/messages/messages"
55 );
56 } catch ( MissingResourceException ex ) {
57 messages = ResourceBundle.getBundle(
58 "org/millscript/millscript/messages/messages",
59 Locale.UK
60 );
61 }
62 }
63
64 /**
65 * Returns the localised message for the specified key.
66 *
67 * @param key the key for the desired message
68 * @return the localised message for the specified key
69 */
70 public static String getMessage( final String key ) {
71
72 if ( messages == null ) {
73 loadMessages();
74 }
75
76 return messages.getString( key );
77
78 }
79
80 /**
81 * Returns the localised message for the specified key, formatted using the
82 * specified arguments.
83 *
84 * @param key the key for the desired message
85 * @param args the arguments required to format the message
86 * @return the localised, formatted message for the specified key
87 */
88 public static String getFormattedMessage( final String key, final Object[] args ) {
89 return MessageFormat.format( getMessage( key ), args );
90 }
91
92 /**
93 * Returns the localised message for the specified key, formatted using the
94 * single specified argument.
95 *
96 * @param key the key for the desired message
97 * @param arg the single argument required to format the message
98 * @return the localised, formatted message for the specified key
99 */
100 public static String getFormattedMessage( final String key, final Object arg ) {
101 return MessageFormat.format(
102 getMessage( key ),
103 new Object[] {
104 arg
105 }
106 );
107 }
108
109 }