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.client.protocol;
29  
30  import java.io.IOException;
31  import java.util.List;
32  
33  import org.apache.commons.logging.Log;
34  import org.apache.commons.logging.LogFactory;
35  import org.apache.http.Header;
36  import org.apache.http.HeaderIterator;
37  import org.apache.http.HttpException;
38  import org.apache.http.HttpResponse;
39  import org.apache.http.HttpResponseInterceptor;
40  import org.apache.http.annotation.Immutable;
41  import org.apache.http.client.CookieStore;
42  import org.apache.http.cookie.Cookie;
43  import org.apache.http.cookie.CookieOrigin;
44  import org.apache.http.cookie.CookieSpec;
45  import org.apache.http.cookie.MalformedCookieException;
46  import org.apache.http.cookie.SM;
47  import org.apache.http.protocol.HttpContext;
48  import org.apache.http.util.Args;
49  
50  /**
51   * Response interceptor that populates the current {@link CookieStore} with data
52   * contained in response cookies received in the given the HTTP response.
53   *
54   * @since 4.0
55   */
56  @Immutable
57  public class ResponseProcessCookies implements HttpResponseInterceptor {
58  
59      private final Log log = LogFactory.getLog(getClass());
60  
61      public ResponseProcessCookies() {
62          super();
63      }
64  
65      public void process(final HttpResponse response, final HttpContext context)
66              throws HttpException, IOException {
67          Args.notNull(response, "HTTP request");
68          Args.notNull(context, "HTTP context");
69  
70          final HttpClientContext clientContext = HttpClientContext.adapt(context);
71  
72          // Obtain actual CookieSpec instance
73          final CookieSpec cookieSpec = clientContext.getCookieSpec();
74          if (cookieSpec == null) {
75              this.log.debug("Cookie spec not specified in HTTP context");
76              return;
77          }
78          // Obtain cookie store
79          final CookieStore cookieStore = clientContext.getCookieStore();
80          if (cookieStore == null) {
81              this.log.debug("Cookie store not specified in HTTP context");
82              return;
83          }
84          // Obtain actual CookieOrigin instance
85          final CookieOrigin cookieOrigin = clientContext.getCookieOrigin();
86          if (cookieOrigin == null) {
87              this.log.debug("Cookie origin not specified in HTTP context");
88              return;
89          }
90          HeaderIterator it = response.headerIterator(SM.SET_COOKIE);
91          processCookies(it, cookieSpec, cookieOrigin, cookieStore);
92  
93          // see if the cookie spec supports cookie versioning.
94          if (cookieSpec.getVersion() > 0) {
95              // process set-cookie2 headers.
96              // Cookie2 will replace equivalent Cookie instances
97              it = response.headerIterator(SM.SET_COOKIE2);
98              processCookies(it, cookieSpec, cookieOrigin, cookieStore);
99          }
100     }
101 
102     private void processCookies(
103             final HeaderIterator iterator,
104             final CookieSpec cookieSpec,
105             final CookieOrigin cookieOrigin,
106             final CookieStore cookieStore) {
107         while (iterator.hasNext()) {
108             final Header header = iterator.nextHeader();
109             try {
110                 final List<Cookie> cookies = cookieSpec.parse(header, cookieOrigin);
111                 for (final Cookie cookie : cookies) {
112                     try {
113                         cookieSpec.validate(cookie, cookieOrigin);
114                         cookieStore.addCookie(cookie);
115 
116                         if (this.log.isDebugEnabled()) {
117                             this.log.debug("Cookie accepted [" + formatCooke(cookie) + "]");
118                         }
119                     } catch (final MalformedCookieException ex) {
120                         if (this.log.isWarnEnabled()) {
121                             this.log.warn("Cookie rejected [" + formatCooke(cookie) + "] "
122                                     + ex.getMessage());
123                         }
124                     }
125                 }
126             } catch (final MalformedCookieException ex) {
127                 if (this.log.isWarnEnabled()) {
128                     this.log.warn("Invalid cookie header: \""
129                             + header + "\". " + ex.getMessage());
130                 }
131             }
132         }
133     }
134 
135     private static String formatCooke(final Cookie cookie) {
136         final StringBuilder buf = new StringBuilder();
137         buf.append(cookie.getName());
138         buf.append("=\"");
139         String v = cookie.getValue();
140         if (v.length() > 100) {
141             v = v.substring(0, 100) + "...";
142         }
143         buf.append(v);
144         buf.append("\"");
145         buf.append(", version:");
146         buf.append(Integer.toString(cookie.getVersion()));
147         buf.append(", domain:");
148         buf.append(cookie.getDomain());
149         buf.append(", path:");
150         buf.append(cookie.getPath());
151         buf.append(", expiry:");
152         buf.append(cookie.getExpiryDate());
153         return buf.toString();
154     }
155 
156 }