File: TestHttpServer.java

package info (click to toggle)
mauve 20120103-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 28,504 kB
  • sloc: java: 250,155; sh: 2,834; xml: 208; makefile: 66
file content (276 lines) | stat: -rw-r--r-- 7,361 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//Tags: not-a-test

//Copyright (C) 2006 Free Software Foundation, Inc.
//Written by Wolfgang Baer (WBaer@gmx.de)

//This file is part of Mauve.

//Mauve is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 2, or (at your option)
//any later version.

//Mauve is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with Mauve; see the file COPYING.  If not, write to
//the Free Software Foundation, 51 Franklin Street, Fifth Floor,
//Boston, MA, 02110-1301 USA.

package gnu.testlet.java.net.HttpURLConnection;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;


/**
 * A HTTP server for testing purpose only. The server can
 * be started on a given port and the response headers and
 * response body to be returned set. This way one can test
 * arbritrary testcases for the http client side library.
 *  
 * @see gnu.testlet.java.net.HttpURLConnection.responseCodeTest
 * @see gnu.testlet.java.net.HttpURLConnection.responseHeadersTest
 * 
 * @author Wolfgang Baer (WBaer@gmx.de)
 */
public final class TestHttpServer implements Runnable
{ 
  
  public interface ConnectionHandlerFactory
  {
    ConnectionHandler newConnectionHandler(Socket s) throws IOException;
  }
  
  /**
   * The request handler skeleton.
   */
  public static abstract class ConnectionHandler implements Runnable
  {  
    protected Socket socket;
    protected OutputStream output;
    protected InputStream input;

    ConnectionHandler(Socket socket) throws IOException
    {
      this.socket = socket;
      output = socket.getOutputStream();
      input = socket.getInputStream();
    }

    /**
     * Process one request on the connection.
     * 
     * @param headers
     * @param body
     * @return true if another request should be read from the connection.
     * @throws IOException
     */
    protected abstract boolean processConnection(List headers, byte[] body)
      throws IOException;

    protected String getHeaderFromList(List headers, String h)
    {
      String search = (h + ":").toLowerCase();
      Iterator it = headers.iterator();
      while (it.hasNext())
        {
          String v = (String)it.next();
          String k = v.toLowerCase();
          if (k.startsWith(search))
            return v.substring(search.length()).trim();
        }
      return null;
    }

    public void run()
    {
      try
        {
          List headerList;
          int contentLength = -1;
          byte[] body;
          do
            {
              headerList = new ArrayList();

              ByteArrayOutputStream line;
              line = new ByteArrayOutputStream();
              for (;;)
                {
                  int ch = input.read();
                  if (-1 == ch)
                    break; // EOF
              
                  if (ch !=  0x0a) // LF
                    line.write(ch);
                  else
                    {
                      byte[] array = line.toByteArray();
                      if (array.length == 1) // the last is only a LF
                        break;
        	
                      String headerLine = new String(array);
                      if (headerLine.length() > 15 &&
                          "Content-Length:".equalsIgnoreCase(headerLine.substring(0,15)))
                        {
                          contentLength = Integer.parseInt(headerLine.substring(15).trim());
                        }
                      headerList.add(headerLine);
                      line = new ByteArrayOutputStream();
                    }
                }

              if (contentLength > 0) 
                {
                  body = new byte[contentLength];
                  int pos = 0;
                  while (pos < contentLength)
                    {
                      int nr = input.read(body, pos, body.length - pos);
                      if (-1 == nr)
                        break;
                      pos += nr;
                    }
                }
              else
                body = null;
              contentLength = -1;
              // Check everything
            } while (processConnection(headerList, body));

          // Clean up
          output.close();
          input.close();
          socket.close();            
        }
      catch (Exception e)
        {
          // ignore
        }
    }

    protected void forceClosed()
    {
      try
        {
          socket.close();
        }
      catch (IOException ioe)
        {
          // Ignore.
        }
    }
  }

  boolean kill = false;
  ServerSocket serverSocket;  
  ConnectionHandlerFactory connectionHandlerFactory;
  
  /**
   * Create a TestHttpServer on an unused port.
   */
  public TestHttpServer() throws IOException
  {
    serverSocket = new ServerSocket(0);
    Thread t = new Thread(this, "TestHttpServer");
    t.start();
  }
  
  /**
   * The local port on which the test server is listening for connections.
   * @return the port
   */
  public int getPort()
  {
    return serverSocket.getLocalPort();
  }
  
  public synchronized void setConnectionHandlerFactory(ConnectionHandlerFactory f)
  {
    connectionHandlerFactory = f;
  }
  
  /**
   * This cleans up recources so more than one
   * TestHttpServer can be used in one mauve run.
   */
  public void killTestServer()
  {
    kill = true;
    closeAllConnections();
    try
      {
        serverSocket.close();
      }
    catch (IOException e)
      {
        // ignore
      }
  }
  
  private List activeConnections = new LinkedList();
  
  /**
   * Listens on the port and creates a Handler for
   * incoming connections.
   */
  public void run() 
  {   
    try
      {
        while (! kill)
          {
            Socket socket = serverSocket.accept();
            try
              {
                ConnectionHandlerFactory f;
                synchronized(this)
                  {
                    f = connectionHandlerFactory;
                  }
                ConnectionHandler request = f.newConnectionHandler(socket);
                Thread thread = new Thread(request);
                thread.start();
                synchronized(activeConnections)
                  {
                    activeConnections.add(request);
                  }
              }
            catch (Exception e)
              {
                // ignore
              }
          }
      }
    catch (IOException e)
      {
        // ignore
      }
  }
  
  public void closeAllConnections()
  {
    synchronized (activeConnections)
      {
        Iterator it = activeConnections.iterator();
        while (it.hasNext())
          {
            ConnectionHandler request = (ConnectionHandler)it.next();
            request.forceClosed();
            it.remove();
          }
      }
  }
}