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.List;
31  
32  import org.apache.http.FormattedHeader;
33  import org.apache.http.Header;
34  import org.apache.http.HeaderElement;
35  import org.apache.http.annotation.NotThreadSafe;
36  import org.apache.http.cookie.Cookie;
37  import org.apache.http.cookie.CookieOrigin;
38  import org.apache.http.cookie.CookieSpec;
39  import org.apache.http.cookie.MalformedCookieException;
40  import org.apache.http.cookie.SM;
41  import org.apache.http.cookie.SetCookie2;
42  import org.apache.http.message.ParserCursor;
43  import org.apache.http.util.Args;
44  import org.apache.http.util.CharArrayBuffer;
45  
46  /**
47   * 'Meta' cookie specification that picks up a cookie policy based on
48   * the format of cookies sent with the HTTP response.
49   *
50   * @since 4.0
51   */
52  @NotThreadSafe // CookieSpec fields are @NotThreadSafe
53  public class BestMatchSpec implements CookieSpec {
54  
55      private final String[] datepatterns;
56      private final boolean oneHeader;
57  
58      // Cached values of CookieSpec instances
59      private RFC2965Spec strict; // @NotThreadSafe
60      private RFC2109Spec obsoleteStrict; // @NotThreadSafe
61      private BrowserCompatSpec compat; // @NotThreadSafe
62  
63      public BestMatchSpec(final String[] datepatterns, final boolean oneHeader) {
64          super();
65          this.datepatterns = datepatterns == null ? null : datepatterns.clone();
66          this.oneHeader = oneHeader;
67      }
68  
69      public BestMatchSpec() {
70          this(null, false);
71      }
72  
73      private RFC2965Spec getStrict() {
74          if (this.strict == null) {
75               this.strict = new RFC2965Spec(this.datepatterns, this.oneHeader);
76          }
77          return strict;
78      }
79  
80      private RFC2109Spec getObsoleteStrict() {
81          if (this.obsoleteStrict == null) {
82               this.obsoleteStrict = new RFC2109Spec(this.datepatterns, this.oneHeader);
83          }
84          return obsoleteStrict;
85      }
86  
87      private BrowserCompatSpec getCompat() {
88          if (this.compat == null) {
89              this.compat = new BrowserCompatSpec(this.datepatterns);
90          }
91          return compat;
92      }
93  
94      @Override
95      public List<Cookie> parse(
96              final Header header,
97              final CookieOrigin origin) throws MalformedCookieException {
98          Args.notNull(header, "Header");
99          Args.notNull(origin, "Cookie origin");
100         HeaderElement[] helems = header.getElements();
101         boolean versioned = false;
102         boolean netscape = false;
103         for (final HeaderElement helem: helems) {
104             if (helem.getParameterByName("version") != null) {
105                 versioned = true;
106             }
107             if (helem.getParameterByName("expires") != null) {
108                netscape = true;
109             }
110         }
111         if (netscape || !versioned) {
112             // Need to parse the header again, because Netscape style cookies do not correctly
113             // support multiple header elements (comma cannot be treated as an element separator)
114             final NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
115             final CharArrayBuffer buffer;
116             final ParserCursor cursor;
117             if (header instanceof FormattedHeader) {
118                 buffer = ((FormattedHeader) header).getBuffer();
119                 cursor = new ParserCursor(
120                         ((FormattedHeader) header).getValuePos(),
121                         buffer.length());
122             } else {
123                 final String s = header.getValue();
124                 if (s == null) {
125                     throw new MalformedCookieException("Header value is null");
126                 }
127                 buffer = new CharArrayBuffer(s.length());
128                 buffer.append(s);
129                 cursor = new ParserCursor(0, buffer.length());
130             }
131             helems = new HeaderElement[] { parser.parseHeader(buffer, cursor) };
132             return getCompat().parse(helems, origin);
133         } else {
134             if (SM.SET_COOKIE2.equals(header.getName())) {
135                 return getStrict().parse(helems, origin);
136             } else {
137                 return getObsoleteStrict().parse(helems, origin);
138             }
139         }
140     }
141 
142     @Override
143     public void validate(
144             final Cookie cookie,
145             final CookieOrigin origin) throws MalformedCookieException {
146         Args.notNull(cookie, "Cookie");
147         Args.notNull(origin, "Cookie origin");
148         if (cookie.getVersion() > 0) {
149             if (cookie instanceof SetCookie2) {
150                 getStrict().validate(cookie, origin);
151             } else {
152                 getObsoleteStrict().validate(cookie, origin);
153             }
154         } else {
155             getCompat().validate(cookie, origin);
156         }
157     }
158 
159     @Override
160     public boolean match(final Cookie cookie, final CookieOrigin origin) {
161         Args.notNull(cookie, "Cookie");
162         Args.notNull(origin, "Cookie origin");
163         if (cookie.getVersion() > 0) {
164             if (cookie instanceof SetCookie2) {
165                 return getStrict().match(cookie, origin);
166             } else {
167                 return getObsoleteStrict().match(cookie, origin);
168             }
169         } else {
170             return getCompat().match(cookie, origin);
171         }
172     }
173 
174     @Override
175     public List<Header> formatCookies(final List<Cookie> cookies) {
176         Args.notNull(cookies, "List of cookies");
177         int version = Integer.MAX_VALUE;
178         boolean isSetCookie2 = true;
179         for (final Cookie cookie: cookies) {
180             if (!(cookie instanceof SetCookie2)) {
181                 isSetCookie2 = false;
182             }
183             if (cookie.getVersion() < version) {
184                 version = cookie.getVersion();
185             }
186         }
187         if (version > 0) {
188             if (isSetCookie2) {
189                 return getStrict().formatCookies(cookies);
190             } else {
191                 return getObsoleteStrict().formatCookies(cookies);
192             }
193         } else {
194             return getCompat().formatCookies(cookies);
195         }
196     }
197 
198     @Override
199     public int getVersion() {
200         return getStrict().getVersion();
201     }
202 
203     @Override
204     public Header getVersionHeader() {
205         return getStrict().getVersionHeader();
206     }
207 
208     @Override
209     public String toString() {
210         return "best-match";
211     }
212 
213 }