Source code: org/apache/http/examples/ElementalHttpServer.java
1 /*
2 * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/httpcore/tags/4.0-alpha2/src/examples/org/apache/http/examples/ElementalHttpServer.java $
3 * $Revision: 408030 $
4 * $Date: 2006-05-20 18:55:00 +0200 (Sat, 20 May 2006) $
5 *
6 * ====================================================================
7 *
8 * Copyright 1999-2006 The Apache Software Foundation
9 *
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 * http://www.apache.org/licenses/LICENSE-2.0
15 *
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 * ====================================================================
22 *
23 * This software consists of voluntary contributions made by many
24 * individuals on behalf of the Apache Software Foundation. For more
25 * information on the Apache Software Foundation, please see
26 * <http://www.apache.org/>.
27 *
28 */
29
30 package org.apache.http.examples;
31
32 import java.io.File;
33 import java.io.IOException;
34 import java.io.InterruptedIOException;
35 import java.net.ServerSocket;
36 import java.net.Socket;
37 import java.net.URLDecoder;
38
39 import org.apache.http.HttpException;
40 import org.apache.http.HttpRequest;
41 import org.apache.http.HttpResponse;
42 import org.apache.http.HttpServerConnection;
43 import org.apache.http.HttpStatus;
44 import org.apache.http.MethodNotSupportedException;
45 import org.apache.http.entity.FileEntity;
46 import org.apache.http.entity.StringEntity;
47 import org.apache.http.impl.DefaultHttpParams;
48 import org.apache.http.impl.DefaultHttpServerConnection;
49 import org.apache.http.params.HttpConnectionParams;
50 import org.apache.http.params.HttpParams;
51 import org.apache.http.params.HttpProtocolParams;
52 import org.apache.http.protocol.HttpService;
53 import org.apache.http.protocol.ResponseConnControl;
54 import org.apache.http.protocol.ResponseContent;
55 import org.apache.http.protocol.ResponseDate;
56 import org.apache.http.protocol.ResponseServer;
57
58 /**
59 * <p>
60 * </p>
61 * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
62 *
63 * @version $Revision: 408030 $
64 */
65 public class ElementalHttpServer {
66
67 public static void main(String[] args) throws Exception {
68 if (args.length < 1) {
69 System.err.println("Please specify document root directory");
70 System.exit(1);
71 }
72 Thread t = new RequestListenerThread(8080, args[0]);
73 t.setDaemon(false);
74 t.start();
75 }
76
77 static class FileServiceHandler extends HttpService {
78
79 public FileServiceHandler(final HttpServerConnection conn) {
80 super(conn);
81 }
82
83 protected void doService(final HttpRequest request, final HttpResponse response)
84 throws HttpException, IOException {
85 String method = request.getRequestLine().getMethod();
86 if (!method.equalsIgnoreCase("GET") && !method.equalsIgnoreCase("HEAD")) {
87 throw new MethodNotSupportedException(method + " method not supported");
88 }
89 String docroot = (String) request.getParams().getParameter("server.docroot");
90 String target = request.getRequestLine().getUri();
91 File file = new File(docroot, URLDecoder.decode(target));
92 if (!file.exists()) {
93 response.setStatusCode(HttpStatus.SC_NOT_FOUND);
94 StringEntity body = new StringEntity("File not found", "UTF-8");
95 response.setEntity(body);
96 System.out.println("File " + file.getPath() + " not found");
97 } else if (!file.canRead() || file.isDirectory()) {
98 response.setStatusCode(HttpStatus.SC_FORBIDDEN);
99 StringEntity body = new StringEntity("Access Denied", "UTF-8");
100 response.setEntity(body);
101 System.out.println("Cannot read file " + file.getPath());
102 } else {
103 response.setStatusCode(HttpStatus.SC_OK);
104 FileEntity body = new FileEntity(file, "text/html");
105 response.setEntity(body);
106 System.out.println("Serving file " + file.getPath());
107 }
108 }
109
110 protected void logMessage(final String s) {
111 System.out.println(s);
112 }
113
114 protected void logIOException(final IOException ex) {
115 System.err.println("IO error: " + ex.getMessage());
116 }
117
118 protected void logProtocolException(final HttpException ex) {
119 System.err.println("HTTP protocol error: " + ex.getMessage());
120 }
121
122 }
123
124 static class RequestListenerThread extends Thread {
125
126 private final ServerSocket serversocket;
127 private HttpParams params;
128
129 public RequestListenerThread(int port, final String docroot) throws IOException {
130 this.serversocket = new ServerSocket(port);
131 this.params = new DefaultHttpParams(null);
132 this.params
133 .setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000)
134 .setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024)
135 .setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false)
136 .setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true)
137 .setParameter(HttpProtocolParams.ORIGIN_SERVER, "Jakarta-HttpComponents/1.1")
138 .setParameter("server.docroot", docroot);
139 }
140
141 public void run() {
142 System.out.println("Listening on port " + this.serversocket.getLocalPort());
143 while (!Thread.interrupted()) {
144 try {
145 Socket socket = this.serversocket.accept();
146 HttpServerConnection conn = new DefaultHttpServerConnection();
147 System.out.println("Incoming connection from " + socket.getInetAddress());
148 conn.bind(socket, this.params);
149 FileServiceHandler fileServiceHandler = new FileServiceHandler(conn);
150
151 // Required protocol interceptors
152 fileServiceHandler.addInterceptor(new ResponseDate());
153 fileServiceHandler.addInterceptor(new ResponseServer());
154 fileServiceHandler.addInterceptor(new ResponseContent());
155 fileServiceHandler.addInterceptor(new ResponseConnControl());
156
157 fileServiceHandler.setParams(this.params);
158 Thread t = new ConnectionProcessorThread(fileServiceHandler);
159 t.setDaemon(true);
160 t.start();
161 } catch (InterruptedIOException ex) {
162 break;
163 } catch (IOException e) {
164 System.err.println("I/O error initialising connection thread: "
165 + e.getMessage());
166 break;
167 }
168 }
169 }
170 }
171
172 static class ConnectionProcessorThread extends Thread {
173
174 private final HttpService httpservice;
175
176 public ConnectionProcessorThread(final HttpService httpservice) {
177 super();
178 this.httpservice = httpservice;
179 }
180
181 public void run() {
182 System.out.println("New connection thread");
183 try {
184 while (!Thread.interrupted() && !this.httpservice.isDestroyed() && this.httpservice.isActive()) {
185 this.httpservice.handleRequest();
186 }
187 } finally {
188 this.httpservice.destroy();
189 }
190 }
191
192 }
193 }