KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > tutorial > SimpleConnectionHandler


1 /*
2  * Copyright 2004 Apache Software Foundation
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12  * implied.
13  *
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 package tutorial;
19
20 import java.io.ByteArrayOutputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.io.InputStream JavaDoc;
23 import java.net.ProtocolException JavaDoc;
24 import java.net.Socket JavaDoc;
25 import java.nio.ByteBuffer JavaDoc;
26
27 import org.apache.avalon.cornerstone.services.connection.ConnectionHandler;
28 import org.apache.avalon.framework.logger.Logger;
29
30 /**
31  * Simple connection handler for our web server. It conforms to HTTP/1.0 only.
32  * This handler will perform the following tasks:
33  * <ul>
34  * <li>Parse the request
35  * <li>Build the reply
36  * <li>Send the reply
37  * </ul>
38  *
39  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
40  */

41 public class SimpleConnectionHandler
42     implements ConnectionHandler {
43   /**
44    * Internal reference to the logging channel supplied by the container.
45    */

46   private Logger m_logger;
47
48   /**
49    * Processes connections as they occur.
50    *
51    * @param socket the socket connection
52    * @throws IOException if an error reading from the socket occurs
53    * @throws ProtocolException if an error handling the connection occurs
54    *
55    * @see org.apache.avalon.cornerstone.services.connection.ConnectionHandler#handleConnection(java.net.Socket)
56    */

57   public void handleConnection(Socket JavaDoc socket) throws IOException JavaDoc,
58       ProtocolException JavaDoc {
59     Request req;
60
61     // who has connected to us?
62
String JavaDoc remoteHost = socket.getInetAddress().getHostName();
63     String JavaDoc remoteIP = socket.getInetAddress().getHostAddress();
64     getLogger().info("Connection received on port " + socket.getLocalPort()
65                      + " from " + remoteHost + " (" + remoteIP + ")");
66
67     // get a request object...
68
InputStream JavaDoc input = socket.getInputStream();
69     ByteArrayOutputStream JavaDoc output = new ByteArrayOutputStream JavaDoc();
70     byte[] bytes = new byte[1024];
71     int count = input.read(bytes);
72     while (count > -1) {
73       output.write(bytes, 0, count);
74       if (input.available() == 0) {
75         break;
76       }
77       count = input.read(bytes);
78     }
79     output.flush();
80     output.close();
81
82     getLogger().debug("Preparing byte buffer...");
83     ByteBuffer JavaDoc bb = ByteBuffer.allocate(output.size());
84     bb.put(output.toByteArray());
85     bb.flip();
86     getLogger().debug("Byte buffer prepared");
87     try {
88       getLogger().debug("Parsing request...");
89       req = Request.parse(bb);
90     }
91     catch (MalformedRequestException e) {
92       getLogger().error(e.getMessage(), e);
93       throw new ProtocolException JavaDoc(e.getMessage());
94     }
95
96     // Handle the request -- only accept HTTP GET
97
if (!req.isGet()) {
98       getLogger().debug("Sending HTTP 405...");
99       Reply.sendHttpReply(socket.getOutputStream(), Reply.HTTP_405,
100                           "This server only accepts GET");
101     }
102     else {
103       getLogger().debug("Sending HTTP 200...");
104       Reply.sendHttpReply(socket.getOutputStream(), Reply.HTTP_200,
105                           "Hello, World!");
106     }
107   }
108
109   /**
110    * Sets the container-supplied logger.
111    */

112   public void setLogger(Logger logger) {
113     m_logger = logger;
114   }
115
116   /**
117    * Return the logging channel assigned to us by the container.
118    * @return the logging channel
119    */

120   private Logger getLogger() {
121     return m_logger;
122   }
123 }
124
Popular Tags