1 19 20 package org.apache.avalon.cornerstone.blocks.connection; 21 22 import java.net.ServerSocket ; 23 import java.util.HashMap ; 24 import org.apache.avalon.cornerstone.services.connection.ConnectionHandlerFactory; 25 import org.apache.avalon.cornerstone.services.connection.ConnectionManager; 26 import org.apache.avalon.cornerstone.services.threads.ThreadManager; 27 import org.apache.excalibur.thread.ThreadPool; 28 29 34 public class AbstractConnectionManager implements ConnectionManager 35 { 36 private final HashMap m_connections = new HashMap (); 37 protected ThreadManager m_threadManager; 38 protected ConnectionMonitor monitor; 39 40 41 52 public synchronized void connect( String name, 53 ServerSocket socket, 54 ConnectionHandlerFactory handlerFactory, 55 ThreadPool threadPool ) 56 throws Exception 57 { 58 if( null != m_connections.get( name ) ) 59 { 60 final String message = "Connection already exists with name " + name; 61 throw new IllegalArgumentException ( message ); 62 } 63 64 if( 0 == socket.getSoTimeout() ) 66 { 67 socket.setSoTimeout( 500 ); 68 } 69 70 final Connection runner = 71 new Connection( socket, handlerFactory, threadPool, monitor ); 72 m_connections.put( name, runner ); 73 threadPool.execute( runner ); 74 } 75 76 85 public void connect( String name, 86 ServerSocket socket, 87 ConnectionHandlerFactory handlerFactory ) 88 throws Exception 89 { 90 connect( name, socket, handlerFactory, m_threadManager.getDefaultThreadPool() ); 91 } 92 93 99 public void disconnect( final String name ) 100 throws Exception 101 { 102 disconnect( name, false ); 103 } 104 105 115 public synchronized void disconnect( final String name, final boolean tearDown ) 116 throws Exception 117 { 118 final Connection connection = (Connection)m_connections.remove( name ); 119 120 if( connection != null ) 121 { 122 connection.dispose(); 124 } 125 else 126 { 127 final String error = 128 "Invalid request for the disconnection of an unrecognized connection name: " 129 + name; 130 throw new IllegalArgumentException ( error ); 131 } 132 } 133 public void dispose() 134 { 135 if( monitor.isDebugEnabled(this.getClass()) ) 136 { 137 monitor.debugMessage(this.getClass(), "disposal" ); 138 } 139 final String [] names = (String [])m_connections.keySet().toArray( new String [ 0 ] ); 140 for( int i = 0; i < names.length; i++ ) 141 { 142 try 143 { 144 disconnect( names[ i ] ); 145 } 146 catch( final Exception e ) 147 { 148 final String message = "Error disconnecting " + names[ i ]; 149 monitor.unexpectedException(this.getClass(), message, e ); 150 } 151 } 152 } 153 } 154 | Popular Tags |