001// Copyright 2006, 2012 The Apache Software Foundation 002// 003// Licensed under the Apache License, Version 2.0 (the "License"); 004// you may not use this file except in compliance with the License. 005// You may obtain a copy of the License at 006// 007// http://www.apache.org/licenses/LICENSE-2.0 008// 009// Unless required by applicable law or agreed to in writing, software 010// distributed under the License is distributed on an "AS IS" BASIS, 011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012// See the License for the specific language governing permissions and 013// limitations under the License. 014 015package org.apache.tapestry5.commons.internal.util; 016 017import java.util.Enumeration; 018import java.util.Locale; 019import java.util.Map; 020import java.util.ResourceBundle; 021import java.util.Set; 022 023import org.apache.tapestry5.commons.Messages; 024import org.apache.tapestry5.commons.util.AbstractMessages; 025import org.apache.tapestry5.commons.util.CollectionFactory; 026 027/** 028 * Implementation of {@link org.apache.tapestry5.commons.Messages} based around a {@link java.util.ResourceBundle}. 029 */ 030public class MessagesImpl extends AbstractMessages 031{ 032 private final Map<String, String> properties = CollectionFactory.newCaseInsensitiveMap(); 033 034 /** 035 * Finds the messages for a given Messages utility class. Strings the trailing "Messages" and replaces it with 036 * "Strings" to form the base path. Loads the bundle using the default locale, and the class' class loader. 037 * 038 * @param forClass 039 * @return Messages for the class 040 */ 041 public static Messages forClass(Class forClass) 042 { 043 String className = forClass.getName(); 044 String stringsClassName = className.replaceAll("Messages$", "Strings"); 045 046 Locale locale = Locale.getDefault(); 047 048 ResourceBundle bundle = ResourceBundle.getBundle(stringsClassName, locale, forClass.getClassLoader()); 049 050 return new MessagesImpl(locale, bundle); 051 } 052 053 public MessagesImpl(Locale locale, ResourceBundle bundle) 054 { 055 super(locale); 056 057 // Our best (threadsafe) chance to determine all the available keys. 058 Enumeration<String> e = bundle.getKeys(); 059 while (e.hasMoreElements()) 060 { 061 String key = e.nextElement(); 062 String value = bundle.getString(key); 063 064 properties.put(key, value); 065 } 066 } 067 068 @Override 069 protected String valueForKey(String key) 070 { 071 return properties.get(key); 072 } 073 074 @Override 075 public Set<String> getKeys() 076 { 077 return properties.keySet(); 078 } 079}