01: /*
02: * Copyright 2002-2007 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 Spring
29: * {@link org.springframework.context.MessageSource} as a {@link java.util.ResourceBundle}.
30: * Used for example to expose a Spring MessageSource to JSTL web views.
31: *
32: * @author Juergen Hoeller
33: * @since 27.02.2003
34: * @see org.springframework.context.MessageSource
35: * @see java.util.ResourceBundle
36: * @see org.springframework.web.servlet.support.JstlUtils#exposeLocalizationContext
37: */
38: public class MessageSourceResourceBundle extends ResourceBundle {
39:
40: private final MessageSource messageSource;
41:
42: private final Locale locale;
43:
44: /**
45: * Create a new MessageSourceResourceBundle for the given MessageSource and Locale.
46: * @param source the MessageSource to retrieve messages from
47: * @param locale the Locale to retrieve messages for
48: */
49: public MessageSourceResourceBundle(MessageSource source,
50: Locale locale) {
51: Assert.notNull(source, "MessageSource must not be null");
52: this .messageSource = source;
53: this .locale = locale;
54: }
55:
56: /**
57: * This implementation resolves the code in the MessageSource.
58: * Returns null if the message could not be resolved.
59: */
60: protected Object handleGetObject(String code) {
61: try {
62: return this .messageSource.getMessage(code, null,
63: this .locale);
64: } catch (NoSuchMessageException ex) {
65: return null;
66: }
67: }
68:
69: /**
70: * This implementation returns <code>null</code>, as a MessageSource does
71: * not allow for enumerating the defined message codes.
72: */
73: public Enumeration getKeys() {
74: return null;
75: }
76:
77: }
|