1. /*
  2. * Copyright 2002-2004 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. package org.springframework.context.support;
  17. import java.util.Enumeration;
  18. import java.util.Locale;
  19. import java.util.ResourceBundle;
  20. import org.springframework.context.MessageSource;
  21. import org.springframework.context.NoSuchMessageException;
  22. /**
  23. * Helper class that allows for accessing a MessageSource as a ResourceBundle.
  24. * Used for example to expose a Spring MessageSource to JSTL web views.
  25. * @author Juergen Hoeller
  26. * @since 27.02.2003
  27. * @see org.springframework.context.MessageSource
  28. * @see java.util.ResourceBundle
  29. * @see org.springframework.web.servlet.support.JstlUtils#exposeLocalizationContext
  30. */
  31. public class MessageSourceResourceBundle extends ResourceBundle {
  32. private final MessageSource source;
  33. private final Locale locale;
  34. public MessageSourceResourceBundle(MessageSource source, Locale locale) {
  35. this.source = source;
  36. this.locale = locale;
  37. }
  38. /**
  39. * This implementation resolves the code in the MessageSource.
  40. * Returns null if the message could not be resolved.
  41. */
  42. protected Object handleGetObject(String code) {
  43. try {
  44. return this.source.getMessage(code, null, this.locale);
  45. }
  46. catch (NoSuchMessageException ex) {
  47. return null;
  48. }
  49. }
  50. /**
  51. * This implementation returns null, as a MessageSource does
  52. * not allow for enumerating the defined message codes.
  53. */
  54. public Enumeration getKeys() {
  55. return null;
  56. }
  57. }