001// Copyright 2004, 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.hivemind.lib.impl;
016
017import java.util.ArrayList;
018import java.util.List;
019
020import org.apache.hivemind.ApplicationRuntimeException;
021import org.apache.hivemind.lib.RemoteExceptionCoordinator;
022import org.apache.hivemind.lib.RemoteExceptionEvent;
023import org.apache.hivemind.lib.RemoteExceptionListener;
024
025/**
026 * Core implementation of {@link org.apache.hivemind.lib.RemoteExceptionCoordinator}.
027 *
028 * @author Howard Lewis Ship
029 */
030
031public class RemoteExceptionCoordinatorImpl implements RemoteExceptionCoordinator
032{
033    private boolean _locked;
034    private List _listeners;
035
036    private void checkLocked(String methodName)
037    {
038        if (_locked)
039            throw new ApplicationRuntimeException(ImplMessages.coordinatorLocked(methodName));
040    }
041
042    public synchronized void addRemoteExceptionListener(RemoteExceptionListener listener)
043    {
044        checkLocked("addRemoteExceptionListener");
045
046        if (_listeners == null)
047            _listeners = new ArrayList();
048
049        _listeners.add(listener);
050    }
051
052    public synchronized void removeRemoteExceptionListener(RemoteExceptionListener listener)
053    {
054        checkLocked("removeRemoteExceptionListener");
055
056        if (_listeners == null)
057            return;
058
059        _listeners.remove(listener);
060    }
061
062    public synchronized void fireRemoteExceptionDidOccur(Object source, Throwable exception)
063    {
064        checkLocked("sendNotification");
065
066        if (_listeners == null || _listeners.size() == 0)
067            return;
068
069        RemoteExceptionEvent event = new RemoteExceptionEvent(source, exception);
070
071        int count = _listeners.size();
072
073        _locked = true;
074
075        try
076        {
077
078            for (int i = 0; i < count; i++)
079            {
080                RemoteExceptionListener listener = (RemoteExceptionListener) _listeners.get(i);
081
082                listener.remoteExceptionDidOccur(event);
083            }
084        }
085        finally
086        {
087            _locked = false;
088        }
089
090    }
091
092}