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.impl.cookie;
29  
30  import java.util.ArrayList;
31  import java.util.Collections;
32  import java.util.List;
33  
34  import org.apache.http.Header;
35  import org.apache.http.HeaderElement;
36  import org.apache.http.annotation.NotThreadSafe;
37  import org.apache.http.client.utils.DateUtils;
38  import org.apache.http.cookie.ClientCookie;
39  import org.apache.http.cookie.Cookie;
40  import org.apache.http.cookie.CookieOrigin;
41  import org.apache.http.cookie.CookiePathComparator;
42  import org.apache.http.cookie.CookieRestrictionViolationException;
43  import org.apache.http.cookie.MalformedCookieException;
44  import org.apache.http.cookie.SM;
45  import org.apache.http.message.BufferedHeader;
46  import org.apache.http.util.Args;
47  import org.apache.http.util.CharArrayBuffer;
48  
49  /**
50   * RFC 2109 compliant {@link org.apache.http.cookie.CookieSpec} implementation.
51   * This is an older version of the official HTTP state management specification
52   * superseded by RFC 2965.
53   *
54   * @see RFC2965Spec
55   *
56   * @since 4.0
57   */
58  @NotThreadSafe // superclass is @NotThreadSafe
59  public class RFC2109Spec extends CookieSpecBase {
60  
61      private final static CookiePathComparator PATH_COMPARATOR = new CookiePathComparator();
62  
63      private final static String[] DATE_PATTERNS = {
64          DateUtils.PATTERN_RFC1123,
65          DateUtils.PATTERN_RFC1036,
66          DateUtils.PATTERN_ASCTIME
67      };
68  
69      private final String[] datepatterns;
70      private final boolean oneHeader;
71  
72      /** Default constructor */
73      public RFC2109Spec(final String[] datepatterns, final boolean oneHeader) {
74          super();
75          if (datepatterns != null) {
76              this.datepatterns = datepatterns.clone();
77          } else {
78              this.datepatterns = DATE_PATTERNS;
79          }
80          this.oneHeader = oneHeader;
81          registerAttribHandler(ClientCookie.VERSION_ATTR, new RFC2109VersionHandler());
82          registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler());
83          registerAttribHandler(ClientCookie.DOMAIN_ATTR, new RFC2109DomainHandler());
84          registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler());
85          registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler());
86          registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler());
87          registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler(
88                  this.datepatterns));
89      }
90  
91      /** Default constructor */
92      public RFC2109Spec() {
93          this(null, false);
94      }
95  
96      public List<Cookie> parse(final Header header, final CookieOrigin origin)
97              throws MalformedCookieException {
98          Args.notNull(header, "Header");
99          Args.notNull(origin, "Cookie origin");
100         if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) {
101             throw new MalformedCookieException("Unrecognized cookie header '"
102                     + header.toString() + "'");
103         }
104         final HeaderElement[] elems = header.getElements();
105         return parse(elems, origin);
106     }
107 
108     @Override
109     public void validate(final Cookie cookie, final CookieOrigin origin)
110             throws MalformedCookieException {
111         Args.notNull(cookie, "Cookie");
112         final String name = cookie.getName();
113         if (name.indexOf(' ') != -1) {
114             throw new CookieRestrictionViolationException("Cookie name may not contain blanks");
115         }
116         if (name.startsWith("$")) {
117             throw new CookieRestrictionViolationException("Cookie name may not start with $");
118         }
119         super.validate(cookie, origin);
120     }
121 
122     public List<Header> formatCookies(final List<Cookie> cookies) {
123         Args.notEmpty(cookies, "List of cookies");
124         List<Cookie> cookieList;
125         if (cookies.size() > 1) {
126             // Create a mutable copy and sort the copy.
127             cookieList = new ArrayList<Cookie>(cookies);
128             Collections.sort(cookieList, PATH_COMPARATOR);
129         } else {
130             cookieList = cookies;
131         }
132         if (this.oneHeader) {
133             return doFormatOneHeader(cookieList);
134         } else {
135             return doFormatManyHeaders(cookieList);
136         }
137     }
138 
139     private List<Header> doFormatOneHeader(final List<Cookie> cookies) {
140         int version = Integer.MAX_VALUE;
141         // Pick the lowest common denominator
142         for (final Cookie cookie : cookies) {
143             if (cookie.getVersion() < version) {
144                 version = cookie.getVersion();
145             }
146         }
147         final CharArrayBuffer buffer = new CharArrayBuffer(40 * cookies.size());
148         buffer.append(SM.COOKIE);
149         buffer.append(": ");
150         buffer.append("$Version=");
151         buffer.append(Integer.toString(version));
152         for (final Cookie cooky : cookies) {
153             buffer.append("; ");
154             final Cookie cookie = cooky;
155             formatCookieAsVer(buffer, cookie, version);
156         }
157         final List<Header> headers = new ArrayList<Header>(1);
158         headers.add(new BufferedHeader(buffer));
159         return headers;
160     }
161 
162     private List<Header> doFormatManyHeaders(final List<Cookie> cookies) {
163         final List<Header> headers = new ArrayList<Header>(cookies.size());
164         for (final Cookie cookie : cookies) {
165             final int version = cookie.getVersion();
166             final CharArrayBuffer buffer = new CharArrayBuffer(40);
167             buffer.append("Cookie: ");
168             buffer.append("$Version=");
169             buffer.append(Integer.toString(version));
170             buffer.append("; ");
171             formatCookieAsVer(buffer, cookie, version);
172             headers.add(new BufferedHeader(buffer));
173         }
174         return headers;
175     }
176 
177     /**
178      * Return a name/value string suitable for sending in a <tt>"Cookie"</tt>
179      * header as defined in RFC 2109 for backward compatibility with cookie
180      * version 0
181      * @param buffer The char array buffer to use for output
182      * @param name The cookie name
183      * @param value The cookie value
184      * @param version The cookie version
185      */
186     protected void formatParamAsVer(final CharArrayBuffer buffer,
187             final String name, final String value, final int version) {
188         buffer.append(name);
189         buffer.append("=");
190         if (value != null) {
191             if (version > 0) {
192                 buffer.append('\"');
193                 buffer.append(value);
194                 buffer.append('\"');
195             } else {
196                 buffer.append(value);
197             }
198         }
199     }
200 
201     /**
202      * Return a string suitable for sending in a <tt>"Cookie"</tt> header
203      * as defined in RFC 2109 for backward compatibility with cookie version 0
204      * @param buffer The char array buffer to use for output
205      * @param cookie The {@link Cookie} to be formatted as string
206      * @param version The version to use.
207      */
208     protected void formatCookieAsVer(final CharArrayBuffer buffer,
209             final Cookie cookie, final int version) {
210         formatParamAsVer(buffer, cookie.getName(), cookie.getValue(), version);
211         if (cookie.getPath() != null) {
212             if (cookie instanceof ClientCookie
213                     && ((ClientCookie) cookie).containsAttribute(ClientCookie.PATH_ATTR)) {
214                 buffer.append("; ");
215                 formatParamAsVer(buffer, "$Path", cookie.getPath(), version);
216             }
217         }
218         if (cookie.getDomain() != null) {
219             if (cookie instanceof ClientCookie
220                     && ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) {
221                 buffer.append("; ");
222                 formatParamAsVer(buffer, "$Domain", cookie.getDomain(), version);
223             }
224         }
225     }
226 
227     public int getVersion() {
228         return 1;
229     }
230 
231     public Header getVersionHeader() {
232         return null;
233     }
234 
235     @Override
236     public String toString() {
237         return "rfc2109";
238     }
239 
240 }