001    // Copyright 2006 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    
015    package org.apache.tapestry5.ioc.internal.util;
016    
017    import org.apache.tapestry5.ioc.Messages;
018    import org.apache.tapestry5.ioc.util.AbstractMessages;
019    
020    import java.util.Enumeration;
021    import java.util.Locale;
022    import java.util.Map;
023    import java.util.ResourceBundle;
024    
025    /**
026     * Implementation of {@link org.apache.tapestry5.ioc.Messages} based around a {@link java.util.ResourceBundle}.
027     */
028    public class MessagesImpl extends AbstractMessages
029    {
030        private final Map<String, String> properties = CollectionFactory.newCaseInsensitiveMap();
031    
032        /**
033         * Finds the messages for a given Messages utility class. Strings the trailing "Messages" and replaces it with
034         * "Strings" to form the base path. Loads the bundle using the default locale, and the class' class loader.
035         *
036         * @param forClass
037         * @return Messages for the class
038         */
039        public static Messages forClass(Class forClass)
040        {
041            String className = forClass.getName();
042            String stringsClassName = className.replaceAll("Messages$", "Strings");
043    
044            Locale locale = Locale.getDefault();
045    
046            ResourceBundle bundle = ResourceBundle.getBundle(stringsClassName, locale, forClass.getClassLoader());
047    
048            return new MessagesImpl(locale, bundle);
049        }
050    
051        public MessagesImpl(Locale locale, ResourceBundle bundle)
052        {
053            super(locale);
054    
055            // Our best (threadsafe) chance to determine all the available keys.
056            Enumeration<String> e = bundle.getKeys();
057            while (e.hasMoreElements())
058            {
059                String key = e.nextElement();
060                String value = bundle.getString(key);
061    
062                properties.put(key, value);
063            }
064        }
065    
066        @Override
067        protected String valueForKey(String key)
068        {
069            return properties.get(key);
070        }
071    
072    }