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