1   /*
2    *   @(#) $Id: ConnectorTest.java 332218 2005-11-10 03:52:42Z trustin $
3    *
4    *   Copyright 2004 The Apache Software Foundation
5    *
6    *   Licensed under the Apache License, Version 2.0 (the "License");
7    *   you may not use this file except in compliance with the License.
8    *   You may obtain a copy of the License at
9    *
10   *       http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *   Unless required by applicable law or agreed to in writing, software
13   *   distributed under the License is distributed on an "AS IS" BASIS,
14   *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   *   See the License for the specific language governing permissions and
16   *   limitations under the License.
17   *
18   */
19  package org.apache.mina.examples.echoserver;
20  
21  import java.net.BindException;
22  import java.net.InetAddress;
23  import java.net.InetSocketAddress;
24  
25  import junit.framework.Assert;
26  
27  import org.apache.mina.common.ByteBuffer;
28  import org.apache.mina.common.TransportType;
29  import org.apache.mina.examples.echoserver.ssl.BogusSSLContextFactory;
30  import org.apache.mina.io.IoAcceptor;
31  import org.apache.mina.io.IoConnector;
32  import org.apache.mina.io.IoHandlerAdapter;
33  import org.apache.mina.io.IoSession;
34  import org.apache.mina.io.datagram.DatagramConnector;
35  import org.apache.mina.io.filter.SSLFilter;
36  import org.apache.mina.io.socket.SocketConnector;
37  import org.apache.mina.util.AvailablePortFinder;
38  
39  /***
40   * Tests echo server example.
41   * 
42   * @author The Apache Directory Project (dev@directory.apache.org)
43   * @version $Rev: 332218 $, $Date: 2005-11-10 12:52:42 +0900 $
44   */
45  public class ConnectorTest extends AbstractTest
46  {
47      public ConnectorTest()
48      {
49      }
50  
51      public void testTCP() throws Exception
52      {
53          IoConnector connector = new SocketConnector();
54          testConnector( connector );
55      }
56      
57      public void testTCPWithSSL() throws Exception
58      {
59          // Add an SSL filter to acceptor
60          SSLFilter acceptorSSLFilter =
61              new SSLFilter( BogusSSLContextFactory.getInstance( true ) );
62          IoAcceptor acceptor = registry.getIoAcceptor( TransportType.SOCKET );
63          acceptor.getFilterChain().addLast( "SSL", acceptorSSLFilter );
64  
65          // Create a connector
66          IoConnector connector = new SocketConnector();
67          
68          // Add an SSL filter to connector
69          SSLFilter connectorSSLFilter =
70              new SSLFilter( BogusSSLContextFactory.getInstance( false ) );
71          connectorSSLFilter.setUseClientMode( true ); // set client mode
72          connector.getFilterChain().addLast( "SSL", connectorSSLFilter );
73  
74          testConnector( connector );
75      }
76      
77      public void testUDP() throws Exception
78      {
79          IoConnector connector = new DatagramConnector();
80          testConnector( connector );
81      }
82      
83      private void testConnector( IoConnector connector ) throws Exception
84      {
85          System.out.println("* Without localAddress");
86          testConnector( connector, false );
87          
88          System.out.println("* With localAddress");
89          testConnector( connector, true );
90      }
91      
92      private void testConnector( IoConnector connector, boolean useLocalAddress ) throws Exception
93      {
94          EchoConnectorHandler handler = new EchoConnectorHandler();
95          ByteBuffer readBuf = handler.readBuf;
96  
97          IoSession session = null;
98          if( !useLocalAddress )
99          {
100             session = connector.connect(
101                     new InetSocketAddress( InetAddress.getLocalHost(), port ),
102                     handler );
103         }
104         else
105         {
106             int clientPort = port;
107             for( int i = 0; i < 65536; i ++ )
108             {
109                 clientPort = AvailablePortFinder.getNextAvailable( clientPort + 1 );
110                 try
111                 {
112                     session = connector.connect(
113                             new InetSocketAddress( InetAddress.getLocalHost(), port ),
114                             new InetSocketAddress( clientPort ),
115                             handler );
116                     break;
117                 }
118                 catch( BindException e )
119                 {
120                     // Try again until we succeed to bind.
121                 }
122             }
123 
124             if( session == null )
125             {
126                 Assert.fail( "Failed to find out an appropriate local address." );
127             }
128         }
129         
130         for( int i = 0; i < 10; i ++ )
131         {
132             ByteBuffer buf = ByteBuffer.allocate( 16 );
133             buf.limit( 16 );
134             fillWriteBuffer( buf, i );
135             buf.flip();
136 
137             Object marker;
138             if( ( i & 1 ) == 0 )
139             {
140                 marker = new Integer( i );
141             }
142             else
143             {
144                 marker = null;
145             }
146 
147             session.write( buf, marker );
148 
149             // This will align message arrival order in UDP
150             for( int j = 0; j < 100; j ++ )
151             {
152                 if( readBuf.position() == ( i + 1 ) * 16 )
153                 {
154                     break;
155                 }
156                 Thread.sleep( 10 );
157             }
158         }
159         
160         for( int i = 0; i < 100; i++ ) {
161             if( readBuf.position() == 160 )
162             {
163                 break;
164             }
165             else
166             {
167                 Thread.sleep( 10 );
168             }
169         }
170 
171         session.close( true );
172         
173         Assert.assertEquals( 160, readBuf.position() );
174         readBuf.flip();
175         
176         ByteBuffer expectedBuf = ByteBuffer.allocate( 160 );
177         for( int i = 0; i < 10; i ++ ) {
178             expectedBuf.limit( ( i + 1 ) * 16 );
179             fillWriteBuffer( expectedBuf, i );
180         }
181         expectedBuf.position( 0 );
182         assertEquals(expectedBuf, readBuf);
183     }
184 
185     private void fillWriteBuffer( ByteBuffer writeBuf, int i )
186     {
187         while( writeBuf.remaining() > 0 )
188         {
189             writeBuf.put( ( byte ) ( i ++ ) );
190         }
191     }
192 
193     public static void main( String[] args )
194     {
195         junit.textui.TestRunner.run( ConnectorTest.class );
196     }
197     
198     private static class EchoConnectorHandler extends IoHandlerAdapter
199     {
200         private ByteBuffer readBuf = ByteBuffer.allocate( 1024 );
201         private int counter = 0;
202 
203         public void dataRead( IoSession session, ByteBuffer buf )
204         {
205             readBuf.put( buf );
206         }
207         
208         public void dataWritten( IoSession session, Object marker )
209         {
210             if( ( counter & 1 ) == 0 )
211             {
212                 Assert.assertEquals( new Integer( counter ), marker );
213             }
214             else
215             {
216                 Assert.assertNull( marker );
217             }
218             
219             counter ++;
220         }
221 
222         public void exceptionCaught( IoSession session, Throwable cause )
223         {
224             cause.printStackTrace();
225         }
226     }
227 }