1 36 37 import java.net.*; 38 import java.nio.*; 39 import java.nio.charset.*; 40 import java.util.regex.*; 41 42 52 class Request { 53 54 57 static class Action { 58 59 private String name; 60 private Action(String name) { this.name = name; } 61 public String toString() { return name; } 62 63 static Action GET = new Action("GET"); 64 static Action PUT = new Action("PUT"); 65 static Action POST = new Action("POST"); 66 static Action HEAD = new Action("HEAD"); 67 68 static Action parse(String s) { 69 if (s.equals("GET")) 70 return GET; 71 if (s.equals("PUT")) 72 return PUT; 73 if (s.equals("POST")) 74 return POST; 75 if (s.equals("HEAD")) 76 return HEAD; 77 throw new IllegalArgumentException (s); 78 } 79 } 80 81 private Action action; 82 private String version; 83 private URI uri; 84 85 Action action() { return action; } 86 String version() { return version; } 87 URI uri() { return uri; } 88 89 private Request(Action a, String v, URI u) { 90 action = a; 91 version = v; 92 uri = u; 93 } 94 95 public String toString() { 96 return (action + " " + version + " " + uri); 97 } 98 99 static boolean isComplete(ByteBuffer bb) { 100 int p = bb.position() - 4; 101 if (p < 0) 102 return false; 103 return (((bb.get(p + 0) == '\r') && 104 (bb.get(p + 1) == '\n') && 105 (bb.get(p + 2) == '\r') && 106 (bb.get(p + 3) == '\n'))); 107 } 108 109 private static Charset ascii = Charset.forName("US-ASCII"); 110 111 132 private static Pattern requestPattern 133 = Pattern.compile("\\A([A-Z]+) +([^ ]+) +HTTP/([0-9\\.]+)$" 134 + ".*^Host: ([^ ]+)$.*\r\n\r\n\\z", 135 Pattern.MULTILINE | Pattern.DOTALL); 136 137 static Request parse(ByteBuffer bb) throws MalformedRequestException { 138 139 CharBuffer cb = ascii.decode(bb); 140 Matcher m = requestPattern.matcher(cb); 141 if (!m.matches()) 142 throw new MalformedRequestException(); 143 Action a; 144 try { 145 a = Action.parse(m.group(1)); 146 } catch (IllegalArgumentException x) { 147 throw new MalformedRequestException(); 148 } 149 URI u; 150 try { 151 u = new URI("http://" 152 + m.group(4) 153 + m.group(2)); 154 } catch (URISyntaxException x) { 155 throw new MalformedRequestException(); 156 } 157 return new Request(a, m.group(3), u); 158 } 159 } 160 | Popular Tags |