001 // Copyright 2006, 2009, 2011 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.util;
016
017 import org.apache.tapestry5.ioc.MessageFormatter;
018 import org.apache.tapestry5.ioc.Messages;
019 import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
020 import org.apache.tapestry5.ioc.internal.util.MessageFormatterImpl;
021
022 import java.util.Locale;
023 import java.util.Map;
024
025 /**
026 * Abstract implementation of {@link Messages} that doesn't know where values come from (that information is supplied in
027 * a subclass, via the {@link #valueForKey(String)} method).
028 */
029 public abstract class AbstractMessages implements Messages
030 {
031 /**
032 * String key to MF instance.
033 */
034 private final Map<String, MessageFormatter> cache = CollectionFactory.newConcurrentMap();
035
036 private final Locale locale;
037
038 protected AbstractMessages(Locale locale)
039 {
040 this.locale = locale;
041 }
042
043 /**
044 * Invoked to provide the value for a particular key. This may be invoked multiple times even for the same key. The
045 * implementation should <em>ignore the case of the key</em>.
046 *
047 * @param key the key to obtain a value for (case insensitive)
048 * @return the value for the key, or null if this instance can not provide the value
049 */
050 protected abstract String valueForKey(String key);
051
052
053 public boolean contains(String key)
054 {
055 return valueForKey(key) != null;
056 }
057
058 public String get(String key)
059 {
060 if (contains(key)) return valueForKey(key);
061
062 return String.format("[[missing key: %s]]", key);
063 }
064
065 public MessageFormatter getFormatter(String key)
066 {
067 MessageFormatter result = cache.get(key);
068
069 if (result == null)
070 {
071 result = buildMessageFormatter(key);
072 cache.put(key, result);
073 }
074
075 return result;
076 }
077
078 private MessageFormatter buildMessageFormatter(String key)
079 {
080 String format = get(key);
081
082 return new MessageFormatterImpl(format, locale);
083 }
084
085 public String format(String key, Object... args)
086 {
087 return getFormatter(key).format(args);
088 }
089
090 }