1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  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,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License. 
18   *  
19   */
20  package org.apache.mina.example.echoserver;
21  
22  import java.io.IOException;
23  import java.net.InetSocketAddress;
24  import java.net.SocketAddress;
25  
26  import junit.framework.TestCase;
27  
28  import org.apache.mina.common.ByteBuffer;
29  import org.apache.mina.common.IoAcceptor;
30  import org.apache.mina.common.IoSession;
31  import org.apache.mina.example.echoserver.ssl.BogusSSLContextFactory;
32  import org.apache.mina.filter.SSLFilter;
33  import org.apache.mina.transport.socket.nio.DatagramAcceptor;
34  import org.apache.mina.transport.socket.nio.DatagramSessionConfig;
35  import org.apache.mina.transport.socket.nio.SocketAcceptor;
36  import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
37  import org.apache.mina.util.SessionLog;
38  
39  /**
40   * Tests echo server example.
41   * 
42   * @author The Apache Directory Project (mina-dev@directory.apache.org)
43   * @version $Rev:448075 $, $Date:2006-09-20 05:26:53Z $
44   */
45  public abstract class AbstractTest extends TestCase {
46      protected boolean useSSL;
47  
48      protected int port;
49  
50      protected SocketAddress boundAddress;
51  
52      protected IoAcceptor datagramAcceptor;
53  
54      protected IoAcceptor socketAcceptor;
55  
56      protected AbstractTest() {
57      }
58  
59      protected static void assertEquals(byte[] expected, byte[] actual) {
60          assertEquals(toString(expected), toString(actual));
61      }
62  
63      protected static void assertEquals(ByteBuffer expected, ByteBuffer actual) {
64          assertEquals(toString(expected), toString(actual));
65      }
66  
67      protected static String toString(byte[] buf) {
68          StringBuffer str = new StringBuffer(buf.length * 4);
69          for (int i = 0; i < buf.length; i++) {
70              str.append(buf[i]);
71              str.append(' ');
72          }
73          return str.toString();
74      }
75  
76      protected static String toString(ByteBuffer buf) {
77          return buf.getHexDump();
78      }
79  
80      protected void setUp() throws Exception {
81          // Disable SSL by default
82          useSSL = false;
83          final SSLFilter sslFilter = new SSLFilter(BogusSSLContextFactory
84                  .getInstance(true));
85  
86          boundAddress = null;
87          datagramAcceptor = new DatagramAcceptor();
88          socketAcceptor = new SocketAcceptor();
89  
90          ((DatagramSessionConfig) datagramAcceptor.getDefaultConfig()
91                  .getSessionConfig()).setReuseAddress(true);
92          ((SocketAcceptorConfig) socketAcceptor.getDefaultConfig())
93                  .setReuseAddress(true);
94  
95          // Find an availble test port and bind to it.
96          boolean socketBound = false;
97          boolean datagramBound = false;
98  
99          // Let's start from port #1 to detect possible resource leak
100         // because test will fail in port 1-1023 if user run this test
101         // as a normal user.
102 
103         SocketAddress address = null;
104 
105         for (port = 1; port <= 65535; port++) {
106             socketBound = false;
107             datagramBound = false;
108 
109             address = new InetSocketAddress(port);
110 
111             try {
112                 socketAcceptor.bind(address, new EchoProtocolHandler() {
113                     public void sessionCreated(IoSession session) {
114                         if (useSSL) {
115                             session.getFilterChain().addFirst("SSL", sslFilter);
116                         }
117                     }
118 
119                     // This is for TLS reentrance test
120                     public void messageReceived(IoSession session,
121                             Object message) throws Exception {
122                         if (!(message instanceof ByteBuffer)) {
123                             return;
124                         }
125 
126                         ByteBuffer buf = (ByteBuffer) message;
127                         if (session.getFilterChain().contains("SSL")
128                                 && buf.remaining() == 1
129                                 && buf.get() == (byte) '.') {
130                             SessionLog.info(session, "TLS Reentrance");
131                             ((SSLFilter) session.getFilterChain().get("SSL"))
132                                     .startSSL(session);
133 
134                             // Send a response
135                             buf = ByteBuffer.allocate(1);
136                             buf.put((byte) '.');
137                             buf.flip();
138                             session
139                                     .setAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE);
140                             session.write(buf);
141                         } else {
142                             super.messageReceived(session, message);
143                         }
144                     }
145                 });
146                 socketBound = true;
147 
148                 datagramAcceptor.bind(address, new EchoProtocolHandler());
149                 datagramBound = true;
150 
151                 break;
152             } catch (IOException e) {
153             } finally {
154                 if (socketBound && !datagramBound) {
155                     socketAcceptor.unbind(address);
156                 }
157                 if (datagramBound && !socketBound) {
158                     datagramAcceptor.unbind(address);
159                 }
160             }
161         }
162 
163         // If there is no port available, test fails.
164         if (!socketBound || !datagramBound) {
165             throw new IOException("Cannot bind any test port.");
166         }
167 
168         boundAddress = address;
169         System.out.println("Using port " + port + " for testing.");
170     }
171 
172     protected void tearDown() throws Exception {
173         if (boundAddress != null) {
174             socketAcceptor.unbind(boundAddress);
175             datagramAcceptor.unbind(boundAddress);
176         }
177     }
178 }