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      @Override
66      public void process(final HttpResponse response, final HttpContext context)
67              throws HttpException, IOException {
68          Args.notNull(response, "HTTP request");
69          Args.notNull(context, "HTTP context");
70  
71          final HttpClientContext clientContext = HttpClientContext.adapt(context);
72  
73          // Obtain actual CookieSpec instance
74          final CookieSpec cookieSpec = clientContext.getCookieSpec();
75          if (cookieSpec == null) {
76              this.log.debug("Cookie spec not specified in HTTP context");
77              return;
78          }
79          // Obtain cookie store
80          final CookieStore cookieStore = clientContext.getCookieStore();
81          if (cookieStore == null) {
82              this.log.debug("Cookie store not specified in HTTP context");
83              return;
84          }
85          // Obtain actual CookieOrigin instance
86          final CookieOrigin cookieOrigin = clientContext.getCookieOrigin();
87          if (cookieOrigin == null) {
88              this.log.debug("Cookie origin not specified in HTTP context");
89              return;
90          }
91          HeaderIterator it = response.headerIterator(SM.SET_COOKIE);
92          processCookies(it, cookieSpec, cookieOrigin, cookieStore);
93  
94          // see if the cookie spec supports cookie versioning.
95          if (cookieSpec.getVersion() > 0) {
96              // process set-cookie2 headers.
97              // Cookie2 will replace equivalent Cookie instances
98              it = response.headerIterator(SM.SET_COOKIE2);
99              processCookies(it, cookieSpec, cookieOrigin, cookieStore);
100         }
101     }
102 
103     private void processCookies(
104             final HeaderIterator iterator,
105             final CookieSpec cookieSpec,
106             final CookieOrigin cookieOrigin,
107             final CookieStore cookieStore) {
108         while (iterator.hasNext()) {
109             final Header header = iterator.nextHeader();
110             try {
111                 final List<Cookie> cookies = cookieSpec.parse(header, cookieOrigin);
112                 for (final Cookie cookie : cookies) {
113                     try {
114                         cookieSpec.validate(cookie, cookieOrigin);
115                         cookieStore.addCookie(cookie);
116 
117                         if (this.log.isDebugEnabled()) {
118                             this.log.debug("Cookie accepted [" + formatCooke(cookie) + "]");
119                         }
120                     } catch (final MalformedCookieException ex) {
121                         if (this.log.isWarnEnabled()) {
122                             this.log.warn("Cookie rejected [" + formatCooke(cookie) + "] "
123                                     + ex.getMessage());
124                         }
125                     }
126                 }
127             } catch (final MalformedCookieException ex) {
128                 if (this.log.isWarnEnabled()) {
129                     this.log.warn("Invalid cookie header: \""
130                             + header + "\". " + ex.getMessage());
131                 }
132             }
133         }
134     }
135 
136     private static String formatCooke(final Cookie cookie) {
137         final StringBuilder buf = new StringBuilder();
138         buf.append(cookie.getName());
139         buf.append("=\"");
140         String v = cookie.getValue();
141         if (v != null) {
142             if (v.length() > 100) {
143                 v = v.substring(0, 100) + "...";
144             }
145             buf.append(v);
146         }
147         buf.append("\"");
148         buf.append(", version:");
149         buf.append(Integer.toString(cookie.getVersion()));
150         buf.append(", domain:");
151         buf.append(cookie.getDomain());
152         buf.append(", path:");
153         buf.append(cookie.getPath());
154         buf.append(", expiry:");
155         buf.append(cookie.getExpiryDate());
156         return buf.toString();
157     }
158 
159 }