View Javadoc

1   /*
2    * $Id: MockHttpServer.java 21939 2011-05-18 13:32:09Z aperepel $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.transport.http.functional;
12  
13  import java.io.BufferedReader;
14  import java.io.InputStream;
15  import java.io.InputStreamReader;
16  import java.io.OutputStream;
17  import java.net.ServerSocket;
18  import java.net.Socket;
19  import java.util.concurrent.CountDownLatch;
20  
21  public abstract class MockHttpServer extends Object implements Runnable
22  {
23      private int listenPort;
24      private CountDownLatch startupLatch;
25      private CountDownLatch testCompleteLatch;
26  
27      public MockHttpServer(int listenPort, CountDownLatch startupLatch, CountDownLatch testCompleteLatch)
28      {
29          this.listenPort = listenPort;
30          this.startupLatch = startupLatch;
31          this.testCompleteLatch = testCompleteLatch;
32      }
33      
34      protected abstract void readHttpRequest(BufferedReader reader) throws Exception;
35      
36      public void run()
37      {
38          try
39          {
40              ServerSocket serverSocket = new ServerSocket(listenPort);
41              
42              // now that we are up and running, the test may send
43              startupLatch.countDown();
44              
45              Socket socket = serverSocket.accept();
46              InputStream in = socket.getInputStream();
47              BufferedReader reader = new BufferedReader(new InputStreamReader(in));
48              
49              // process the contents of the HTTP request
50              readHttpRequest(reader);
51              
52              OutputStream out = socket.getOutputStream();
53              out.write("HTTP/1.1 200 OK\n\n".getBytes());
54              
55              in.close();
56              out.close();
57              socket.close();
58              serverSocket.close();
59          }
60          catch (Exception ex)
61          {
62              throw new RuntimeException(ex);
63          }
64          finally
65          {
66              testCompleteLatch.countDown();
67          }
68      }
69  }
70  
71