1 36 37 import java.io.*; 38 import java.nio.*; 39 40 48 class RequestServicer implements Runnable { 49 50 private ChannelIO cio; 51 52 private static int created = 0; 53 54 RequestServicer(ChannelIO cio) { 55 this.cio = cio; 56 57 synchronized (RequestServicer.class) { 59 created++; 60 if ((created % 50) == 0) { 61 System.out.println("."); 62 created = 0; 63 } else { 64 System.out.print("."); 65 } 66 } 67 } 68 69 private void service() throws IOException { 70 Reply rp = null; 71 try { 72 ByteBuffer rbb = receive(); Request rq = null; 74 try { rq = Request.parse(rbb); 76 } catch (MalformedRequestException x) { 77 rp = new Reply(Reply.Code.BAD_REQUEST, 78 new StringContent(x)); 79 } 80 if (rp == null) rp = build(rq); do {} while (rp.send(cio)); do {} while (!cio.shutdown()); 83 cio.close(); 84 rp.release(); 85 } catch (IOException x) { 86 String m = x.getMessage(); 87 if (!m.equals("Broken pipe") && 88 !m.equals("Connection reset by peer")) { 89 System.err.println("RequestHandler: " + x.toString()); 90 } 91 92 try { 93 99 cio.shutdown(); 100 } catch (IOException e) { 101 } 103 104 cio.close(); 105 if (rp != null) { 106 rp.release(); 107 } 108 } 109 } 110 111 public void run() { 112 try { 113 service(); 114 } catch (IOException x) { 115 x.printStackTrace(); 116 } 117 } 118 119 ByteBuffer receive() throws IOException { 120 121 do {} while (!cio.doHandshake()); 122 123 for (;;) { 124 int read = cio.read(); 125 ByteBuffer bb = cio.getReadBuf(); 126 if ((read < 0) || (Request.isComplete(bb))) { 127 bb.flip(); 128 return bb; 129 } 130 } 131 } 132 133 Reply build(Request rq) throws IOException { 134 135 Reply rp = null; 136 Request.Action action = rq.action(); 137 if ((action != Request.Action.GET) && 138 (action != Request.Action.HEAD)) 139 rp = new Reply(Reply.Code.METHOD_NOT_ALLOWED, 140 new StringContent(rq.toString())); 141 else 142 rp = new Reply(Reply.Code.OK, 143 new FileContent(rq.uri()), action); 144 try { 145 rp.prepare(); 146 } catch (IOException x) { 147 rp.release(); 148 rp = new Reply(Reply.Code.NOT_FOUND, 149 new StringContent(x)); 150 rp.prepare(); 151 } 152 return rp; 153 } 154 } 155 | Popular Tags |