View Javadoc
1   package net.technearts.rip;
2   
3   import java.io.BufferedReader;
4   import java.io.IOException;
5   import java.io.StringReader;
6   import java.net.MalformedURLException;
7   import java.net.URL;
8   import java.util.HashMap;
9   
10  import org.eclipse.jetty.http.HttpMethod;
11  
12  /**
13   * Requisição http (rfc 2612).
14   */
15  public class HttpRequestParser {
16    private String reqLine;
17    private final HashMap<String, String> reqHeaders;
18    private final StringBuilder msgBody;
19  
20    public HttpRequestParser() {
21      reqHeaders = new HashMap<>();
22      msgBody = new StringBuilder();
23    }
24  
25    private void appendHeaderParameter(final String header)
26        throws HttpFormatException {
27      final int idx = header.indexOf(':');
28      if (idx == -1) {
29        throw new HttpFormatException("Invalid Header Parameter: " + header);
30      }
31      reqHeaders.put(header.substring(0, idx),
32          header.substring(idx + 1, header.length()));
33    }
34  
35    private void appendMessageBody(final String bodyLine) {
36      msgBody.append(bodyLine).append("\r\n");
37    }
38  
39    /**
40     * Lista de cabeçalhos ver seções: 4.5, 5.3, 7.1 da rfc 2616
41     *
42     * @param headerName o cabeçalho
43     * @return o valor do cabeçalho ou null.
44     */
45    public String getHeaderParam(final String headerName) {
46      return reqHeaders.get(headerName);
47    }
48  
49    /**
50     * Corpo da mensagem (body). Ver diferença entre corpo da mensagem e corpo da
51     * entidade (seção 14.41)
52     *
53     * @return o corpo da mensagem
54     */
55    public String getMessageBody() {
56      return msgBody.toString();
57    }
58  
59    /**
60     * O método http.
61     *
62     * @return o método http chamado.
63     */
64    public HttpMethod getMethod() {
65      final HttpMethod method = HttpMethod
66          .fromString(getRequestLine().split(" ")[0]);
67      if (method == null) {
68        throw new IllegalArgumentException();
69      }
70      return method;
71    }
72  
73    /**
74     * Seção 5.1: a linha da requisição começar com o método, seguido da URI e
75     * versão do protocolo, terminando com CRLF.
76     *
77     * @return a linha da requisição.
78     */
79    public String getRequestLine() {
80      return reqLine;
81    }
82  
83    /**
84     * A URL.
85     *
86     * @return a URL da requisição.
87     */
88    public URL getUrl() {
89      final String protocol = "HTTP";
90      final String host = getHeaderParam("Host");
91      final int port = 80;
92      final String file = getRequestLine().split(" ")[1];
93      try {
94        return new URL(protocol, host, port, file);
95      } catch (final MalformedURLException ex) {
96        throw new IllegalArgumentException();
97      }
98    }
99  
100   /**
101    * Parse da requisição.
102    *
103    * @param reader Um objeto reader com a requisição.
104    * @throws IOException         Qualquer erro de leitura.
105    * @throws HttpFormatException Qualquer erro de formato
106    */
107   public void parseRequest(final BufferedReader reader)
108       throws IOException, HttpFormatException {
109     setRequestLine(reader.readLine());
110     String header = reader.readLine();
111     while (header != null && header.length() > 0) {
112       appendHeaderParameter(header);
113       header = reader.readLine();
114     }
115     String bodyLine = reader.readLine();
116     while (bodyLine != null) {
117       appendMessageBody(bodyLine);
118       bodyLine = reader.readLine();
119     }
120   }
121 
122   /**
123    * Parse da requisição.
124    *
125    * @param request A requisição http.
126    * @throws IOException         Qualquer erro de leitura.
127    * @throws HttpFormatException Qualquer erro de formato
128    */
129   public void parseRequest(final String request)
130       throws IOException, HttpFormatException {
131     parseRequest(new BufferedReader(new StringReader(request)));
132   }
133 
134   private void setRequestLine(final String requestLine)
135       throws HttpFormatException {
136     if (requestLine == null || requestLine.length() == 0) {
137       throw new HttpFormatException("Invalid Request-Line: " + requestLine);
138     }
139     reqLine = requestLine;
140   }
141 }