2 // ========================================================================
3 // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.http;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.Enumeration;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.List;
30 import java.util.NoSuchElementException;
32 import java.util.StringTokenizer;
33 import java.util.regex.Pattern;
35 import org.eclipse.jetty.util.ArrayTernaryTrie;
36 import org.eclipse.jetty.util.LazyList;
37 import org.eclipse.jetty.util.QuotedStringTokenizer;
38 import org.eclipse.jetty.util.StringUtil;
39 import org.eclipse.jetty.util.Trie;
40 import org.eclipse.jetty.util.log.Log;
41 import org.eclipse.jetty.util.log.Logger;
45 * HTTP Fields. A collection of HTTP header and or Trailer fields.
47 * <p>This class is not synchronized as it is expected that modifications will only be performed by a
50 * <p>The cookie handling provided by this class is guided by the Servlet specification and RFC6265.
53 public class HttpFields implements Iterable<HttpField>
55 private static final Logger LOG = Log.getLogger(HttpFields.class);
56 private final static Pattern __splitter = Pattern.compile("\\s*,\\s*");
57 public final static String __separators = ", \t";
59 private final ArrayList<HttpField> _fields = new ArrayList<>(20);
69 * Get Collection of header names.
71 public Collection<String> getFieldNamesCollection()
73 final Set<String> list = new HashSet<>(_fields.size());
74 for (HttpField f : _fields)
77 list.add(f.getName());
83 * Get enumeration of header _names. Returns an enumeration of strings representing the header
84 * _names for this request.
86 public Enumeration<String> getFieldNames()
88 return Collections.enumeration(getFieldNamesCollection());
93 return _fields.size();
97 * Get a Field by index.
98 * @return A Field value or null if the Field value has not been set
101 public HttpField getField(int i)
103 return _fields.get(i);
107 public Iterator<HttpField> iterator()
109 return _fields.iterator();
112 public HttpField getField(HttpHeader header)
114 for (int i=0;i<_fields.size();i++)
116 HttpField f=_fields.get(i);
117 if (f.getHeader()==header)
123 public HttpField getField(String name)
125 for (int i=0;i<_fields.size();i++)
127 HttpField f=_fields.get(i);
128 if (f.getName().equalsIgnoreCase(name))
134 public boolean contains(HttpHeader header, String value)
136 for (int i=0;i<_fields.size();i++)
138 HttpField f=_fields.get(i);
139 if (f.getHeader()==header && contains(f,value))
145 public boolean contains(String name, String value)
147 for (int i=0;i<_fields.size();i++)
149 HttpField f=_fields.get(i);
150 if (f.getName().equalsIgnoreCase(name) && contains(f,value))
156 private boolean contains(HttpField field,String value)
158 String v = field.getValue();
162 if (value.equalsIgnoreCase(v))
165 String[] split = __splitter.split(v);
166 for (int i = 0; split!=null && i < split.length; i++)
168 if (value.equals(split[i]))
175 public boolean containsKey(String name)
177 for (int i=0;i<_fields.size();i++)
179 HttpField f=_fields.get(i);
180 if (f.getName().equalsIgnoreCase(name))
186 public String getStringField(HttpHeader header)
188 return getStringField(header.asString());
191 public String get(HttpHeader header)
193 return getStringField(header.asString());
196 public String get(String header)
198 return getStringField(header);
202 * @return the value of a field, or null if not found. For multiple fields of the same name,
203 * only the first is returned.
204 * @param name the case-insensitive field name
206 public String getStringField(String name)
208 HttpField field = getField(name);
209 return field==null?null:field.getValue();
215 * @return List the values
216 * @param name the case-insensitive field name
218 public List<String> getValuesList(String name)
220 final List<String> list = new ArrayList<>();
221 for (HttpField f : _fields)
222 if (f.getName().equalsIgnoreCase(name))
223 list.add(f.getValue());
230 * @return Enumeration of the values
231 * @param name the case-insensitive field name
233 public Enumeration<String> getValues(final String name)
235 for (int i=0;i<_fields.size();i++)
237 final HttpField f = _fields.get(i);
239 if (f.getName().equalsIgnoreCase(name) && f.getValue()!=null)
242 return new Enumeration<String>()
248 public boolean hasMoreElements()
252 while (i<_fields.size())
254 field=_fields.get(i++);
255 if (field.getName().equalsIgnoreCase(name) && field.getValue()!=null)
265 public String nextElement() throws NoSuchElementException
267 if (hasMoreElements())
269 String value=field.getValue();
273 throw new NoSuchElementException();
280 List<String> empty=Collections.emptyList();
281 return Collections.enumeration(empty);
285 * Get multi field values with separator. The multiple values can be represented as separate
286 * headers of the same name, or by a single header using the separator(s), or a combination of
287 * both. Separators may be quoted.
289 * @param name the case-insensitive field name
290 * @param separators String of separators.
291 * @return Enumeration of the values, or null if no such header.
293 public Enumeration<String> getValues(String name, final String separators)
295 final Enumeration<String> e = getValues(name);
298 return new Enumeration<String>()
300 QuotedStringTokenizer tok = null;
303 public boolean hasMoreElements()
305 if (tok != null && tok.hasMoreElements()) return true;
306 while (e.hasMoreElements())
308 String value = e.nextElement();
311 tok = new QuotedStringTokenizer(value, separators, false, false);
312 if (tok.hasMoreElements()) return true;
320 public String nextElement() throws NoSuchElementException
322 if (!hasMoreElements()) throw new NoSuchElementException();
323 String next = (String) tok.nextElement();
324 if (next != null) next = next.trim();
330 public void put(HttpField field)
333 for (int i=_fields.size();i-->0;)
335 HttpField f=_fields.get(i);
342 _fields.set(i,field);
354 * @param name the name of the field
355 * @param value the value of the field. If null the field is cleared.
357 public void put(String name, String value)
362 put(new HttpField(name, value));
365 public void put(HttpHeader header, HttpHeaderValue value)
367 put(header,value.toString());
373 * @param header the header name of the field
374 * @param value the value of the field. If null the field is cleared.
376 public void put(HttpHeader header, String value)
381 put(new HttpField(header, value));
387 * @param name the name of the field
388 * @param list the List value of the field. If null the field is cleared.
390 public void put(String name, List<String> list)
393 for (String v : list)
399 * Add to or set a field. If the field is allowed to have multiple values, add will add multiple
400 * headers of the same name.
402 * @param name the name of the field
403 * @param value the value of the field.
404 * @exception IllegalArgumentException If the name is a single valued field and already has a
407 public void add(String name, String value) throws IllegalArgumentException
412 HttpField field = new HttpField(name, value);
416 public void add(HttpHeader header, HttpHeaderValue value) throws IllegalArgumentException
418 add(header,value.toString());
422 * Add to or set a field. If the field is allowed to have multiple values, add will add multiple
423 * headers of the same name.
425 * @param header the header
426 * @param value the value of the field.
427 * @exception IllegalArgumentException
429 public void add(HttpHeader header, String value) throws IllegalArgumentException
431 if (value == null) throw new IllegalArgumentException("null value");
433 HttpField field = new HttpField(header, value);
440 * @param name the field to remove
442 public HttpField remove(HttpHeader name)
444 for (int i=_fields.size();i-->0;)
446 HttpField f=_fields.get(i);
447 if (f.getHeader()==name)
448 return _fields.remove(i);
456 * @param name the field to remove
458 public HttpField remove(String name)
460 for (int i=_fields.size();i-->0;)
462 HttpField f=_fields.get(i);
463 if (f.getName().equalsIgnoreCase(name))
464 return _fields.remove(i);
470 * Get a header as an long value. Returns the value of an integer field or -1 if not found. The
471 * case of the field name is ignored.
473 * @param name the case-insensitive field name
474 * @exception NumberFormatException If bad long found
476 public long getLongField(String name) throws NumberFormatException
478 HttpField field = getField(name);
479 return field==null?-1L:StringUtil.toLong(field.getValue());
483 * Get a header as a date value. Returns the value of a date field, or -1 if not found. The case
484 * of the field name is ignored.
486 * @param name the case-insensitive field name
488 public long getDateField(String name)
490 HttpField field = getField(name);
494 String val = valueParameters(field.getValue(), null);
498 final long date = DateParser.parseDate(val);
500 throw new IllegalArgumentException("Cannot convert date: " + val);
506 * Sets the value of an long field.
508 * @param name the field name
509 * @param value the field long value
511 public void putLongField(HttpHeader name, long value)
513 String v = Long.toString(value);
518 * Sets the value of an long field.
520 * @param name the field name
521 * @param value the field long value
523 public void putLongField(String name, long value)
525 String v = Long.toString(value);
531 * Sets the value of a date field.
533 * @param name the field name
534 * @param date the field date value
536 public void putDateField(HttpHeader name, long date)
538 String d=DateGenerator.formatDate(date);
543 * Sets the value of a date field.
545 * @param name the field name
546 * @param date the field date value
548 public void putDateField(String name, long date)
550 String d=DateGenerator.formatDate(date);
555 * Sets the value of a date field.
557 * @param name the field name
558 * @param date the field date value
560 public void addDateField(String name, long date)
562 String d=DateGenerator.formatDate(date);
572 StringBuilder buffer = new StringBuilder();
573 for (HttpField field : _fields)
577 String tmp = field.getName();
578 if (tmp != null) buffer.append(tmp);
580 tmp = field.getValue();
581 if (tmp != null) buffer.append(tmp);
582 buffer.append("\r\n");
585 buffer.append("\r\n");
586 return buffer.toString();
603 public void add(HttpField field)
611 * Add fields from another HttpFields instance. Single valued fields are replaced, while all
614 * @param fields the fields to add
616 public void add(HttpFields fields)
618 if (fields == null) return;
620 Enumeration<String> e = fields.getFieldNames();
621 while (e.hasMoreElements())
623 String name = e.nextElement();
624 Enumeration<String> values = fields.getValues(name);
625 while (values.hasMoreElements())
626 add(name, values.nextElement());
631 * Get field value parameters. Some field values can have parameters. This method separates the
632 * value from the parameters and optionally populates a map with the parameters. For example:
636 * FieldName : Value ; param1=val1 ; param2=val2
640 * @param value The Field value, possibly with parameteres.
641 * @param parameters A map to populate with the parameters, or null
644 public static String valueParameters(String value, Map<String,String> parameters)
646 if (value == null) return null;
648 int i = value.indexOf(';');
649 if (i < 0) return value;
650 if (parameters == null) return value.substring(0, i).trim();
652 StringTokenizer tok1 = new QuotedStringTokenizer(value.substring(i), ";", false, true);
653 while (tok1.hasMoreTokens())
655 String token = tok1.nextToken();
656 StringTokenizer tok2 = new QuotedStringTokenizer(token, "= ");
657 if (tok2.hasMoreTokens())
659 String paramName = tok2.nextToken();
660 String paramVal = null;
661 if (tok2.hasMoreTokens()) paramVal = tok2.nextToken();
662 parameters.put(paramName, paramVal);
666 return value.substring(0, i).trim();
669 private static final Float __one = new Float("1.0");
670 private static final Float __zero = new Float("0.0");
671 private static final Trie<Float> __qualities = new ArrayTernaryTrie<>();
674 __qualities.put("*", __one);
675 __qualities.put("1.0", __one);
676 __qualities.put("1", __one);
677 __qualities.put("0.9", new Float("0.9"));
678 __qualities.put("0.8", new Float("0.8"));
679 __qualities.put("0.7", new Float("0.7"));
680 __qualities.put("0.66", new Float("0.66"));
681 __qualities.put("0.6", new Float("0.6"));
682 __qualities.put("0.5", new Float("0.5"));
683 __qualities.put("0.4", new Float("0.4"));
684 __qualities.put("0.33", new Float("0.33"));
685 __qualities.put("0.3", new Float("0.3"));
686 __qualities.put("0.2", new Float("0.2"));
687 __qualities.put("0.1", new Float("0.1"));
688 __qualities.put("0", __zero);
689 __qualities.put("0.0", __zero);
692 public static Float getQuality(String value)
694 if (value == null) return __zero;
696 int qe = value.indexOf(";");
697 if (qe++ < 0 || qe == value.length()) return __one;
699 if (value.charAt(qe++) == 'q')
702 Float q = __qualities.get(value, qe, value.length() - qe);
707 Map<String,String> params = new HashMap<>(4);
708 valueParameters(value, params);
709 String qs = params.get("q");
712 Float q = __qualities.get(qs);
728 * List values in quality order.
730 * @param e Enumeration of values with quality parameters
731 * @return values in quality order.
733 public static List<String> qualityList(Enumeration<String> e)
735 if (e == null || !e.hasMoreElements())
736 return Collections.emptyList();
741 // Assume list will be well ordered and just add nonzero
742 while (e.hasMoreElements())
744 String v = e.nextElement();
745 Float q = getQuality(v);
749 list = LazyList.add(list, v);
750 qual = LazyList.add(qual, q);
754 List<String> vl = LazyList.getList(list, false);
758 List<Float> ql = LazyList.getList(qual, false);
760 // sort list with swaps
762 for (int i = vl.size(); i-- > 0;)
765 if (last.compareTo(q) > 0)
767 String tmp = vl.get(i);
768 vl.set(i, vl.get(i + 1));
770 ql.set(i, ql.get(i + 1));