001 /*
002 * Copyright 2004 Niclas Hedhman.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
013 * implied.
014 *
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019 package net.dpml.transit.monitor;
020
021 import java.util.ArrayList;
022
023 /**
024 * A repository monitor router handles mutlicast distribution of monitor events to
025 * a set of subscribed monitors.
026 *
027 * @author <a href="http://www.dpml.net">Digital Product Meta Library</a>
028 * @version 1.0.3
029 */
030 public class AbstractMonitorRouter implements Router
031 {
032 //--------------------------------------------------------------------
033 // static
034 //--------------------------------------------------------------------
035
036 /**
037 * An empty set of monitors.
038 */
039 private static final Monitor[] EMPTY_MONITORS = new Monitor[0];
040
041 //--------------------------------------------------------------------
042 // state
043 //--------------------------------------------------------------------
044
045 /**
046 * List of attached monitors.
047 */
048 private ArrayList m_monitors;
049
050 //--------------------------------------------------------------------
051 // Router
052 //--------------------------------------------------------------------
053
054 /**
055 * Add a monitor to the set of monitors managed by this router.
056 * @param monitor the monitor to add
057 */
058 public void addMonitor( Monitor monitor )
059 {
060 synchronized( this )
061 {
062 ArrayList list;
063 if( m_monitors == null )
064 {
065 list = new ArrayList();
066 }
067 else
068 {
069 list = (ArrayList) m_monitors.clone();
070 }
071 list.add( monitor );
072 m_monitors = list;
073 }
074 }
075
076 /**
077 * Remove a monitor from the set of monitors managed by this router.
078 * @param monitor the monitor to remove
079 */
080 public void removeMonitor( Monitor monitor )
081 {
082 synchronized( this )
083 {
084 if( m_monitors == null )
085 {
086 return;
087 }
088 ArrayList list = (ArrayList) m_monitors.clone();
089 list.remove( monitor );
090 if( list.size() == 0 )
091 {
092 m_monitors = null;
093 }
094 else
095 {
096 m_monitors = list;
097 }
098 }
099 }
100
101 /**
102 * Return the list of monitors.
103 * @return an array of connected monitors
104 */
105 Monitor[] getMonitors()
106 {
107 if( null == m_monitors )
108 {
109 return EMPTY_MONITORS;
110 }
111 else
112 {
113 return (Monitor[]) m_monitors.toArray( new Monitor[0] );
114 }
115 }
116 }
117