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.hc.client5.http.protocol;
29  
30  import java.util.HashMap;
31  import java.util.Map;
32  
33  import javax.net.ssl.SSLSession;
34  
35  import org.apache.hc.client5.http.HttpRoute;
36  import org.apache.hc.client5.http.RouteInfo;
37  import org.apache.hc.client5.http.auth.AuthCache;
38  import org.apache.hc.client5.http.auth.AuthExchange;
39  import org.apache.hc.client5.http.auth.AuthScheme;
40  import org.apache.hc.client5.http.auth.AuthSchemeFactory;
41  import org.apache.hc.client5.http.auth.CredentialsProvider;
42  import org.apache.hc.client5.http.config.RequestConfig;
43  import org.apache.hc.client5.http.cookie.CookieOrigin;
44  import org.apache.hc.client5.http.cookie.CookieSpec;
45  import org.apache.hc.client5.http.cookie.CookieSpecFactory;
46  import org.apache.hc.client5.http.cookie.CookieStore;
47  import org.apache.hc.core5.annotation.Internal;
48  import org.apache.hc.core5.http.EndpointDetails;
49  import org.apache.hc.core5.http.HttpHost;
50  import org.apache.hc.core5.http.HttpRequest;
51  import org.apache.hc.core5.http.HttpResponse;
52  import org.apache.hc.core5.http.ProtocolVersion;
53  import org.apache.hc.core5.http.config.Lookup;
54  import org.apache.hc.core5.http.protocol.HttpContext;
55  import org.apache.hc.core5.http.protocol.HttpCoreContext;
56  
57  /**
58   * Client execution {@link HttpContext}. This class can be re-used for
59   * multiple consecutive logically related request executions that represent
60   * a single communication session. This context may not be used concurrently.
61   * <p>
62   * IMPORTANT: This class is NOT thread-safe and MUST NOT be used concurrently by
63   * multiple message exchanges.
64   *
65   * @since 4.3
66   */
67  public class HttpClientContext extends HttpCoreContext {
68  
69      /**
70       * @deprecated Use getter methods
71       */
72      @Deprecated
73      public static final String HTTP_ROUTE   = "http.route";
74  
75      /**
76       * @deprecated Use getter methods
77       */
78      @Deprecated
79      public static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
80  
81      /**
82       * @deprecated Use getter methods
83       */
84      @Deprecated
85      public static final String COOKIESPEC_REGISTRY   = "http.cookiespec-registry";
86  
87      /**
88       * @deprecated Use getter methods
89       */
90      @Deprecated
91      public static final String COOKIE_SPEC           = "http.cookie-spec";
92  
93      /**
94       * @deprecated Use getter methods
95       */
96      @Deprecated
97      public static final String COOKIE_ORIGIN         = "http.cookie-origin";
98  
99      /**
100      * @deprecated Use getter methods
101      */
102     @Deprecated
103     public static final String COOKIE_STORE          = "http.cookie-store";
104 
105     /**
106      * @deprecated Use getter methods
107      */
108     @Deprecated
109     public static final String CREDS_PROVIDER        = "http.auth.credentials-provider";
110 
111     /**
112      * @deprecated Use getter methods
113      */
114     @Deprecated
115     public static final String AUTH_CACHE            = "http.auth.auth-cache";
116 
117     /**
118      * @deprecated Use getter methods
119      */
120     @Deprecated
121     public static final String AUTH_EXCHANGE_MAP     = "http.auth.exchanges";
122 
123     /**
124      * @deprecated Use getter methods
125      */
126     @Deprecated
127     public static final String USER_TOKEN            = "http.user-token";
128 
129     /**
130      * @deprecated Use getter methods
131      */
132     @Deprecated
133     public static final String AUTHSCHEME_REGISTRY   = "http.authscheme-registry";
134 
135     /**
136      * @deprecated Use getter methods
137      */
138     @Deprecated
139     public static final String REQUEST_CONFIG = "http.request-config";
140 
141     /**
142      * @deprecated Use getter methods
143      */
144     @Deprecated
145     public static final String EXCHANGE_ID = "http.exchange-id";
146 
147     /**
148      * @deprecated Use {@link #castOrCreate(HttpContext)}.
149      */
150     @Deprecated
151     public static HttpClientContext adapt(final HttpContext context) {
152         if (context == null) {
153             return new HttpClientContext();
154         }
155         if (context instanceof HttpClientContext) {
156             return (HttpClientContext) context;
157         }
158         return new HttpClientContext(context);
159     }
160 
161     /**
162      * Casts the given generic {@link HttpContext} as {@link HttpClientContext} or
163      * throws an {@link IllegalStateException} if the given context is not suitable.
164      *
165      * @since 5.4
166      */
167     public static HttpClientContext cast(final HttpContext context) {
168         if (context == null) {
169             return null;
170         }
171         if (context instanceof HttpClientContext) {
172             return (HttpClientContext) context;
173         } else {
174             return new Delegate(context);
175         }
176     }
177 
178     /**
179      * Casts the given generic {@link HttpContext} as {@link HttpClientContext} or
180      * creates new {@link HttpClientContext} if the given context is null..
181      *
182      * @since 5.4
183      */
184     public static HttpClientContext castOrCreate(final HttpContext context) {
185         return context != null ? cast(context) : create();
186     }
187 
188     public static HttpClientContext create() {
189         return new HttpClientContext();
190     }
191 
192     private HttpRoute route;
193     private RedirectLocations redirectLocations;
194     private CookieSpec cookieSpec;
195     private CookieOrigin cookieOrigin;
196     private Map<HttpHost, AuthExchange> authExchangeMap;
197     private String exchangeId;
198 
199     private Lookup<CookieSpecFactory> cookieSpecFactoryLookup;
200     private Lookup<AuthSchemeFactory> authSchemeFactoryLookup;
201     private CookieStore cookieStore;
202     private CredentialsProvider credentialsProvider;
203     private AuthCache authCache;
204     private Object userToken;
205     private RequestConfig requestConfig;
206 
207     public HttpClientContext(final HttpContext context) {
208         super(context);
209     }
210 
211     public HttpClientContext() {
212         super();
213     }
214 
215     /**
216      * Represents current route used to execute message exchanges.
217      * <p>
218      * This context attribute is expected to be populated by the protocol handler.
219      */
220     public RouteInfo getHttpRoute() {
221         return route;
222     }
223 
224     /**
225      * @since 5.4
226      */
227     @Internal
228     public void setRoute(final HttpRoute route) {
229         this.route = route;
230     }
231 
232     /**
233      * Represents a collection of all redirects executed in the context of request execution.
234      * <p>
235      * This context attribute is expected to be populated by the protocol handler.
236      */
237     public RedirectLocations getRedirectLocations() {
238         if (this.redirectLocations == null) {
239             this.redirectLocations = new RedirectLocations();
240         }
241         return this.redirectLocations;
242     }
243 
244     /**
245      * @since 5.4
246      */
247     @Internal
248     public void setRedirectLocations(final RedirectLocations redirectLocations) {
249         this.redirectLocations = redirectLocations;
250     }
251 
252     /**
253      * Represents a {@link CookieStore} used in the context of the request execution.
254      * <p>
255      * This context attribute can be set by the caller.
256      */
257     public CookieStore getCookieStore() {
258         return cookieStore;
259     }
260 
261     public void setCookieStore(final CookieStore cookieStore) {
262         this.cookieStore = cookieStore;
263     }
264 
265     /**
266      * Represents a {@link CookieSpec} chosen in the context of request execution.
267      * <p>
268      * This context attribute is expected to be populated by the protocol handler.
269      */
270     public CookieSpec getCookieSpec() {
271         return cookieSpec;
272     }
273 
274     /**
275      * @since 5.4
276      */
277     @Internal
278     public void setCookieSpec(final CookieSpec cookieSpec) {
279         this.cookieSpec = cookieSpec;
280     }
281 
282     /**
283      * Represents a {@link CookieOrigin} produced in the context of request execution.
284      * <p>
285      * This context attribute is expected to be populated by the protocol handler.
286      */
287     public CookieOrigin getCookieOrigin() {
288         return cookieOrigin;
289     }
290 
291     /**
292      * @since 5.4
293      */
294     @Internal
295     public void setCookieOrigin(final CookieOrigin cookieOrigin) {
296         this.cookieOrigin = cookieOrigin;
297     }
298 
299     /**
300      * Represents a {@link CookieSpecFactory} registry used in the context of the request execution.
301      * <p>
302      * This context attribute can be set by the caller.
303      */
304     public Lookup<CookieSpecFactory> getCookieSpecRegistry() {
305         return cookieSpecFactoryLookup;
306     }
307 
308     public void setCookieSpecRegistry(final Lookup<CookieSpecFactory> lookup) {
309         this.cookieSpecFactoryLookup = lookup;
310     }
311 
312     /**
313      * Represents a {@link AuthSchemeFactory} registry used in the context of the request execution.
314      * <p>
315      * This context attribute can be set by the caller.
316      */
317     public Lookup<AuthSchemeFactory> getAuthSchemeRegistry() {
318         return authSchemeFactoryLookup;
319     }
320 
321     public void setAuthSchemeRegistry(final Lookup<AuthSchemeFactory> lookup) {
322         this.authSchemeFactoryLookup = lookup;
323     }
324 
325     /**
326      * Represents a {@link CredentialsProvider} registry used in the context of the request execution.
327      * <p>
328      * This context attribute can be set by the caller.
329      */
330     public CredentialsProvider getCredentialsProvider() {
331         return credentialsProvider;
332     }
333 
334     public void setCredentialsProvider(final CredentialsProvider credentialsProvider) {
335         this.credentialsProvider = credentialsProvider;
336     }
337 
338     /**
339      * Represents a {@link AuthCache} used in the context of the request execution.
340      * <p>
341      * This context attribute can be set by the caller.
342      */
343     public AuthCache getAuthCache() {
344         return authCache;
345     }
346 
347     public void setAuthCache(final AuthCache authCache) {
348         this.authCache = authCache;
349     }
350 
351     /**
352      * Represents a map of {@link AuthExchange}s performed in the context of the request
353      * execution.
354      * <p>
355      * This context attribute is expected to be populated by the protocol handler.
356      *
357      * @since 5.0
358      */
359     public Map<HttpHost, AuthExchange> getAuthExchanges() {
360         if (authExchangeMap == null) {
361             authExchangeMap = new HashMap<>();
362         }
363         return authExchangeMap;
364     }
365 
366     /**
367      * @since 5.0
368      */
369     public AuthExchange getAuthExchange(final HttpHost host) {
370         return getAuthExchanges().computeIfAbsent(host, k -> new AuthExchange());
371     }
372 
373     /**
374      * @since 5.0
375      */
376     public void setAuthExchange(final HttpHost host, final AuthExchange authExchange) {
377         getAuthExchanges().put(host, authExchange);
378     }
379 
380     /**
381      * @since 5.0
382      */
383     public void resetAuthExchange(final HttpHost host, final AuthScheme authScheme) {
384         final AuthExchange authExchange = new AuthExchange();
385         authExchange.select(authScheme);
386         getAuthExchanges().put(host, authExchange);
387     }
388 
389     /**
390      * @deprecated Use {@link #getUserToken()}
391      */
392     @Deprecated
393     @SuppressWarnings("unchecked")
394     public <T> T getUserToken(final Class<T> clazz) {
395         return (T) getUserToken();
396     }
397 
398     /**
399      * Represents an arbitrary user token that identifies the user in the context
400      * of the request execution.
401      * <p>
402      * This context attribute can be set by the caller.
403      */
404     public Object getUserToken() {
405         return userToken;
406     }
407 
408     public void setUserToken(final Object userToken) {
409         this.userToken = userToken;
410     }
411 
412     /**
413      * Represents an {@link RequestConfig used} in the context of the request execution.
414      * <p>
415      * This context attribute can be set by the caller.
416      */
417     public RequestConfig getRequestConfig() {
418         return requestConfig;
419     }
420 
421     /**
422      * Returns {@link RequestConfig} set in the context or {@link RequestConfig#DEFAULT}
423      * if not explicitly set in the context.
424      *
425      * @since 5.4
426      */
427     public final RequestConfig getRequestConfigOrDefault() {
428         final RequestConfig requestConfig = getRequestConfig();
429         return requestConfig != null ? requestConfig : RequestConfig.DEFAULT;
430     }
431 
432     public void setRequestConfig(final RequestConfig requestConfig) {
433         this.requestConfig = requestConfig;
434     }
435 
436     /**
437      * Represents an identifier generated for the current message exchange executed
438      * in the given context.
439      * <p>
440      * This context attribute is expected to be populated by the protocol handler.
441      * @since 5.1
442      */
443     public String getExchangeId() {
444         return exchangeId;
445     }
446 
447     /**
448      * @since 5.1
449      */
450     public void setExchangeId(final String exchangeId) {
451         this.exchangeId = exchangeId;
452     }
453 
454     /**
455      * Internal adaptor class that delegates all its method calls to a plain {@link HttpContext}.
456      * To be removed in the future.
457      */
458     @SuppressWarnings("deprecation")
459     @Internal
460     static class Delegate extends HttpClientContext {
461 
462         private final HttpContext httpContext;
463 
464         Delegate(final HttpContext httpContext) {
465             super(null);
466             this.httpContext = httpContext;
467         }
468 
469         <T> T getAttr(final String id, final Class<T> clazz) {
470             final Object obj = httpContext.getAttribute(id);
471             if (obj == null) {
472                 return null;
473             }
474             return clazz.cast(obj);
475         }
476 
477         @Override
478         public RouteInfo getHttpRoute() {
479             return getAttr(HTTP_ROUTE, RouteInfo.class);
480         }
481 
482         @Override
483         public void setRoute(final HttpRoute route) {
484             httpContext.setAttribute(HTTP_ROUTE, route);
485         }
486 
487         @Override
488         public RedirectLocations getRedirectLocations() {
489             RedirectLocations redirectLocations = getAttr(REDIRECT_LOCATIONS, RedirectLocations.class);
490             if (redirectLocations == null) {
491                 redirectLocations = new RedirectLocations();
492                 httpContext.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
493             }
494             return redirectLocations;
495         }
496 
497         @Override
498         public void setRedirectLocations(final RedirectLocations redirectLocations) {
499             httpContext.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
500         }
501 
502         @Override
503         public CookieStore getCookieStore() {
504             return getAttr(COOKIE_STORE, CookieStore.class);
505         }
506 
507         @Override
508         public void setCookieStore(final CookieStore cookieStore) {
509             httpContext.setAttribute(COOKIE_STORE, cookieStore);
510         }
511 
512         @Override
513         public CookieSpec getCookieSpec() {
514             return getAttr(COOKIE_SPEC, CookieSpec.class);
515         }
516 
517         @Override
518         public void setCookieSpec(final CookieSpec cookieSpec) {
519             httpContext.setAttribute(COOKIE_SPEC, cookieSpec);
520         }
521 
522         @Override
523         public CookieOrigin getCookieOrigin() {
524             return getAttr(COOKIE_ORIGIN, CookieOrigin.class);
525         }
526 
527         @Override
528         public void setCookieOrigin(final CookieOrigin cookieOrigin) {
529             httpContext.setAttribute(COOKIE_ORIGIN, cookieOrigin);
530         }
531 
532         @Override
533         public Lookup<CookieSpecFactory> getCookieSpecRegistry() {
534             return getAttr(COOKIESPEC_REGISTRY, Lookup.class);
535         }
536 
537         @Override
538         public void setCookieSpecRegistry(final Lookup<CookieSpecFactory> lookup) {
539             httpContext.setAttribute(COOKIESPEC_REGISTRY, lookup);
540         }
541 
542         @Override
543         public Lookup<AuthSchemeFactory> getAuthSchemeRegistry() {
544             return getAttr(AUTHSCHEME_REGISTRY, Lookup.class);
545         }
546 
547         @Override
548         public void setAuthSchemeRegistry(final Lookup<AuthSchemeFactory> lookup) {
549             httpContext.setAttribute(AUTHSCHEME_REGISTRY, lookup);
550         }
551 
552         @Override
553         public CredentialsProvider getCredentialsProvider() {
554             return getAttr(CREDS_PROVIDER, CredentialsProvider.class);
555         }
556 
557         @Override
558         public void setCredentialsProvider(final CredentialsProvider credentialsProvider) {
559             httpContext.setAttribute(CREDS_PROVIDER, credentialsProvider);
560         }
561 
562         @Override
563         public AuthCache getAuthCache() {
564             return getAttr(AUTH_CACHE, AuthCache.class);
565         }
566 
567         @Override
568         public void setAuthCache(final AuthCache authCache) {
569             httpContext.setAttribute(AUTH_CACHE, authCache);
570         }
571 
572         @Override
573         public Map<HttpHost, AuthExchange> getAuthExchanges() {
574             Map<HttpHost, AuthExchange> map = getAttr(AUTH_EXCHANGE_MAP, Map.class);
575             if (map == null) {
576                 map = new HashMap<>();
577                 httpContext.setAttribute(AUTH_EXCHANGE_MAP, map);
578             }
579             return map;
580         }
581 
582         @Override
583         public Object getUserToken() {
584             return httpContext.getAttribute(USER_TOKEN);
585         }
586 
587         @Override
588         public void setUserToken(final Object userToken) {
589             httpContext.setAttribute(USER_TOKEN, userToken);
590         }
591 
592         @Override
593         public RequestConfig getRequestConfig() {
594             return getAttr(REQUEST_CONFIG, RequestConfig.class);
595         }
596 
597         @Override
598         public void setRequestConfig(final RequestConfig requestConfig) {
599             httpContext.setAttribute(REQUEST_CONFIG, requestConfig);
600         }
601 
602         @Override
603         public String getExchangeId() {
604             return getAttr(EXCHANGE_ID, String.class);
605         }
606 
607         @Override
608         public void setExchangeId(final String exchangeId) {
609             httpContext.setAttribute(EXCHANGE_ID, exchangeId);
610         }
611 
612         @Override
613         public HttpRequest getRequest() {
614             return getAttr(HttpCoreContext.HTTP_REQUEST, HttpRequest.class);
615         }
616 
617         @Override
618         public void setRequest(final HttpRequest request) {
619             httpContext.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
620         }
621 
622         @Override
623         public HttpResponse getResponse() {
624             return getAttr(HttpCoreContext.HTTP_RESPONSE, HttpResponse.class);
625         }
626 
627         @Override
628         public void setResponse(final HttpResponse response) {
629             httpContext.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
630         }
631 
632         @Override
633         public EndpointDetails getEndpointDetails() {
634             return getAttr(HttpCoreContext.CONNECTION_ENDPOINT, EndpointDetails.class);
635         }
636 
637         @Override
638         public void setEndpointDetails(final EndpointDetails endpointDetails) {
639             httpContext.setAttribute(CONNECTION_ENDPOINT, endpointDetails);
640         }
641 
642         @Override
643         public SSLSession getSSLSession() {
644             return getAttr(HttpCoreContext.SSL_SESSION, SSLSession.class);
645         }
646 
647         @Override
648         public void setSSLSession(final SSLSession sslSession) {
649             httpContext.setAttribute(HttpCoreContext.SSL_SESSION, sslSession);
650         }
651 
652         @Override
653         public ProtocolVersion getProtocolVersion() {
654             return httpContext.getProtocolVersion();
655         }
656 
657         @Override
658         public void setProtocolVersion(final ProtocolVersion version) {
659             httpContext.setProtocolVersion(version);
660         }
661 
662         @Override
663         public Object getAttribute(final String id) {
664             return httpContext.getAttribute(id);
665         }
666 
667         @Override
668         public Object setAttribute(final String id, final Object obj) {
669             return httpContext.setAttribute(id, obj);
670         }
671 
672         @Override
673         public Object removeAttribute(final String id) {
674             return httpContext.removeAttribute(id);
675         }
676 
677         @Override
678         public <T> T getAttribute(final String id, final Class<T> clazz) {
679             return getAttr(id, clazz);
680         }
681 
682         @Override
683         public String toString() {
684             return httpContext.toString();
685         }
686 
687     }
688 
689 }