43 import java.nio.channels.*;
52 class RequestHandler
implements Handler {
54 private ChannelIO cio;
55 private ByteBuffer rbb =
null;
57 private boolean requestReceived =
false;
58 private Request request =
null;
59 private Reply reply =
null;
61 private static int created = 0;
63 RequestHandler(ChannelIO cio) {
67 synchronized (RequestHandler.class) {
69 if ((created % 50) == 0) {
70 System.out.println(
".");
73 System.out.print(
".");
81 private boolean receive(SelectionKey sk)
throws IOException {
82 ByteBuffer tmp =
null;
84 if (requestReceived) {
88 if (!cio.doHandshake(sk)) {
92 if ((cio.read() < 0) || Request.isComplete(cio.getReadBuf())) {
93 rbb = cio.getReadBuf();
94 return (requestReceived =
true);
101 private boolean parse() throws IOException {
103 request = Request.parse(rbb);
105 }
catch (MalformedRequestException x) {
106 reply =
new Reply(Reply.Code.BAD_REQUEST,
107 new StringContent(x));
114 private void build() throws IOException {
115 Request.Action action = request.action();
116 if ((action != Request.Action.GET) &&
117 (action != Request.Action.HEAD)) {
118 reply =
new Reply(Reply.Code.METHOD_NOT_ALLOWED,
119 new StringContent(request.toString()));
121 reply =
new Reply(Reply.Code.OK,
122 new FileContent(request.uri()), action);
125 public void handle(SelectionKey sk)
throws IOException {
128 if (request ==
null) {
136 }
catch (IOException x) {
138 reply =
new Reply(Reply.Code.NOT_FOUND,
139 new StringContent(x));
144 sk.interestOps(SelectionKey.OP_WRITE);
147 if (cio.shutdown()) {
154 if (cio.shutdown()) {
160 }
catch (IOException x) {
161 String m = x.getMessage();
162 if (!m.equals(
"Broken pipe") &&
163 !m.equals(
"Connection reset by peer")) {
164 System.err.println(
"RequestHandler: " + x.toString());
175 }
catch (IOException e) {
187 private boolean send() throws IOException {
189 return reply.send(cio);
190 }
catch (IOException x) {
191 if (x.getMessage().startsWith(
"Resource temporarily")) {
192 System.err.println(
"## RTA");