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 java.io.Serializable;
31  import java.util.ArrayList;
32  import java.util.Collections;
33  import java.util.List;
34  import java.util.Locale;
35  
36  import org.apache.http.Header;
37  import org.apache.http.HeaderIterator;
38  import org.apache.http.annotation.NotThreadSafe;
39  import org.apache.http.util.CharArrayBuffer;
40  
41  /**
42   * A class for combining a set of headers.
43   * This class allows for multiple headers with the same name and
44   * keeps track of the order in which headers were added.
45   *
46   *
47   * @since 4.0
48   */
49  @NotThreadSafe
50  public class HeaderGroup implements Cloneable, Serializable {
51  
52      private static final long serialVersionUID = 2608834160639271617L;
53  
54      private final Header[] EMPTY = new Header[] {};
55  
56      /** The list of headers for this group, in the order in which they were added */
57      private final List<Header> headers;
58  
59      /**
60       * Constructor for HeaderGroup.
61       */
62      public HeaderGroup() {
63          this.headers = new ArrayList<Header>(16);
64      }
65  
66      /**
67       * Removes any contained headers.
68       */
69      public void clear() {
70          headers.clear();
71      }
72  
73      /**
74       * Adds the given header to the group.  The order in which this header was
75       * added is preserved.
76       *
77       * @param header the header to add
78       */
79      public void addHeader(final Header header) {
80          if (header == null) {
81              return;
82          }
83          headers.add(header);
84      }
85  
86      /**
87       * Removes the given header.
88       *
89       * @param header the header to remove
90       */
91      public void removeHeader(final Header header) {
92          if (header == null) {
93              return;
94          }
95          headers.remove(header);
96      }
97  
98      /**
99       * Replaces the first occurence of the header with the same name. If no header with
100      * the same name is found the given header is added to the end of the list.
101      *
102      * @param header the new header that should replace the first header with the same
103      * name if present in the list.
104      */
105     public void updateHeader(final Header header) {
106         if (header == null) {
107             return;
108         }
109         // HTTPCORE-361 : we don't use the for-each syntax, i.e.
110         //     for (Header header : headers)
111         // as that creates an Iterator that needs to be garbage-collected
112         for (int i = 0; i < this.headers.size(); i++) {
113             final Header current = this.headers.get(i);
114             if (current.getName().equalsIgnoreCase(header.getName())) {
115                 this.headers.set(i, header);
116                 return;
117             }
118         }
119         this.headers.add(header);
120     }
121 
122     /**
123      * Sets all of the headers contained within this group overriding any
124      * existing headers. The headers are added in the order in which they appear
125      * in the array.
126      *
127      * @param headers the headers to set
128      */
129     public void setHeaders(final Header[] headers) {
130         clear();
131         if (headers == null) {
132             return;
133         }
134         Collections.addAll(this.headers, headers);
135     }
136 
137     /**
138      * Gets a header representing all of the header values with the given name.
139      * If more that one header with the given name exists the values will be
140      * combined with a "," as per RFC 2616.
141      *
142      * <p>Header name comparison is case insensitive.
143      *
144      * @param name the name of the header(s) to get
145      * @return a header with a condensed value or {@code null} if no
146      * headers by the given name are present
147      */
148     public Header getCondensedHeader(final String name) {
149         final Header[] hdrs = getHeaders(name);
150 
151         if (hdrs.length == 0) {
152             return null;
153         } else if (hdrs.length == 1) {
154             return hdrs[0];
155         } else {
156             final CharArrayBuffer valueBuffer = new CharArrayBuffer(128);
157             valueBuffer.append(hdrs[0].getValue());
158             for (int i = 1; i < hdrs.length; i++) {
159                 valueBuffer.append(", ");
160                 valueBuffer.append(hdrs[i].getValue());
161             }
162 
163             return new BasicHeader(name.toLowerCase(Locale.ROOT), valueBuffer.toString());
164         }
165     }
166 
167     /**
168      * Gets all of the headers with the given name.  The returned array
169      * maintains the relative order in which the headers were added.
170      *
171      * <p>Header name comparison is case insensitive.
172      *
173      * @param name the name of the header(s) to get
174      *
175      * @return an array of length &ge; 0
176      */
177     public Header[] getHeaders(final String name) {
178         List<Header> headersFound = null;
179         // HTTPCORE-361 : we don't use the for-each syntax, i.e.
180         //     for (Header header : headers)
181         // as that creates an Iterator that needs to be garbage-collected
182         for (int i = 0; i < this.headers.size(); i++) {
183             final Header header = this.headers.get(i);
184             if (header.getName().equalsIgnoreCase(name)) {
185                 if (headersFound == null) {
186                     headersFound = new ArrayList<Header>();
187                 }
188                 headersFound.add(header);
189             }
190         }
191         return headersFound != null ? headersFound.toArray(new Header[headersFound.size()]) : EMPTY;
192     }
193 
194     /**
195      * Gets the first header with the given name.
196      *
197      * <p>Header name comparison is case insensitive.
198      *
199      * @param name the name of the header to get
200      * @return the first header or {@code null}
201      */
202     public Header getFirstHeader(final String name) {
203         // HTTPCORE-361 : we don't use the for-each syntax, i.e.
204         //     for (Header header : headers)
205         // as that creates an Iterator that needs to be garbage-collected
206         for (int i = 0; i < this.headers.size(); i++) {
207             final Header header = this.headers.get(i);
208             if (header.getName().equalsIgnoreCase(name)) {
209                 return header;
210             }
211         }
212         return null;
213     }
214 
215     /**
216      * Gets the last header with the given name.
217      *
218      * <p>Header name comparison is case insensitive.
219      *
220      * @param name the name of the header to get
221      * @return the last header or {@code null}
222      */
223     public Header getLastHeader(final String name) {
224         // start at the end of the list and work backwards
225         for (int i = headers.size() - 1; i >= 0; i--) {
226             final Header header = headers.get(i);
227             if (header.getName().equalsIgnoreCase(name)) {
228                 return header;
229             }
230         }
231 
232         return null;
233     }
234 
235     /**
236      * Gets all of the headers contained within this group.
237      *
238      * @return an array of length &ge; 0
239      */
240     public Header[] getAllHeaders() {
241         return headers.toArray(new Header[headers.size()]);
242     }
243 
244     /**
245      * Tests if headers with the given name are contained within this group.
246      *
247      * <p>Header name comparison is case insensitive.
248      *
249      * @param name the header name to test for
250      * @return {@code true} if at least one header with the name is
251      * contained, {@code false} otherwise
252      */
253     public boolean containsHeader(final String name) {
254         // HTTPCORE-361 : we don't use the for-each syntax, i.e.
255         //     for (Header header : headers)
256         // as that creates an Iterator that needs to be garbage-collected
257         for (int i = 0; i < this.headers.size(); i++) {
258             final Header header = this.headers.get(i);
259             if (header.getName().equalsIgnoreCase(name)) {
260                 return true;
261             }
262         }
263 
264         return false;
265     }
266 
267     /**
268      * Returns an iterator over this group of headers.
269      *
270      * @return iterator over this group of headers.
271      *
272      * @since 4.0
273      */
274     public HeaderIterator iterator() {
275         return new BasicListHeaderIterator(this.headers, null);
276     }
277 
278     /**
279      * Returns an iterator over the headers with a given name in this group.
280      *
281      * @param name      the name of the headers over which to iterate, or
282      *                  {@code null} for all headers
283      *
284      * @return iterator over some headers in this group.
285      *
286      * @since 4.0
287      */
288     public HeaderIterator iterator(final String name) {
289         return new BasicListHeaderIterator(this.headers, name);
290     }
291 
292     /**
293      * Returns a copy of this object
294      *
295      * @return copy of this object
296      *
297      * @since 4.0
298      */
299     public HeaderGroup copy() {
300         final HeaderGroup clone = new HeaderGroup();
301         clone.headers.addAll(this.headers);
302         return clone;
303     }
304 
305     @Override
306     public Object clone() throws CloneNotSupportedException {
307         return super.clone();
308     }
309 
310     @Override
311     public String toString() {
312         return this.headers.toString();
313     }
314 
315 }