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.List;
32  
33  import org.apache.http.FormattedHeader;
34  import org.apache.http.Header;
35  import org.apache.http.HeaderElement;
36  import org.apache.http.annotation.NotThreadSafe;
37  import org.apache.http.cookie.ClientCookie;
38  import org.apache.http.cookie.Cookie;
39  import org.apache.http.cookie.CookieOrigin;
40  import org.apache.http.cookie.MalformedCookieException;
41  import org.apache.http.cookie.SM;
42  import org.apache.http.message.BufferedHeader;
43  import org.apache.http.message.ParserCursor;
44  import org.apache.http.util.Args;
45  import org.apache.http.util.CharArrayBuffer;
46  
47  /**
48   * This {@link org.apache.http.cookie.CookieSpec} implementation conforms to
49   * the original draft specification published by Netscape Communications.
50   * It should be avoided unless absolutely necessary for compatibility with
51   * legacy applications.
52   *
53   * @since 4.0
54   */
55  @NotThreadSafe // superclass is @NotThreadSafe
56  public class NetscapeDraftSpec extends CookieSpecBase {
57  
58      protected static final String EXPIRES_PATTERN = "EEE, dd-MMM-yy HH:mm:ss z";
59  
60      private final String[] datepatterns;
61  
62      /** Default constructor */
63      public NetscapeDraftSpec(final String[] datepatterns) {
64          super();
65          if (datepatterns != null) {
66              this.datepatterns = datepatterns.clone();
67          } else {
68              this.datepatterns = new String[] { EXPIRES_PATTERN };
69          }
70          registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler());
71          registerAttribHandler(ClientCookie.DOMAIN_ATTR, new NetscapeDomainHandler());
72          registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler());
73          registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler());
74          registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler(
75                  this.datepatterns));
76      }
77  
78      /** Default constructor */
79      public NetscapeDraftSpec() {
80          this(null);
81      }
82  
83      /**
84        * Parses the Set-Cookie value into an array of <tt>Cookie</tt>s.
85        *
86        * <p>Syntax of the Set-Cookie HTTP Response Header:</p>
87        *
88        * <p>This is the format a CGI script would use to add to
89        * the HTTP headers a new piece of data which is to be stored by
90        * the client for later retrieval.</p>
91        *
92        * <PRE>
93        *  Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
94        * </PRE>
95        *
96        * <p>Please note that the Netscape draft specification does not fully conform to the HTTP
97        * header format. Comma character if present in <code>Set-Cookie</code> will not be treated
98        * as a header element separator</p>
99        *
100       * @see <a href="http://web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html">
101       *  The Cookie Spec.</a>
102       *
103       * @param header the <tt>Set-Cookie</tt> received from the server
104       * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie value
105       * @throws MalformedCookieException if an exception occurs during parsing
106       */
107     public List<Cookie> parse(final Header header, final CookieOrigin origin)
108             throws MalformedCookieException {
109         Args.notNull(header, "Header");
110         Args.notNull(origin, "Cookie origin");
111         if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) {
112             throw new MalformedCookieException("Unrecognized cookie header '"
113                     + header.toString() + "'");
114         }
115         final NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
116         final CharArrayBuffer buffer;
117         final ParserCursor cursor;
118         if (header instanceof FormattedHeader) {
119             buffer = ((FormattedHeader) header).getBuffer();
120             cursor = new ParserCursor(
121                     ((FormattedHeader) header).getValuePos(),
122                     buffer.length());
123         } else {
124             final String s = header.getValue();
125             if (s == null) {
126                 throw new MalformedCookieException("Header value is null");
127             }
128             buffer = new CharArrayBuffer(s.length());
129             buffer.append(s);
130             cursor = new ParserCursor(0, buffer.length());
131         }
132         return parse(new HeaderElement[] { parser.parseHeader(buffer, cursor) }, origin);
133     }
134 
135     public List<Header> formatCookies(final List<Cookie> cookies) {
136         Args.notEmpty(cookies, "List of cookies");
137         final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
138         buffer.append(SM.COOKIE);
139         buffer.append(": ");
140         for (int i = 0; i < cookies.size(); i++) {
141             final Cookie cookie = cookies.get(i);
142             if (i > 0) {
143                 buffer.append("; ");
144             }
145             buffer.append(cookie.getName());
146             final String s = cookie.getValue();
147             if (s != null) {
148                 buffer.append("=");
149                 buffer.append(s);
150             }
151         }
152         final List<Header> headers = new ArrayList<Header>(1);
153         headers.add(new BufferedHeader(buffer));
154         return headers;
155     }
156 
157     public int getVersion() {
158         return 0;
159     }
160 
161     public Header getVersionHeader() {
162         return null;
163     }
164 
165     @Override
166     public String toString() {
167         return "netscape";
168     }
169 
170 }