View Javadoc

1   /*
2    * $Id: MockHttpServer.java 19191 2010-08-25 21:05:23Z tcarlson $
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  
20  import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
21  
22  public abstract class MockHttpServer extends Object implements Runnable
23  {
24      private int listenPort;
25      private CountDownLatch startupLatch;
26      private CountDownLatch testCompleteLatch;
27  
28      public MockHttpServer(int listenPort, CountDownLatch startupLatch, CountDownLatch testCompleteLatch)
29      {
30          this.listenPort = listenPort;
31          this.startupLatch = startupLatch;
32          this.testCompleteLatch = testCompleteLatch;
33      }
34      
35      protected abstract void readHttpRequest(BufferedReader reader) throws Exception;
36      
37      public void run()
38      {
39          try
40          {
41              ServerSocket serverSocket = new ServerSocket(listenPort);
42              
43              // now that we are up and running, the test may send
44              startupLatch.countDown();
45              
46              Socket socket = serverSocket.accept();
47              InputStream in = socket.getInputStream();
48              BufferedReader reader = new BufferedReader(new InputStreamReader(in));
49              
50              // process the contents of the HTTP request
51              readHttpRequest(reader);
52              
53              OutputStream out = socket.getOutputStream();
54              out.write("HTTP/1.1 200 OK\n\n".getBytes());
55              
56              in.close();
57              out.close();
58              socket.close();
59              serverSocket.close();
60          }
61          catch (Exception ex)
62          {
63              throw new RuntimeException(ex);
64          }
65          finally
66          {
67              testCompleteLatch.countDown();
68          }
69      }
70  }
71  
72