View Javadoc

1   /*
2    * $Header: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpParser.java,v 1.7.2.1 2004/02/22 18:21:13 olegk Exp $
3    * $Revision: 1.7.2.1 $
4    * $Date: 2004/02/22 18:21:13 $
5    *
6    * ====================================================================
7    *
8    *  Copyright 1999-2004 The Apache Software Foundation
9    *
10   *  Licensed under the Apache License, Version 2.0 (the "License");
11   *  you may not use this file except in compliance with the License.
12   *  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import java.io.IOException;
35  import java.io.InputStream;
36  import java.io.ByteArrayOutputStream;
37  import java.util.ArrayList;
38  
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  
42  /***
43   * A utility class for parsing http header values.
44   * 
45   * @author Michael Becke
46   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
47   * 
48   * @since 2.0beta1
49   */
50  public class HttpParser {
51  
52      /*** Log object for this class. */
53      private static final Log LOG = LogFactory.getLog(HttpParser.class);
54      
55      /***
56       * Constructor for HttpParser.
57       */
58      private HttpParser() { }
59  
60      /***
61       * Return byte array from an (unchunked) input stream.
62       * Stop reading when <tt>"\n"</tt> terminator encountered 
63       * If the stream ends before the line terminator is found,
64       * the last part of the string will still be returned. 
65       * If no input data available, <code>null</code> is returned
66       *
67       * @param inputStream the stream to read from
68       *
69       * @throws IOException if an I/O problem occurs
70       * @return a byte array from the stream
71       */
72      public static byte[] readRawLine(InputStream inputStream) throws IOException {
73          LOG.trace("enter HttpParser.readRawLine()");
74  
75          ByteArrayOutputStream buf = new ByteArrayOutputStream();
76          int ch;
77          while ((ch = inputStream.read()) >= 0) {
78              buf.write(ch);
79              if (ch == '\n') {
80                  break;
81              }
82          }
83          if (buf.size() == 0) {
84              return null;
85          }
86          return buf.toByteArray();
87      }
88  
89      /***
90       * Read up to <tt>"\n"</tt> from an (unchunked) input stream.
91       * If the stream ends before the line terminator is found,
92       * the last part of the string will still be returned.
93       * If no input data available, <code>null</code> is returned
94       *
95       * @param inputStream the stream to read from
96       *
97       * @throws IOException if an I/O problem occurs
98       * @return a line from the stream
99       */
100 
101     public static String readLine(InputStream inputStream) throws IOException {
102         LOG.trace("enter HttpParser.readLine()");
103         byte[] rawdata = readRawLine(inputStream);
104         if (rawdata == null) {
105             return null;
106         }
107         int len = rawdata.length;
108         int offset = 0;
109         if (len > 0) {
110             if (rawdata[len - 1] == '\n') {
111                 offset++;
112                 if (len > 1) {
113                     if (rawdata[len - 2] == '\r') {
114                         offset++;
115                     }
116                 }
117             }
118         }
119         return HttpConstants.getString(rawdata, 0, len - offset);
120     }
121 
122     /***
123      * Parses headers from the given stream.  Headers with the same name are not
124      * combined.
125      * 
126      * @param is the stream to read headers from
127      * 
128      * @return an array of headers in the order in which they were parsed
129      * 
130      * @throws IOException if an IO error occurs while reading from the stream
131      * @throws HttpException if there is an error parsing a header value
132      */
133     public static Header[] parseHeaders(InputStream is) throws IOException, HttpException {
134         LOG.trace("enter HeaderParser.parseHeaders(HttpConnection, HeaderGroup)");
135 
136         ArrayList headers = new ArrayList();
137         String name = null;
138         StringBuffer value = null;
139         for (; ;) {
140             String line = HttpParser.readLine(is);
141             if ((line == null) || (line.length() < 1)) {
142                 break;
143             }
144 
145             // Parse the header name and value
146             // Check for folded headers first
147             // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2
148             // discussion on folded headers
149             if ((line.charAt(0) == ' ') || (line.charAt(0) == '\t')) {
150                 // we have continuation folded header
151                 // so append value
152                 if (value != null) {
153                     value.append(' ');
154                     value.append(line.trim());
155                 }
156             } else {
157                 // make sure we save the previous name,value pair if present
158                 if (name != null) {
159                     headers.add(new Header(name, value.toString()));
160                 }
161 
162                 // Otherwise we should have normal HTTP header line
163                 // Parse the header name and value
164                 int colon = line.indexOf(":");
165                 if (colon < 0) {
166                     throw new HttpException("Unable to parse header: " + line);
167                 }
168                 name = line.substring(0, colon).trim();
169                 value = new StringBuffer(line.substring(colon + 1).trim());
170             }
171 
172         }
173 
174         // make sure we save the last name,value pair if present
175         if (name != null) {
176             headers.add(new Header(name, value.toString()));
177         }
178         
179         return (Header[]) headers.toArray(new Header[headers.size()]);    
180     }
181     
182 }