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