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.client;
29  
30  import java.io.Closeable;
31  import java.io.IOException;
32  import java.util.List;
33  import java.util.concurrent.TimeUnit;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.http.HttpException;
38  import org.apache.http.HttpHost;
39  import org.apache.http.HttpRequest;
40  import org.apache.http.annotation.ThreadSafe;
41  import org.apache.http.auth.AuthSchemeProvider;
42  import org.apache.http.auth.AuthState;
43  import org.apache.http.client.ClientProtocolException;
44  import org.apache.http.client.CookieStore;
45  import org.apache.http.client.CredentialsProvider;
46  import org.apache.http.client.config.RequestConfig;
47  import org.apache.http.client.methods.CloseableHttpResponse;
48  import org.apache.http.client.methods.Configurable;
49  import org.apache.http.client.methods.HttpExecutionAware;
50  import org.apache.http.client.methods.HttpRequestWrapper;
51  import org.apache.http.client.params.ClientPNames;
52  import org.apache.http.client.params.HttpClientParamConfig;
53  import org.apache.http.client.protocol.HttpClientContext;
54  import org.apache.http.config.Lookup;
55  import org.apache.http.conn.ClientConnectionManager;
56  import org.apache.http.conn.ClientConnectionRequest;
57  import org.apache.http.conn.HttpClientConnectionManager;
58  import org.apache.http.conn.ManagedClientConnection;
59  import org.apache.http.conn.routing.HttpRoute;
60  import org.apache.http.conn.routing.HttpRoutePlanner;
61  import org.apache.http.conn.scheme.SchemeRegistry;
62  import org.apache.http.cookie.CookieSpecProvider;
63  import org.apache.http.impl.execchain.ClientExecChain;
64  import org.apache.http.params.HttpParams;
65  import org.apache.http.params.HttpParamsNames;
66  import org.apache.http.protocol.BasicHttpContext;
67  import org.apache.http.protocol.HttpContext;
68  import org.apache.http.util.Args;
69  
70  /**
71   * Internal class.
72   *
73   * @since 4.3
74   */
75  @ThreadSafe
76  @SuppressWarnings("deprecation")
77  class InternalHttpClient extends CloseableHttpClient {
78  
79      private final Log log = LogFactory.getLog(getClass());
80  
81      private final ClientExecChain execChain;
82      private final HttpClientConnectionManager connManager;
83      private final HttpRoutePlanner routePlanner;
84      private final Lookup<CookieSpecProvider> cookieSpecRegistry;
85      private final Lookup<AuthSchemeProvider> authSchemeRegistry;
86      private final CookieStore cookieStore;
87      private final CredentialsProvider credentialsProvider;
88      private final RequestConfig defaultConfig;
89      private final List<Closeable> closeables;
90  
91      public InternalHttpClient(
92              final ClientExecChain execChain,
93              final HttpClientConnectionManager connManager,
94              final HttpRoutePlanner routePlanner,
95              final Lookup<CookieSpecProvider> cookieSpecRegistry,
96              final Lookup<AuthSchemeProvider> authSchemeRegistry,
97              final CookieStore cookieStore,
98              final CredentialsProvider credentialsProvider,
99              final RequestConfig defaultConfig,
100             final List<Closeable> closeables) {
101         super();
102         Args.notNull(execChain, "HTTP client exec chain");
103         Args.notNull(connManager, "HTTP connection manager");
104         Args.notNull(routePlanner, "HTTP route planner");
105         this.execChain = execChain;
106         this.connManager = connManager;
107         this.routePlanner = routePlanner;
108         this.cookieSpecRegistry = cookieSpecRegistry;
109         this.authSchemeRegistry = authSchemeRegistry;
110         this.cookieStore = cookieStore;
111         this.credentialsProvider = credentialsProvider;
112         this.defaultConfig = defaultConfig;
113         this.closeables = closeables;
114     }
115 
116     private HttpRoute determineRoute(
117             final HttpHost target,
118             final HttpRequest request,
119             final HttpContext context) throws HttpException {
120         HttpHost host = target;
121         if (host == null) {
122             host = (HttpHost) request.getParams().getParameter(ClientPNames.DEFAULT_HOST);
123         }
124         return this.routePlanner.determineRoute(host, request, context);
125     }
126 
127     private void setupContext(final HttpClientContext context) {
128         if (context.getAttribute(HttpClientContext.TARGET_AUTH_STATE) == null) {
129             context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, new AuthState());
130         }
131         if (context.getAttribute(HttpClientContext.PROXY_AUTH_STATE) == null) {
132             context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, new AuthState());
133         }
134         if (context.getAttribute(HttpClientContext.AUTHSCHEME_REGISTRY) == null) {
135             context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry);
136         }
137         if (context.getAttribute(HttpClientContext.COOKIESPEC_REGISTRY) == null) {
138             context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);
139         }
140         if (context.getAttribute(HttpClientContext.COOKIE_STORE) == null) {
141             context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
142         }
143         if (context.getAttribute(HttpClientContext.CREDS_PROVIDER) == null) {
144             context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider);
145         }
146         if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
147             context.setAttribute(HttpClientContext.REQUEST_CONFIG, this.defaultConfig);
148         }
149     }
150 
151     @Override
152     protected CloseableHttpResponse doExecute(
153             final HttpHost target,
154             final HttpRequest request,
155             final HttpContext context) throws IOException, ClientProtocolException {
156         Args.notNull(request, "HTTP request");
157         HttpExecutionAware execAware = null;
158         if (request instanceof HttpExecutionAware) {
159             execAware = (HttpExecutionAware) request;
160         }
161         try {
162             final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request);
163             final HttpClientContext localcontext = HttpClientContext.adapt(
164                     context != null ? context : new BasicHttpContext());
165             RequestConfig config = null;
166             if (request instanceof Configurable) {
167                 config = ((Configurable) request).getConfig();
168             }
169             if (config == null) {
170                 final HttpParams params = request.getParams();
171                 if (params instanceof HttpParamsNames) {
172                     if (!((HttpParamsNames) params).getNames().isEmpty()) {
173                         config = HttpClientParamConfig.getRequestConfig(params);
174                     }
175                 } else {
176                     config = HttpClientParamConfig.getRequestConfig(params);
177                 }
178             }
179             if (config != null) {
180                 localcontext.setRequestConfig(config);
181             }
182             setupContext(localcontext);
183             final HttpRoute route = determineRoute(target, wrapper, localcontext);
184             return this.execChain.execute(route, wrapper, localcontext, execAware);
185         } catch (final HttpException httpException) {
186             throw new ClientProtocolException(httpException);
187         }
188     }
189 
190     public void close() {
191         this.connManager.shutdown();
192         if (this.closeables != null) {
193             for (final Closeable closeable: this.closeables) {
194                 try {
195                     closeable.close();
196                 } catch (final IOException ex) {
197                     this.log.error(ex.getMessage(), ex);
198                 }
199             }
200         }
201     }
202 
203     public HttpParams getParams() {
204         throw new UnsupportedOperationException();
205     }
206 
207     public ClientConnectionManager getConnectionManager() {
208 
209         return new ClientConnectionManager() {
210 
211             public void shutdown() {
212                 connManager.shutdown();
213             }
214 
215             public ClientConnectionRequest requestConnection(
216                     final HttpRoute route, final Object state) {
217                 throw new UnsupportedOperationException();
218             }
219 
220             public void releaseConnection(
221                     final ManagedClientConnection conn,
222                     final long validDuration, final TimeUnit timeUnit) {
223                 throw new UnsupportedOperationException();
224             }
225 
226             public SchemeRegistry getSchemeRegistry() {
227                 throw new UnsupportedOperationException();
228             }
229 
230             public void closeIdleConnections(final long idletime, final TimeUnit tunit) {
231                 connManager.closeIdleConnections(idletime, tunit);
232             }
233 
234             public void closeExpiredConnections() {
235                 connManager.closeExpiredConnections();
236             }
237 
238         };
239 
240     }
241 
242 }