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