001// Copyright 2006, 2007, 2008, 2011, 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.internal.event;
016
017import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
018import org.apache.tapestry5.services.InvalidationEventHub;
019import org.apache.tapestry5.services.InvalidationListener;
020
021import java.util.List;
022import java.util.Map;
023
024/**
025 * Base implementation class for classes (especially services) that need to manage a list of
026 * {@link org.apache.tapestry5.services.InvalidationListener}s.
027 */
028public class InvalidationEventHubImpl implements InvalidationEventHub
029{
030    private final List<Runnable> callbacks;
031
032    protected InvalidationEventHubImpl(boolean productionMode)
033    {
034        if (productionMode)
035        {
036            callbacks = null;
037        } else
038        {
039            callbacks = CollectionFactory.newThreadSafeList();
040        }
041    }
042
043    /**
044     * Notifies all listeners/callbacks.
045     */
046    protected final void fireInvalidationEvent()
047    {
048        if (callbacks == null)
049        {
050            return;
051        }
052
053        for (Runnable callback : callbacks)
054        {
055            callback.run();
056        }
057    }
058
059    public final void addInvalidationCallback(Runnable callback)
060    {
061        assert callback != null;
062
063        // In production mode, callbacks may be null, in which case, just
064        // ignore the callback.
065        if (callbacks != null)
066        {
067            callbacks.add(callback);
068        }
069    }
070
071    public final void clearOnInvalidation(final Map<?, ?> map)
072    {
073        assert map != null;
074
075        addInvalidationCallback(new Runnable()
076        {
077            public void run()
078            {
079                map.clear();
080            }
081        });
082    }
083
084    public final void addInvalidationListener(final InvalidationListener listener)
085    {
086        assert listener != null;
087
088        addInvalidationCallback(new Runnable()
089        {
090            public void run()
091            {
092                listener.objectWasInvalidated();
093            }
094        });
095    }
096
097}