001// Copyright 2005 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.tapestry.listener;
016
017import java.util.Collection;
018import java.util.Collections;
019import java.util.HashMap;
020import java.util.Map;
021
022import org.apache.hivemind.ApplicationRuntimeException;
023import org.apache.hivemind.util.Defense;
024import org.apache.tapestry.IActionListener;
025
026/**
027 * @author Howard M. Lewis Ship
028 * @since 4.0
029 */
030public class ListenerMapImpl implements ListenerMap
031{
032    private final Object _target;
033
034    /**
035     * Keyed on String method name, value is
036     * {@link org.apache.tapestry.listener.ListenerMethodInvoker}.
037     */
038
039    private final Map _invokers;
040
041    private final Map _listeners = new HashMap();
042
043    public ListenerMapImpl(Object target, Map invokers)
044    {
045        Defense.notNull(target, "target");
046        Defense.notNull(invokers, "invokers");
047
048        _target = target;
049        _invokers = invokers;
050    }
051
052    public boolean canProvideListener(String name)
053    {
054        return _invokers.containsKey(name);
055    }
056
057    public synchronized IActionListener getListener(String name)
058    {
059        IActionListener result = (IActionListener) _listeners.get(name);
060
061        if (result == null)
062        {
063            result = createListener(name);
064            _listeners.put(name, result);
065        }
066
067        return result;
068    }
069
070    private IActionListener createListener(String name)
071    {
072        ListenerMethodInvoker invoker = (ListenerMethodInvoker) _invokers.get(name);
073
074        if (invoker == null)
075            throw new ApplicationRuntimeException(ListenerMessages.objectMissingMethod(
076                    _target,
077                    name), _target, null, null);
078
079        return new SyntheticListener(_target, invoker);
080    }
081
082    public Collection getListenerNames()
083    {
084        return Collections.unmodifiableCollection(_invokers.keySet());
085    }
086}