001    // Copyright 2010 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.internal.services;
016    
017    import org.apache.tapestry5.ioc.MessageFormatter;
018    import org.apache.tapestry5.ioc.Messages;
019    
020    /**
021     * Implementation of {@link Messages} that wraps two other Messages instances: a primary and a delegate.
022     * The primary handles any keys it contains; method invocations that reference keys not contained by
023     * the primary are passed on to the delegate.
024     * 
025     * @since 5.2.0
026     */
027    public class DelegatingMessagesImpl implements Messages
028    {
029        private final Messages primary, delegate;
030    
031        public DelegatingMessagesImpl(Messages primary, Messages delegate)
032        {
033            this.primary = primary;
034            this.delegate = delegate;
035        }
036    
037        public boolean contains(String key)
038        {
039            return primary.contains(key) || delegate.contains(key);
040        }
041    
042        private Messages select(String key)
043        {
044            return primary.contains(key) ? primary : delegate;
045        }
046    
047        public String format(String key, Object... args)
048        {
049            return select(key).format(key, args);
050        }
051    
052        public String get(String key)
053        {
054            return select(key).get(key);
055        }
056    
057        public MessageFormatter getFormatter(String key)
058        {
059            return select(key).getFormatter(key);
060        }
061    }