1 36 37 import java.io.*; 38 import java.nio.*; 39 import java.nio.channels.*; 40 41 49 class RequestHandler implements Handler { 50 51 private ChannelIO cio; 52 private ByteBuffer rbb = null; 53 54 private boolean requestReceived = false; 55 private Request request = null; 56 private Reply reply = null; 57 58 private static int created = 0; 59 60 RequestHandler(ChannelIO cio) { 61 this.cio = cio; 62 63 synchronized (RequestHandler.class) { 65 created++; 66 if ((created % 50) == 0) { 67 System.out.println("."); 68 created = 0; 69 } else { 70 System.out.print("."); 71 } 72 } 73 } 74 75 private boolean receive(SelectionKey sk) throws IOException { 79 ByteBuffer tmp = null; 80 81 if (requestReceived) { 82 return true; 83 } 84 85 if (!cio.doHandshake(sk)) { 86 return false; 87 } 88 89 if ((cio.read() < 0) || Request.isComplete(cio.getReadBuf())) { 90 rbb = cio.getReadBuf(); 91 return (requestReceived = true); 92 } 93 return false; 94 } 95 96 private boolean parse() throws IOException { 99 try { 100 request = Request.parse(rbb); 101 return true; 102 } catch (MalformedRequestException x) { 103 reply = new Reply(Reply.Code.BAD_REQUEST, 104 new StringContent(x)); 105 } 106 return false; 107 } 108 109 private void build() throws IOException { 112 Request.Action action = request.action(); 113 if ((action != Request.Action.GET) && 114 (action != Request.Action.HEAD)) { 115 reply = new Reply(Reply.Code.METHOD_NOT_ALLOWED, 116 new StringContent(request.toString())); 117 } 118 reply = new Reply(Reply.Code.OK, 119 new FileContent(request.uri()), action); 120 } 121 122 public void handle(SelectionKey sk) throws IOException { 123 try { 124 125 if (request == null) { 126 if (!receive(sk)) 127 return; 128 rbb.flip(); 129 if (parse()) 130 build(); 131 try { 132 reply.prepare(); 133 } catch (IOException x) { 134 reply.release(); 135 reply = new Reply(Reply.Code.NOT_FOUND, 136 new StringContent(x)); 137 reply.prepare(); 138 } 139 if (send()) { 140 sk.interestOps(SelectionKey.OP_WRITE); 142 } else { 143 if (cio.shutdown()) { 145 cio.close(); 146 reply.release(); 147 } 148 } 149 } else { 150 if (!send()) { if (cio.shutdown()) { 152 cio.close(); 153 reply.release(); 154 } 155 } 156 } 157 } catch (IOException x) { 158 String m = x.getMessage(); 159 if (!m.equals("Broken pipe") && 160 !m.equals("Connection reset by peer")) { 161 System.err.println("RequestHandler: " + x.toString()); 162 } 163 164 try { 165 171 cio.shutdown(); 172 } catch (IOException e) { 173 } 175 176 cio.close(); 177 if (reply != null) { 178 reply.release(); 179 } 180 } 181 182 } 183 184 private boolean send() throws IOException { 185 try { 186 return reply.send(cio); 187 } catch (IOException x) { 188 if (x.getMessage().startsWith("Resource temporarily")) { 189 System.err.println("## RTA"); 190 return true; 191 } 192 throw x; 193 } 194 } 195 } 196 | Popular Tags |