01: package pygmy.core;
02:
03: import java.io.IOException;
04: import java.io.EOFException;
05: import java.util.Properties;
06: import java.util.logging.Logger;
07: import java.util.logging.Level;
08: import java.net.HttpURLConnection;
09: import java.net.Socket;
10:
11: public class ConnectionRunnable implements Runnable {
12: private static final Logger log = Logger
13: .getLogger(ConnectionRunnable.class.getName());
14:
15: protected Server server;
16: protected Socket connection;
17: protected Properties config;
18: protected String scheme;
19:
20: public ConnectionRunnable(Server aServer, String aScheme,
21: Socket aConnection, Properties aConnectionConfig) {
22: this .scheme = aScheme;
23: this .server = aServer;
24: this .connection = aConnection;
25: this .config = aConnectionConfig;
26: }
27:
28: public void run() {
29: try {
30: boolean next = false;
31: do {
32: HttpRequest request = createRequest();
33: if (request.readRequest(connection.getInputStream())) {
34: HttpResponse response = new HttpResponse(request,
35: connection.getOutputStream(), server
36: .getResponseListeners());
37: if (log.isLoggable(Level.INFO)) {
38: log.info(connection.getInetAddress()
39: .getHostAddress()
40: + ":"
41: + connection.getPort()
42: + " - "
43: + request.getUrl());
44: }
45: if (!server.post(request, response)) {
46: response.sendError(
47: HttpURLConnection.HTTP_NOT_FOUND,
48: " was not found on this server.");
49: }
50: next = response.isKeepAlive();
51: if (!next) {
52: log.info("Closing connection.");
53: response.addHeader("Connection", "close");
54: }
55: response.commitResponse();
56: } else {
57: log.info("No request sent. Closing connection.");
58: next = false;
59: }
60: } while (next);
61: } catch (EOFException eof) {
62: log.finer("Closing connection");
63: // do nothing
64: } catch (IOException e) {
65: log.log(Level.WARNING, "IOException", e);
66: } catch (Exception e) {
67: log.log(Level.WARNING, "Handler threw an exception.", e);
68: } finally {
69: try {
70: connection.close();
71: } catch (IOException e) {
72: }
73: }
74: }
75:
76: protected HttpRequest createRequest() throws IOException {
77: return new HttpRequest(scheme, connection, config);
78: }
79: }
|