OnePortAsyncChannelServerTest xref

    1   /***
    2    *
    3    * Copyright 2004 Hiram Chirino
    4    *
    5    * Licensed under the Apache License, Version 2.0 (the "License");
    6    * you may not use this file except in compliance with the License.
    7    * You may obtain a copy of the License at
    8    *
    9    * http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   *
    17   **/
    18  package org.activeio.oneport;
    19
    20  import java.io.IOException;
    21  import java.io.InputStream;
    22  import java.net.MalformedURLException;
    23  import java.net.URI;
    24  import java.net.URISyntaxException;
    25  import java.net.URL;
    26
    27  import javax.naming.NamingException;
    28
    29  import junit.framework.TestCase;
    30
    31  import org.activeio.AcceptListener;
    32  import org.activeio.AsynchChannel;
    33  import org.activeio.AsynchChannelFactory;
    34  import org.activeio.AsynchChannelServer;
    35  import org.activeio.Channel;
    36  import org.activeio.FilterAsynchChannelServer;
    37  import org.activeio.FilterSynchChannel;
    38  import org.activeio.Packet;
    39  import org.activeio.SynchChannel;
    40  import org.activeio.adapter.AsynchToSynchChannelAdapter;
    41  import org.activeio.adapter.SynchToAsynchChannelFactoryAdaptor;
    42  import org.activeio.net.SocketMetadata;
    43  import org.activeio.net.SocketSynchChannelFactory;
    44  import org.activeio.packet.ByteArrayPacket;
    45  import org.apache.commons.logging.Log;
    46  import org.apache.commons.logging.LogFactory;
    47
    48  import EDU.oswego.cs.dl.util.concurrent.Slot;
    49  import EDU.oswego.cs.dl.util.concurrent.SynchronizedInt;
    50  import EDU.oswego.cs.dl.util.concurrent.ThreadFactory;
    51  import EDU.oswego.cs.dl.util.concurrent.ThreadedExecutor;
    52
    53  /***
    54   */
    55  public class OnePortAsyncChannelServerTest extends TestCase {
    56
    57      static private Log log = LogFactory.getLog(OnePortAsyncChannelServerTest.class);
    58      static public SynchronizedInt serverPacketCounter = new SynchronizedInt(0);
    59
    60      public OnePortAsynchChannelServer server;
    61      public AsynchChannelServer httpServer;
    62      public AsynchChannelServer iiopServer;
    63      public SocketSynchChannelFactory channelFactory;
    64      public Slot resultSlot = new Slot();
    65
    66      public void testIIOPAccept() throws Exception {
    67          serverPacketCounter.set(0);
    68          hitIIOPServer();
    69          String type = (String) resultSlot.poll(1000 * 5);
    70          assertEquals("IIOP", type);
    71          // Verify that a request when through the one port.
    72          assertTrue(serverPacketCounter.get()>0);
    73      }
    74
    75      public void testHttpAccept() throws IOException, URISyntaxException, InterruptedException {
    76          serverPacketCounter.set(0);
    77          hitHttpServer();
    78          String type = (String) resultSlot.poll(1000 * 5 * 10000);
    79          assertEquals("HTTP", type);
    80          // Verify that a request when through the one port.
    81          assertTrue(serverPacketCounter.get()>0);
    82      }
    83
    84      protected void hitHttpServer() throws IOException, MalformedURLException {
    85          URI connectURI = server.getConnectURI();
    86          String url = "http://" + connectURI.getHost() + ":" + connectURI.getPort() + "/index.action";
    87          log.info(url);
    88          InputStream is = new URL(url).openStream();
    89          StringBuffer b = new StringBuffer();
    90          int c;
    91          while ((c = is.read()) >= 0) {
    92              b.append((char) c);
    93          }
    94
    95          log.info("HTTP response: " + b);
    96      }
    97
    98      protected void hitIIOPServer() throws Exception {
    99          SynchChannel channel = channelFactory.openSynchChannel(server.getConnectURI());
    100         ((SocketMetadata)channel.narrow(SocketMetadata.class)).setTcpNoDelay(true);
    101         channel.write(new ByteArrayPacket("GIOPcrapcrap".getBytes("UTF-8")));
    102         channel.flush();
    103         channel.dispose();
    104     }
    105
    106     public void testUnknownAccept() throws IOException, URISyntaxException, InterruptedException {
    107         SynchChannel channel = channelFactory.openSynchChannel(server.getConnectURI());
    108         ((SocketMetadata)channel.narrow(SocketMetadata.class)).setTcpNoDelay(true);
    109         channel
    110                 .write(new ByteArrayPacket("Licensed under the Apache License, Version 2.0 (the \"License\")"
    111                         .getBytes("UTF-8")));
    112         channel.flush();
    113         String type = (String) resultSlot.poll(1000 * 5);
    114         assertNull(type);
    115         channel.dispose();
    116     }
    117
    118     protected void setUp() throws Exception {
    119         channelFactory = new SocketSynchChannelFactory();
    120         ThreadedExecutor executor = new ThreadedExecutor();
    121         executor.setThreadFactory(new ThreadFactory(){
    122             int count=0;
    123             public Thread newThread(Runnable arg0) {
    124                 return new Thread(arg0, "activeio:"+(count++));
    125             }});
    126         AsynchChannelFactory factory = SynchToAsynchChannelFactoryAdaptor.adapt(channelFactory,executor);
    127
    128         AsynchChannelServer cs = factory.bindAsynchChannel(new URI("tcp://localhost:0"));
    129         cs = new FilterAsynchChannelServer(cs) {
    130             public void onAccept(Channel channel) {
    131                 SynchChannel synchChannel = AsynchToSynchChannelAdapter.adapt(channel);
    132                 super.onAccept(new FilterSynchChannel(synchChannel) {
    133                     public org.activeio.Packet read(long timeout) throws IOException {
    134                         Packet packet = super.read(timeout);
    135                         if( packet!=null && packet.hasRemaining() )
    136                             serverPacketCounter.increment();
    137                         return packet;
    138                     }
    139                 });
    140             }
    141         };
    142
    143         server = new OnePortAsynchChannelServer(cs);
    144         server.start();
    145
    146         startHTTPServer();
    147         startIIOPServer();
    148
    149         log.info("Running on: "+server.getConnectURI());
    150     }
    151
    152     /***
    153      * @throws IOException
    154      * @throws NamingException
    155      */
    156     protected void startIIOPServer() throws Exception {
    157         iiopServer = server.bindAsynchChannel(IIOPRecognizer.IIOP_RECOGNIZER);
    158         iiopServer.setAcceptListener(new AcceptListener() {
    159             public void onAccept(Channel channel) {
    160                 try {
    161                     log.info("Got a IIOP connection.");
    162                     resultSlot.offer("IIOP", 1);
    163                     channel.dispose();
    164                 } catch (InterruptedException e) {
    165                     e.printStackTrace();
    166                 }
    167             }
    168
    169             public void onAcceptError(IOException error) {
    170             }
    171         });
    172         iiopServer.start();
    173     }
    174
    175     /***
    176      * @throws IOException
    177      * @throws Exception
    178      */
    179     protected void startHTTPServer() throws Exception {
    180         httpServer = server.bindAsynchChannel(HttpRecognizer.HTTP_RECOGNIZER);
    181         httpServer.setAcceptListener(new AcceptListener() {
    182             public void onAccept(Channel channel) {
    183                 try {
    184                     log.info("Got a HTTP connection.");
    185                     resultSlot.offer("HTTP", 1);
    186
    187                     byte data[] = ("HTTP/1.1 200 OK\r\n" + "Content-Type: text/html; charset=UTF-8\r\n" + "\r\n"
    188                             + "Hello World").getBytes("UTF-8");
    189
    190                     ((SocketMetadata)channel.narrow(SocketMetadata.class)).setTcpNoDelay(true);
    191                     ((AsynchChannel) channel).write(new ByteArrayPacket(data));
    192
    193                     channel.dispose();
    194                 } catch (Throwable e) {
    195                     e.printStackTrace();
    196                 }
    197             }
    198
    199             public void onAcceptError(IOException error) {
    200             }
    201         });
    202         httpServer.start();
    203     }
    204
    205     protected void tearDown() throws Exception {
    206         stopIIOPServer();
    207         stopHTTPServer();
    208         server.dispose();
    209     }
    210
    211     /***
    212      * @throws InterruptedException
    213      *
    214      */
    215     protected void stopHTTPServer() throws InterruptedException {
    216         httpServer.dispose();
    217     }
    218
    219     /***
    220      * @throws Exception
    221      *
    222      */
    223     protected void stopIIOPServer() throws Exception {
    224         iiopServer.dispose();
    225     }
    226 }