1 17 18 package tutorial; 19 20 import java.net.URI ; 21 import java.net.URISyntaxException ; 22 import java.nio.ByteBuffer ; 23 import java.nio.CharBuffer ; 24 import java.nio.charset.Charset ; 25 import java.util.regex.Matcher ; 26 import java.util.regex.Pattern ; 27 28 35 public class Request { 36 37 static class Action { 38 private String m_name; 39 static final Action GET = new Action("GET"); 40 static final Action POST = new Action("POST"); 41 static final Action PUT = new Action("PUT"); 42 static final Action HEAD = new Action("HEAD"); 43 44 private Action(String name) { 45 m_name = name; 46 } 47 48 public String toString() { 49 return m_name; 50 } 51 52 static Action parse(String s) throws IllegalArgumentException { 53 if (s.equals("GET")) { 54 return GET; 55 } 56 if (s.equals("POST")) { 57 return POST; 58 } 59 if (s.equals("PUT")) { 60 return PUT; 61 } 62 if (s.equals("HEAD")) { 63 return HEAD; 64 } 65 throw new IllegalArgumentException (s); 66 } 67 } 68 69 private Action m_action; 70 private String m_version; 71 private URI m_uri; 72 73 private Request(Action action, String version, URI uri) { 74 setAction(action); 75 setVersion(version); 76 setUri(uri); 77 } 78 79 private static Charset ascii = Charset.forName("US-ASCII"); 80 81 private static Pattern requestPattern = Pattern.compile( 82 "\\A([A-Z]+) +([^ ]+) +HTTP/([0-9\\.]+)$" 83 + ".*^Host: ([^ ]+)$.*\r\n\r\n", Pattern.MULTILINE | Pattern.DOTALL); 84 85 public static Request parse(ByteBuffer bb) throws MalformedRequestException { 86 CharBuffer cb = ascii.decode(bb); 87 88 Matcher m = requestPattern.matcher(cb); 89 if (!m.matches()) { 90 throw new MalformedRequestException(); 91 } 92 93 Action a; 94 try { 95 a = Action.parse(m.group(1)); 96 } 97 catch (IllegalArgumentException e) { 98 throw new MalformedRequestException(e); 99 } 100 101 URI u; 102 try { 103 u = new URI ("http://" + m.group(4) + m.group(2)); 104 } 105 catch (URISyntaxException e) { 106 throw new MalformedRequestException(e); 107 } 108 109 return new Request(a, m.group(3), u); 110 } 111 112 public Action getAction() { 113 return m_action; 114 } 115 116 public String getVersion() { 117 return m_version; 118 } 119 120 public URI getUri() { 121 return m_uri; 122 } 123 124 public boolean isGet() { 125 if (m_action.toString().equals("GET")) { 126 return true; 127 } 128 else { 129 return false; 130 } 131 } 132 133 private void setAction(Action action) { 134 m_action = action; 135 } 136 137 private void setVersion(String version) { 138 m_version = version; 139 } 140 141 private void setUri(URI uri) { 142 m_uri = uri; 143 } 144 } 145 | Popular Tags |