KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > context > ResourceBundleMessageSourceTests


1 /*
2  * Copyright 2002-2005 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.web.context;
18
19 import java.util.Date JavaDoc;
20 import java.util.Locale JavaDoc;
21
22 import org.springframework.context.AbstractApplicationContextTests;
23 import org.springframework.context.ConfigurableApplicationContext;
24 import org.springframework.context.MessageSource;
25 import org.springframework.context.NoSuchMessageException;
26 import org.springframework.context.support.AbstractMessageSource;
27 import org.springframework.mock.web.MockServletContext;
28 import org.springframework.ui.context.Theme;
29 import org.springframework.web.context.support.XmlWebApplicationContext;
30 import org.springframework.web.servlet.theme.AbstractThemeResolver;
31
32 /**
33  * Creates a WebApplicationContext that points to a "web.xml" file that
34  * contains the entry for what file to use for the applicationContext
35  * (file "org/springframework/web/context/WEB-INF/applicationContext.xml").
36  * That file then has an entry for a bean called "messageSource".
37  * Whatever the basename property is set to for this bean is what the name of
38  * a properties file in the classpath must be (in our case the name is
39  * "messages" - note no package names).
40  * Thus the catalog filename will be in the root of where the classes are compiled
41  * to and will be called "messages_XX_YY.properties" where "XX" and "YY" are the
42  * language and country codes known by the ResourceBundle class.
43  *
44  * <p>NOTE: The main method of this class is the "createWebApplicationContext(...)" method,
45  * and it was copied from org.springframework.web.context.XmlWebApplicationContextTests.
46  *
47  * @author Rod Johnson
48  * @author Tony Falabella
49  * @author Jean-Pierre Pawlak
50  */

51 public class ResourceBundleMessageSourceTests extends AbstractApplicationContextTests {
52
53     /**
54      * We use ticket WAR root for file structure.
55      * We don't attempt to read web.xml.
56      */

57     public static final String JavaDoc WAR_ROOT = "/org/springframework/web/context";
58
59     private ConfigurableWebApplicationContext root;
60
61     private MessageSource themeMsgSource;
62
63     protected ConfigurableApplicationContext createContext() throws Exception JavaDoc {
64         root = new XmlWebApplicationContext();
65         MockServletContext sc = new MockServletContext("");
66         root.setServletContext(sc);
67         root.setConfigLocations(new String JavaDoc[] {"/org/springframework/web/context/WEB-INF/applicationContext.xml"});
68         root.refresh();
69
70         ConfigurableWebApplicationContext wac = new XmlWebApplicationContext();
71         wac.setParent(root);
72         wac.setServletContext(sc);
73         wac.setNamespace("test-servlet");
74         wac.setConfigLocations(new String JavaDoc[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"});
75         wac.refresh();
76
77         Theme theme = wac.getTheme(AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME);
78         assertNotNull(theme);
79         assertTrue("Theme name has to be the default theme name", AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME.equals(theme.getName()));
80         themeMsgSource = theme.getMessageSource();
81         assertNotNull(themeMsgSource);
82         return wac;
83     }
84
85     public void testCount() {
86         assertTrue("should have 14 beans, not " +
87                 this.applicationContext.getBeanDefinitionCount(),
88                 this.applicationContext.getBeanDefinitionCount() == 14);
89     }
90
91     /**
92      * Overridden as we can't trust superclass method.
93      * @see org.springframework.context.AbstractApplicationContextTests#testEvents()
94      */

95     public void testEvents() throws Exception JavaDoc {
96         // Do nothing
97
}
98
99     public void testRootMessageSourceWithUseCodeAsDefaultMessage() throws NoSuchMessageException {
100         AbstractMessageSource messageSource = (AbstractMessageSource) root.getBean("messageSource");
101         messageSource.setUseCodeAsDefaultMessage(true);
102
103         assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault()));
104         assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault()));
105
106         try {
107             applicationContext.getMessage("code0", null, Locale.getDefault());
108             fail("looking for code0 should throw a NoSuchMessageException");
109         }
110         catch (NoSuchMessageException ex) {
111             // that's how it should be
112
}
113     }
114
115     /**
116      * @see org.springframework.context.support.AbstractMessageSource for more details.
117      * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files.
118      */

119     public void testGetMessageWithDefaultPassedInAndFoundInMsgCatalog() {
120         assertTrue("valid msg from resourcebundle with default msg passed in returned default msg. Expected msg from catalog.",
121                 getApplicationContext().getMessage("message.format.example2", null, "This is a default msg if not found in msg.cat.", Locale.US
122                 )
123                 .equals("This is a test message in the message catalog with no args."));
124         // getApplicationContext().getTheme("theme").getMessageSource().getMessage()
125
}
126
127     /**
128      * @see org.springframework.context.support.AbstractMessageSource for more details.
129      * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files.
130      */

131     public void testGetMessageWithDefaultPassedInAndNotFoundInMsgCatalog() {
132         assertTrue("bogus msg from resourcebundle with default msg passed in returned default msg",
133                 getApplicationContext().getMessage("bogus.message", null, "This is a default msg if not found in msg.cat.", Locale.UK
134                 )
135                 .equals("This is a default msg if not found in msg.cat."));
136     }
137
138     /**
139      * The underlying implementation uses a hashMap to cache messageFormats
140      * once a message has been asked for. This test is an attempt to
141      * make sure the cache is being used properly.
142      * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files.
143      * @see org.springframework.context.support.AbstractMessageSource for more details.
144      */

145     public void testGetMessageWithMessageAlreadyLookedFor() throws Exception JavaDoc {
146         Object JavaDoc[] arguments = {
147             new Integer JavaDoc(7), new Date JavaDoc(System.currentTimeMillis()),
148             "a disturbance in the Force"
149         };
150
151         // The first time searching, we don't care about for this test
152
getApplicationContext().getMessage("message.format.example1", arguments, Locale.US);
153
154         // Now msg better be as expected
155
assertTrue("2nd search within MsgFormat cache returned expected message for Locale.US",
156                 getApplicationContext().getMessage("message.format.example1", arguments, Locale.US
157                 )
158                 .indexOf("there was \"a disturbance in the Force\" on planet 7.") != -1);
159
160         Object JavaDoc[] newArguments = {
161             new Integer JavaDoc(8), new Date JavaDoc(System.currentTimeMillis()),
162             "a disturbance in the Force"
163         };
164
165         // Now msg better be as expected even with different args
166
assertTrue("2nd search within MsgFormat cache with different args returned expected message for Locale.US",
167                 getApplicationContext().getMessage("message.format.example1", newArguments, Locale.US
168                 )
169                 .indexOf("there was \"a disturbance in the Force\" on planet 8.") != -1);
170     }
171
172     /**
173      * @see org.springframework.context.support.AbstractMessageSource for more details.
174      * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files.
175      * Example taken from the javadocs for the java.text.MessageFormat class
176      */

177     public void testGetMessageWithNoDefaultPassedInAndFoundInMsgCatalog()
178             throws Exception JavaDoc {
179         Object JavaDoc[] arguments = {
180             new Integer JavaDoc(7), new Date JavaDoc(System.currentTimeMillis()),
181             "a disturbance in the Force"
182         };
183
184
185         /*
186          Try with Locale.US
187          Since the msg has a time value in it, we will use String.indexOf(...)
188          to just look for a substring without the time. This is because it is
189          possible that by the time we store a time variable in this method
190          and the time the ResourceBundleMessageSource resolves the msg the
191          minutes of the time might not be the same.
192          */

193         assertTrue("msg from resourcebundle for Locale.US substituting args for placeholders is as expected",
194                 getApplicationContext().getMessage("message.format.example1", arguments, Locale.US
195                 )
196                 .indexOf("there was \"a disturbance in the Force\" on planet 7.") != -1);
197
198         // Try with Locale.UK
199
assertTrue("msg from resourcebundle for Locale.UK substituting args for placeholders is as expected",
200                 getApplicationContext().getMessage("message.format.example1", arguments, Locale.UK
201                 )
202                 .indexOf("there was \"a disturbance in the Force\" on station number 7.") != -1);
203
204         // Try with Locale.US - different test msg that requires no args
205
assertTrue("msg from resourcebundle that requires no args for Locale.US is as expected",
206                 getApplicationContext().getMessage("message.format.example2", null, Locale.US)
207                 .equals("This is a test message in the message catalog with no args."));
208     }
209
210     /**
211      * @see org.springframework.context.support.AbstractMessageSource for more details.
212      * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files.
213      */

214     public void testGetMessageWithNoDefaultPassedInAndNotFoundInMsgCatalog() {
215         // Expecting an exception
216
try {
217             getApplicationContext().getMessage("bogus.message", null, Locale.UK);
218             fail("bogus msg from resourcebundle without default msg should have thrown exception");
219         }
220         catch (NoSuchMessageException tExcept) {
221             assertTrue("bogus msg from resourcebundle without default msg threw expected exception",
222                     true);
223         }
224     }
225
226     public void testGetMultipleBasenamesForMessageSource() throws NoSuchMessageException {
227         assertEquals("message1", getApplicationContext().getMessage("code1", null, Locale.UK));
228         assertEquals("message2", getApplicationContext().getMessage("code2", null, Locale.UK));
229         assertEquals("message3", getApplicationContext().getMessage("code3", null, Locale.UK));
230     }
231
232     /**
233      * @see org.springframework.context.support.AbstractMessageSource for more details.
234      * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/themeXXX.properties" files.
235      */

236     public void testGetMessageWithDefaultPassedInAndFoundInThemeCatalog() {
237         // Try with Locale.US
238
String JavaDoc msg = getThemeMessage("theme.example1", null, "This is a default theme msg if not found in theme cat.", Locale.US);
239         assertTrue("valid msg from theme resourcebundle with default msg passed in returned default msg. Expected msg from catalog. Received: " + msg,
240                 msg.equals("This is a test message in the theme message catalog."));
241         // Try with Locale.UK
242
msg = getThemeMessage("theme.example1", null, "This is a default theme msg if not found in theme cat.", Locale.UK);
243         assertTrue("valid msg from theme resourcebundle with default msg passed in returned default msg. Expected msg from catalog.",
244                 msg.equals("This is a test message in the theme message catalog with no args."));
245     }
246
247     /**
248      * @see org.springframework.context.support.AbstractMessageSource for more details.
249      * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/themeXXX.properties" files.
250      */

251     public void testGetMessageWithDefaultPassedInAndNotFoundInThemeCatalog() {
252         assertTrue("bogus msg from theme resourcebundle with default msg passed in returned default msg",
253                 getThemeMessage("bogus.message", null, "This is a default msg if not found in theme cat.", Locale.UK
254                 )
255                 .equals("This is a default msg if not found in theme cat."));
256     }
257
258     public void testThemeSourceNesting() throws NoSuchMessageException {
259         String JavaDoc overriddenMsg = getThemeMessage("theme.example2", null, null, Locale.UK);
260         String JavaDoc originalMsg = root.getTheme(AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME).getMessageSource().getMessage("theme.example2", null, Locale.UK);
261         assertTrue("correct overridden msg", "test-message2".equals(overriddenMsg));
262         assertTrue("correct original msg", "message2".equals(originalMsg));
263     }
264
265     private String JavaDoc getThemeMessage(String JavaDoc code, Object JavaDoc args[], String JavaDoc defaultMessage, Locale JavaDoc locale) {
266         return themeMsgSource.getMessage(code, args, defaultMessage, locale);
267     }
268
269 }
270
Popular Tags