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