View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.testserver;
29  
30  import java.io.IOException;
31  import java.net.InetAddress;
32  import java.net.Socket;
33  import java.net.SocketException;
34  import java.util.concurrent.TimeUnit;
35  
36  import org.apache.commons.logging.Log;
37  import org.apache.commons.logging.LogFactory;
38  import org.apache.http.ConnectionClosedException;
39  import org.apache.http.ExceptionLogger;
40  import org.apache.http.HttpConnectionFactory;
41  import org.apache.http.config.SocketConfig;
42  import org.apache.http.impl.bootstrap.ServerBootstrap;
43  import org.apache.http.protocol.HttpExpectationVerifier;
44  import org.apache.http.protocol.HttpRequestHandler;
45  import org.apache.http.protocol.UriHttpRequestHandlerMapper;
46  import org.apache.http.util.Asserts;
47  
48  public class HttpServer {
49  
50      private final UriHttpRequestHandlerMapper reqistry;
51      private volatile HttpExpectationVerifier expectationVerifier;
52      private volatile int timeout;
53  
54      private volatile org.apache.http.impl.bootstrap.HttpServer server;
55  
56      public HttpServer() throws IOException {
57          super();
58          this.reqistry = new UriHttpRequestHandlerMapper();
59      }
60  
61      public int getTimeout() {
62          return this.timeout;
63      }
64  
65      public void setTimeout(final int timeout) {
66          this.timeout = timeout;
67      }
68  
69      public void registerHandler(
70              final String pattern,
71              final HttpRequestHandler handler) {
72          this.reqistry.register(pattern, handler);
73      }
74  
75      public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
76          this.expectationVerifier = expectationVerifier;
77      }
78  
79      public int getPort() {
80          final org.apache.http.impl.bootstrap.HttpServer local = this.server;
81          if (local != null) {
82              return this.server.getLocalPort();
83          } else {
84              throw new IllegalStateException("Server not running");
85          }
86      }
87  
88      public InetAddress getInetAddress() {
89          final org.apache.http.impl.bootstrap.HttpServer local = this.server;
90          if (local != null) {
91              return local.getInetAddress();
92          } else {
93              throw new IllegalStateException("Server not running");
94          }
95      }
96  
97      public void start() throws IOException {
98          Asserts.check(this.server == null, "Server already running");
99          this.server = ServerBootstrap.bootstrap()
100                 .setSocketConfig(SocketConfig.custom()
101                         .setSoTimeout(this.timeout)
102                         .build())
103                 .setServerInfo("TEST-SERVER/1.1")
104                 .setConnectionFactory(new LoggingConnFactory())
105                 .setExceptionLogger(new SimpleExceptionLogger())
106                 .setExpectationVerifier(this.expectationVerifier)
107                 .setHandlerMapper(this.reqistry)
108                 .create();
109         this.server.start();
110     }
111 
112     public void shutdown() {
113         final org.apache.http.impl.bootstrap.HttpServer local = this.server;
114         this.server = null;
115         if (local != null) {
116             local.shutdown(5, TimeUnit.SECONDS);
117         }
118     }
119 
120     static class LoggingConnFactory implements HttpConnectionFactory<LoggingBHttpServerConnection> {
121 
122         @Override
123         public LoggingBHttpServerConnection createConnection(final Socket socket) throws IOException {
124             final LoggingBHttpServerConnection conn = new LoggingBHttpServerConnection(8 * 1024);
125             conn.bind(socket);
126             return conn;
127         }
128     }
129 
130     static class SimpleExceptionLogger implements ExceptionLogger {
131 
132         private final Log log = LogFactory.getLog(HttpServer.class);
133 
134         @Override
135         public void log(final Exception ex) {
136             if (ex instanceof ConnectionClosedException) {
137                 this.log.debug(ex.getMessage());
138             } else if (ex instanceof SocketException) {
139                 this.log.debug(ex.getMessage());
140             } else {
141                 this.log.error(ex.getMessage(), ex);
142             }
143         }
144     }
145 
146 }