01: /*
02: * Copyright 2002-2005 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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.context.support;
18:
19: import java.util.Enumeration;
20: import java.util.Locale;
21: import java.util.ResourceBundle;
22:
23: import org.springframework.context.MessageSource;
24: import org.springframework.context.NoSuchMessageException;
25: import org.springframework.util.Assert;
26:
27: /**
28: * Helper class that allows for accessing a MessageSource as a ResourceBundle.
29: * Used for example to expose a Spring MessageSource to JSTL web views.
30: *
31: * @author Juergen Hoeller
32: * @since 27.02.2003
33: * @see org.springframework.context.MessageSource
34: * @see java.util.ResourceBundle
35: * @see org.springframework.web.servlet.support.JstlUtils#exposeLocalizationContext
36: */
37: public class MessageSourceResourceBundle extends ResourceBundle {
38:
39: private final MessageSource messageSource;
40:
41: private final Locale locale;
42:
43: /**
44: * Create a new MessageSourceResourceBundle for the given MessageSource and Locale.
45: * @param source the MessageSource to retrieve messages from
46: * @param locale the Locale to retrieve messages for
47: */
48: public MessageSourceResourceBundle(MessageSource source,
49: Locale locale) {
50: Assert.notNull(source, "MessageSource is required");
51: this .messageSource = source;
52: this .locale = locale;
53: }
54:
55: /**
56: * This implementation resolves the code in the MessageSource.
57: * Returns null if the message could not be resolved.
58: */
59: protected Object handleGetObject(String code) {
60: try {
61: return this .messageSource.getMessage(code, null,
62: this .locale);
63: } catch (NoSuchMessageException ex) {
64: return null;
65: }
66: }
67:
68: /**
69: * This implementation returns <code>null</code>, as a MessageSource does
70: * not allow for enumerating the defined message codes.
71: */
72: public Enumeration getKeys() {
73: return null;
74: }
75:
76: }
|