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 package org.apache.commons.httpclient.server;
31
32 import java.io.IOException;
33 import java.io.InputStream;
34
35 import org.apache.commons.httpclient.Header;
36 import org.apache.commons.httpclient.HttpVersion;
37
38 /***
39 * This request handler provides service interface similar to that of Servlet API.
40 *
41 * @author Oleg Kalnichevski
42 */
43 public class HttpServiceHandler implements HttpRequestHandler {
44
45 private HttpService service = null;
46
47 public HttpServiceHandler(final HttpService service) {
48 super();
49 if (service == null) {
50 throw new IllegalArgumentException("Service may not be null");
51 }
52 this.service = service;
53 }
54
55 public boolean processRequest(
56 final SimpleHttpServerConnection conn,
57 final SimpleRequest request) throws IOException {
58 if (conn == null) {
59 throw new IllegalArgumentException("Connection may not be null");
60 }
61 if (request == null) {
62 throw new IllegalArgumentException("Request may not be null");
63 }
64 boolean complete = false;
65 SimpleResponse response = new SimpleResponse();
66 this.service.process(request, response);
67
68
69 request.getBodyBytes();
70
71
72 if (!response.containsHeader("Content-Type")) {
73 response.addHeader(new Header("Content-Type", "text/plain"));
74 }
75
76
77 if (!response.containsHeader("Content-Length") && !response.containsHeader("Transfer-Encoding")) {
78 InputStream content = response.getBody();
79 if (content != null) {
80 long len = response.getContentLength();
81 if (len < 0) {
82 if (response.getHttpVersion().lessEquals(HttpVersion.HTTP_1_0)) {
83 throw new IOException("Chunked encoding not supported for HTTP version "
84 + response.getHttpVersion());
85 }
86 Header header = new Header("Transfer-Encoding", "chunked");
87 response.addHeader(header);
88 } else {
89 Header header = new Header("Content-Length", Long.toString(len));
90 response.setHeader(header);
91 }
92 } else {
93 Header header = new Header("Content-Length", "0");
94 response.addHeader(header);
95 }
96 }
97
98 if (!response.containsHeader("Connection")) {
99
100 Header connheader = request.getFirstHeader("Connection");
101 if (connheader != null) {
102 if (connheader.getValue().equalsIgnoreCase("keep-alive")) {
103 Header header = new Header("Connection", "keep-alive");
104 response.addHeader(header);
105 conn.setKeepAlive(true);
106 }
107 if (connheader.getValue().equalsIgnoreCase("close")) {
108 Header header = new Header("Connection", "close");
109 response.addHeader(header);
110 conn.setKeepAlive(false);
111 }
112 } else {
113
114 if (response.getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
115 conn.setKeepAlive(true);
116 } else {
117 conn.setKeepAlive(false);
118 }
119 }
120 }
121 if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
122
123 response.setBody(null);
124 }
125 conn.writeResponse(response);
126 return true;
127 }
128
129 }