View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.message;
29  
30  import org.apache.http.FormattedHeader;
31  import org.apache.http.Header;
32  import org.apache.http.ProtocolVersion;
33  import org.apache.http.RequestLine;
34  import org.apache.http.StatusLine;
35  import org.apache.http.annotation.Immutable;
36  import org.apache.http.util.Args;
37  import org.apache.http.util.CharArrayBuffer;
38  
39  /**
40   * Interface for formatting elements of the HEAD section of an HTTP message.
41   * This is the complement to {@link LineParser}.
42   * There are individual methods for formatting a request line, a
43   * status line, or a header line. The formatting does <i>not</i> include the
44   * trailing line break sequence CR-LF.
45   * The formatted lines are returned in memory, the formatter does not depend
46   * on any specific IO mechanism.
47   * Instances of this interface are expected to be stateless and thread-safe.
48   *
49   * @since 4.0
50   */
51  @Immutable
52  public class BasicLineFormatter implements LineFormatter {
53  
54      /**
55       * A default instance of this class, for use as default or fallback.
56       * Note that {@link BasicLineFormatter} is not a singleton, there can
57       * be many instances of the class itself and of derived classes.
58       * The instance here provides non-customized, default behavior.
59       *
60       * @deprecated (4.3) use {@link #INSTANCE}
61       */
62      @Deprecated
63      public final static BasicLineFormatter DEFAULT = new BasicLineFormatter();
64  
65      public final static BasicLineFormatter INSTANCE = new BasicLineFormatter();
66  
67      public BasicLineFormatter() {
68          super();
69      }
70  
71      /**
72       * Obtains a buffer for formatting.
73       *
74       * @param charBuffer a buffer already available, or <code>null</code>
75       *
76       * @return  the cleared argument buffer if there is one, or
77       *          a new empty buffer that can be used for formatting
78       */
79      protected CharArrayBuffer initBuffer(final CharArrayBuffer charBuffer) {
80          CharArrayBuffer buffer = charBuffer;
81          if (buffer != null) {
82              buffer.clear();
83          } else {
84              buffer = new CharArrayBuffer(64);
85          }
86          return buffer;
87      }
88  
89  
90      /**
91       * Formats a protocol version.
92       *
93       * @param version           the protocol version to format
94       * @param formatter         the formatter to use, or
95       *                          <code>null</code> for the
96       *                          {@link #INSTANCE default}
97       *
98       * @return  the formatted protocol version
99       */
100     public static
101         String formatProtocolVersion(final ProtocolVersion version,
102                                      final LineFormatter formatter) {
103         return (formatter != null ? formatter : BasicLineFormatter.INSTANCE)
104                 .appendProtocolVersion(null, version).toString();
105     }
106 
107 
108     // non-javadoc, see interface LineFormatter
109     @Override
110     public CharArrayBuffer appendProtocolVersion(final CharArrayBuffer buffer,
111                                                  final ProtocolVersion version) {
112         Args.notNull(version, "Protocol version");
113         // can't use initBuffer, that would clear the argument!
114         CharArrayBuffer result = buffer;
115         final int len = estimateProtocolVersionLen(version);
116         if (result == null) {
117             result = new CharArrayBuffer(len);
118         } else {
119             result.ensureCapacity(len);
120         }
121 
122         result.append(version.getProtocol());
123         result.append('/');
124         result.append(Integer.toString(version.getMajor()));
125         result.append('.');
126         result.append(Integer.toString(version.getMinor()));
127 
128         return result;
129     }
130 
131 
132     /**
133      * Guesses the length of a formatted protocol version.
134      * Needed to guess the length of a formatted request or status line.
135      *
136      * @param version   the protocol version to format, or <code>null</code>
137      *
138      * @return  the estimated length of the formatted protocol version,
139      *          in characters
140      */
141     protected int estimateProtocolVersionLen(final ProtocolVersion version) {
142         return version.getProtocol().length() + 4; // room for "HTTP/1.1"
143     }
144 
145 
146     /**
147      * Formats a request line.
148      *
149      * @param reqline           the request line to format
150      * @param formatter         the formatter to use, or
151      *                          <code>null</code> for the
152      *                          {@link #INSTANCE default}
153      *
154      * @return  the formatted request line
155      */
156     public static String formatRequestLine(final RequestLine reqline,
157                                            final LineFormatter formatter) {
158         return (formatter != null ? formatter : BasicLineFormatter.INSTANCE)
159                 .formatRequestLine(null, reqline).toString();
160     }
161 
162 
163     // non-javadoc, see interface LineFormatter
164     @Override
165     public CharArrayBuffer formatRequestLine(final CharArrayBuffer buffer,
166                                              final RequestLine reqline) {
167         Args.notNull(reqline, "Request line");
168         final CharArrayBuffer result = initBuffer(buffer);
169         doFormatRequestLine(result, reqline);
170 
171         return result;
172     }
173 
174 
175     /**
176      * Actually formats a request line.
177      * Called from {@link #formatRequestLine}.
178      *
179      * @param buffer    the empty buffer into which to format,
180      *                  never <code>null</code>
181      * @param reqline   the request line to format, never <code>null</code>
182      */
183     protected void doFormatRequestLine(final CharArrayBuffer buffer,
184                                        final RequestLine reqline) {
185         final String method = reqline.getMethod();
186         final String uri    = reqline.getUri();
187 
188         // room for "GET /index.html HTTP/1.1"
189         final int len = method.length() + 1 + uri.length() + 1 +
190             estimateProtocolVersionLen(reqline.getProtocolVersion());
191         buffer.ensureCapacity(len);
192 
193         buffer.append(method);
194         buffer.append(' ');
195         buffer.append(uri);
196         buffer.append(' ');
197         appendProtocolVersion(buffer, reqline.getProtocolVersion());
198     }
199 
200 
201 
202     /**
203      * Formats a status line.
204      *
205      * @param statline          the status line to format
206      * @param formatter         the formatter to use, or
207      *                          <code>null</code> for the
208      *                          {@link #INSTANCE default}
209      *
210      * @return  the formatted status line
211      */
212     public static String formatStatusLine(final StatusLine statline,
213                                           final LineFormatter formatter) {
214         return (formatter != null ? formatter : BasicLineFormatter.INSTANCE)
215                 .formatStatusLine(null, statline).toString();
216     }
217 
218 
219     // non-javadoc, see interface LineFormatter
220     @Override
221     public CharArrayBuffer formatStatusLine(final CharArrayBuffer buffer,
222                                             final StatusLine statline) {
223         Args.notNull(statline, "Status line");
224         final CharArrayBuffer result = initBuffer(buffer);
225         doFormatStatusLine(result, statline);
226 
227         return result;
228     }
229 
230 
231     /**
232      * Actually formats a status line.
233      * Called from {@link #formatStatusLine}.
234      *
235      * @param buffer    the empty buffer into which to format,
236      *                  never <code>null</code>
237      * @param statline  the status line to format, never <code>null</code>
238      */
239     protected void doFormatStatusLine(final CharArrayBuffer buffer,
240                                       final StatusLine statline) {
241 
242         int len = estimateProtocolVersionLen(statline.getProtocolVersion())
243             + 1 + 3 + 1; // room for "HTTP/1.1 200 "
244         final String reason = statline.getReasonPhrase();
245         if (reason != null) {
246             len += reason.length();
247         }
248         buffer.ensureCapacity(len);
249 
250         appendProtocolVersion(buffer, statline.getProtocolVersion());
251         buffer.append(' ');
252         buffer.append(Integer.toString(statline.getStatusCode()));
253         buffer.append(' '); // keep whitespace even if reason phrase is empty
254         if (reason != null) {
255             buffer.append(reason);
256         }
257     }
258 
259 
260     /**
261      * Formats a header.
262      *
263      * @param header            the header to format
264      * @param formatter         the formatter to use, or
265      *                          <code>null</code> for the
266      *                          {@link #INSTANCE default}
267      *
268      * @return  the formatted header
269      */
270     public static String formatHeader(final Header header,
271                                       final LineFormatter formatter) {
272         return (formatter != null ? formatter : BasicLineFormatter.INSTANCE)
273                 .formatHeader(null, header).toString();
274     }
275 
276 
277     // non-javadoc, see interface LineFormatter
278     @Override
279     public CharArrayBuffer formatHeader(final CharArrayBuffer buffer,
280                                         final Header header) {
281         Args.notNull(header, "Header");
282         final CharArrayBuffer result;
283 
284         if (header instanceof FormattedHeader) {
285             // If the header is backed by a buffer, re-use the buffer
286             result = ((FormattedHeader)header).getBuffer();
287         } else {
288             result = initBuffer(buffer);
289             doFormatHeader(result, header);
290         }
291         return result;
292 
293     } // formatHeader
294 
295 
296     /**
297      * Actually formats a header.
298      * Called from {@link #formatHeader}.
299      *
300      * @param buffer    the empty buffer into which to format,
301      *                  never <code>null</code>
302      * @param header    the header to format, never <code>null</code>
303      */
304     protected void doFormatHeader(final CharArrayBuffer buffer,
305                                   final Header header) {
306         final String name = header.getName();
307         final String value = header.getValue();
308 
309         int len = name.length() + 2;
310         if (value != null) {
311             len += value.length();
312         }
313         buffer.ensureCapacity(len);
314 
315         buffer.append(name);
316         buffer.append(": ");
317         if (value != null) {
318             buffer.append(value);
319         }
320     }
321 
322 
323 } // class BasicLineFormatter