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.HeaderElement;
31  import org.apache.http.NameValuePair;
32  import org.apache.http.annotation.Immutable;
33  import org.apache.http.util.Args;
34  import org.apache.http.util.CharArrayBuffer;
35  
36  /**
37   * Basic implementation for formatting header value elements.
38   * Instances of this class are stateless and thread-safe.
39   * Derived classes are expected to maintain these properties.
40   *
41   * @since 4.0
42   */
43  @Immutable
44  public class BasicHeaderValueFormatter implements HeaderValueFormatter {
45  
46      /**
47       * A default instance of this class, for use as default or fallback.
48       * Note that {@link BasicHeaderValueFormatter} is not a singleton, there
49       * can be many instances of the class itself and of derived classes.
50       * The instance here provides non-customized, default behavior.
51       *
52       * @deprecated (4.3) use {@link #INSTANCE}
53       */
54      @Deprecated
55      public final static
56          BasicHeaderValueFormatter DEFAULT = new BasicHeaderValueFormatter();
57  
58      public final static BasicHeaderValueFormatter INSTANCE = new BasicHeaderValueFormatter();
59  
60      /**
61       * Special characters that can be used as separators in HTTP parameters.
62       * These special characters MUST be in a quoted string to be used within
63       * a parameter value .
64       */
65      public final static String SEPARATORS = " ;,:@()<>\\\"/[]?={}\t";
66  
67      /**
68       * Unsafe special characters that must be escaped using the backslash
69       * character
70       */
71      public final static String UNSAFE_CHARS = "\"\\";
72  
73      public BasicHeaderValueFormatter() {
74          super();
75      }
76  
77      /**
78       * Formats an array of header elements.
79       *
80       * @param elems     the header elements to format
81       * @param quote     <code>true</code> to always format with quoted values,
82       *                  <code>false</code> to use quotes only when necessary
83       * @param formatter         the formatter to use, or <code>null</code>
84       *                          for the {@link #INSTANCE default}
85       *
86       * @return  the formatted header elements
87       */
88      public static
89          String formatElements(final HeaderElement[] elems,
90                                final boolean quote,
91                                final HeaderValueFormatter formatter) {
92          return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE)
93                  .formatElements(null, elems, quote).toString();
94      }
95  
96  
97      // non-javadoc, see interface HeaderValueFormatter
98      public CharArrayBuffer formatElements(final CharArrayBuffer charBuffer,
99                                            final HeaderElement[] elems,
100                                           final boolean quote) {
101         Args.notNull(elems, "Header element array");
102         final int len = estimateElementsLen(elems);
103         CharArrayBuffer buffer = charBuffer;
104         if (buffer == null) {
105             buffer = new CharArrayBuffer(len);
106         } else {
107             buffer.ensureCapacity(len);
108         }
109 
110         for (int i=0; i<elems.length; i++) {
111             if (i > 0) {
112                 buffer.append(", ");
113             }
114             formatHeaderElement(buffer, elems[i], quote);
115         }
116 
117         return buffer;
118     }
119 
120 
121     /**
122      * Estimates the length of formatted header elements.
123      *
124      * @param elems     the header elements to format, or <code>null</code>
125      *
126      * @return  a length estimate, in number of characters
127      */
128     protected int estimateElementsLen(final HeaderElement[] elems) {
129         if ((elems == null) || (elems.length < 1)) {
130             return 0;
131         }
132 
133         int result = (elems.length-1) * 2; // elements separated by ", "
134         for (final HeaderElement elem : elems) {
135             result += estimateHeaderElementLen(elem);
136         }
137 
138         return result;
139     }
140 
141 
142 
143     /**
144      * Formats a header element.
145      *
146      * @param elem      the header element to format
147      * @param quote     <code>true</code> to always format with quoted values,
148      *                  <code>false</code> to use quotes only when necessary
149      * @param formatter         the formatter to use, or <code>null</code>
150      *                          for the {@link #INSTANCE default}
151      *
152      * @return  the formatted header element
153      */
154     public static
155         String formatHeaderElement(final HeaderElement elem,
156                                    final boolean quote,
157                                    final HeaderValueFormatter formatter) {
158         return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE)
159                 .formatHeaderElement(null, elem, quote).toString();
160     }
161 
162 
163     // non-javadoc, see interface HeaderValueFormatter
164     public CharArrayBuffer formatHeaderElement(final CharArrayBuffer charBuffer,
165                                                final HeaderElement elem,
166                                                final boolean quote) {
167         Args.notNull(elem, "Header element");
168         final int len = estimateHeaderElementLen(elem);
169         CharArrayBuffer buffer = charBuffer;
170         if (buffer == null) {
171             buffer = new CharArrayBuffer(len);
172         } else {
173             buffer.ensureCapacity(len);
174         }
175 
176         buffer.append(elem.getName());
177         final String value = elem.getValue();
178         if (value != null) {
179             buffer.append('=');
180             doFormatValue(buffer, value, quote);
181         }
182 
183         final int parcnt = elem.getParameterCount();
184         if (parcnt > 0) {
185             for (int i=0; i<parcnt; i++) {
186                 buffer.append("; ");
187                 formatNameValuePair(buffer, elem.getParameter(i), quote);
188             }
189         }
190 
191         return buffer;
192     }
193 
194 
195     /**
196      * Estimates the length of a formatted header element.
197      *
198      * @param elem      the header element to format, or <code>null</code>
199      *
200      * @return  a length estimate, in number of characters
201      */
202     protected int estimateHeaderElementLen(final HeaderElement elem) {
203         if (elem == null) {
204             return 0;
205         }
206 
207         int result = elem.getName().length(); // name
208         final String value = elem.getValue();
209         if (value != null) {
210             // assume quotes, but no escaped characters
211             result += 3 + value.length(); // ="value"
212         }
213 
214         final int parcnt = elem.getParameterCount();
215         if (parcnt > 0) {
216             for (int i=0; i<parcnt; i++) {
217                 result += 2 +                   // ; <param>
218                     estimateNameValuePairLen(elem.getParameter(i));
219             }
220         }
221 
222         return result;
223     }
224 
225 
226 
227 
228     /**
229      * Formats a set of parameters.
230      *
231      * @param nvps      the parameters to format
232      * @param quote     <code>true</code> to always format with quoted values,
233      *                  <code>false</code> to use quotes only when necessary
234      * @param formatter         the formatter to use, or <code>null</code>
235      *                          for the {@link #INSTANCE default}
236      *
237      * @return  the formatted parameters
238      */
239     public static
240         String formatParameters(final NameValuePair[] nvps,
241                                 final boolean quote,
242                                 final HeaderValueFormatter formatter) {
243         return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE)
244                 .formatParameters(null, nvps, quote).toString();
245     }
246 
247 
248     // non-javadoc, see interface HeaderValueFormatter
249     public CharArrayBuffer formatParameters(final CharArrayBuffer charBuffer,
250                                             final NameValuePair[] nvps,
251                                             final boolean quote) {
252         Args.notNull(nvps, "Header parameter array");
253         final int len = estimateParametersLen(nvps);
254         CharArrayBuffer buffer = charBuffer;
255         if (buffer == null) {
256             buffer = new CharArrayBuffer(len);
257         } else {
258             buffer.ensureCapacity(len);
259         }
260 
261         for (int i = 0; i < nvps.length; i++) {
262             if (i > 0) {
263                 buffer.append("; ");
264             }
265             formatNameValuePair(buffer, nvps[i], quote);
266         }
267 
268         return buffer;
269     }
270 
271 
272     /**
273      * Estimates the length of formatted parameters.
274      *
275      * @param nvps      the parameters to format, or <code>null</code>
276      *
277      * @return  a length estimate, in number of characters
278      */
279     protected int estimateParametersLen(final NameValuePair[] nvps) {
280         if ((nvps == null) || (nvps.length < 1)) {
281             return 0;
282         }
283 
284         int result = (nvps.length-1) * 2; // "; " between the parameters
285         for (final NameValuePair nvp : nvps) {
286             result += estimateNameValuePairLen(nvp);
287         }
288 
289         return result;
290     }
291 
292 
293     /**
294      * Formats a name-value pair.
295      *
296      * @param nvp       the name-value pair to format
297      * @param quote     <code>true</code> to always format with a quoted value,
298      *                  <code>false</code> to use quotes only when necessary
299      * @param formatter         the formatter to use, or <code>null</code>
300      *                          for the {@link #INSTANCE default}
301      *
302      * @return  the formatted name-value pair
303      */
304     public static
305         String formatNameValuePair(final NameValuePair nvp,
306                                    final boolean quote,
307                                    final HeaderValueFormatter formatter) {
308         return (formatter != null ? formatter : BasicHeaderValueFormatter.INSTANCE)
309                 .formatNameValuePair(null, nvp, quote).toString();
310     }
311 
312 
313     // non-javadoc, see interface HeaderValueFormatter
314     public CharArrayBuffer formatNameValuePair(final CharArrayBuffer charBuffer,
315                                                final NameValuePair nvp,
316                                                final boolean quote) {
317         Args.notNull(nvp, "Name / value pair");
318         final int len = estimateNameValuePairLen(nvp);
319         CharArrayBuffer buffer = charBuffer;
320         if (buffer == null) {
321             buffer = new CharArrayBuffer(len);
322         } else {
323             buffer.ensureCapacity(len);
324         }
325 
326         buffer.append(nvp.getName());
327         final String value = nvp.getValue();
328         if (value != null) {
329             buffer.append('=');
330             doFormatValue(buffer, value, quote);
331         }
332 
333         return buffer;
334     }
335 
336 
337     /**
338      * Estimates the length of a formatted name-value pair.
339      *
340      * @param nvp       the name-value pair to format, or <code>null</code>
341      *
342      * @return  a length estimate, in number of characters
343      */
344     protected int estimateNameValuePairLen(final NameValuePair nvp) {
345         if (nvp == null) {
346             return 0;
347         }
348 
349         int result = nvp.getName().length(); // name
350         final String value = nvp.getValue();
351         if (value != null) {
352             // assume quotes, but no escaped characters
353             result += 3 + value.length(); // ="value"
354         }
355         return result;
356     }
357 
358 
359     /**
360      * Actually formats the value of a name-value pair.
361      * This does not include a leading = character.
362      * Called from {@link #formatNameValuePair formatNameValuePair}.
363      *
364      * @param buffer    the buffer to append to, never <code>null</code>
365      * @param value     the value to append, never <code>null</code>
366      * @param quote     <code>true</code> to always format with quotes,
367      *                  <code>false</code> to use quotes only when necessary
368      */
369     protected void doFormatValue(final CharArrayBuffer buffer,
370                                  final String value,
371                                  final boolean quote) {
372 
373         boolean quoteFlag = quote;
374         if (!quoteFlag) {
375             for (int i = 0; (i < value.length()) && !quoteFlag; i++) {
376                 quoteFlag = isSeparator(value.charAt(i));
377             }
378         }
379 
380         if (quoteFlag) {
381             buffer.append('"');
382         }
383         for (int i = 0; i < value.length(); i++) {
384             final char ch = value.charAt(i);
385             if (isUnsafe(ch)) {
386                 buffer.append('\\');
387             }
388             buffer.append(ch);
389         }
390         if (quoteFlag) {
391             buffer.append('"');
392         }
393     }
394 
395 
396     /**
397      * Checks whether a character is a {@link #SEPARATORS separator}.
398      *
399      * @param ch        the character to check
400      *
401      * @return  <code>true</code> if the character is a separator,
402      *          <code>false</code> otherwise
403      */
404     protected boolean isSeparator(final char ch) {
405         return SEPARATORS.indexOf(ch) >= 0;
406     }
407 
408 
409     /**
410      * Checks whether a character is {@link #UNSAFE_CHARS unsafe}.
411      *
412      * @param ch        the character to check
413      *
414      * @return  <code>true</code> if the character is unsafe,
415      *          <code>false</code> otherwise
416      */
417     protected boolean isUnsafe(final char ch) {
418         return UNSAFE_CHARS.indexOf(ch) >= 0;
419     }
420 
421 
422 } // class BasicHeaderValueFormatter