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.execchain;
29  
30  import java.io.IOException;
31  import java.io.InterruptedIOException;
32  import java.net.URI;
33  import java.net.URISyntaxException;
34  import java.util.concurrent.ExecutionException;
35  import java.util.concurrent.TimeUnit;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.apache.http.ConnectionReuseStrategy;
40  import org.apache.http.HttpClientConnection;
41  import org.apache.http.HttpEntity;
42  import org.apache.http.HttpException;
43  import org.apache.http.HttpHost;
44  import org.apache.http.HttpRequest;
45  import org.apache.http.HttpResponse;
46  import org.apache.http.ProtocolException;
47  import org.apache.http.annotation.Contract;
48  import org.apache.http.annotation.ThreadingBehavior;
49  import org.apache.http.client.config.RequestConfig;
50  import org.apache.http.client.methods.CloseableHttpResponse;
51  import org.apache.http.client.methods.HttpExecutionAware;
52  import org.apache.http.client.methods.HttpRequestWrapper;
53  import org.apache.http.client.methods.HttpUriRequest;
54  import org.apache.http.client.protocol.HttpClientContext;
55  import org.apache.http.client.protocol.RequestClientConnControl;
56  import org.apache.http.client.utils.URIUtils;
57  import org.apache.http.conn.ConnectionKeepAliveStrategy;
58  import org.apache.http.conn.ConnectionRequest;
59  import org.apache.http.conn.HttpClientConnectionManager;
60  import org.apache.http.conn.routing.HttpRoute;
61  import org.apache.http.impl.conn.ConnectionShutdownException;
62  import org.apache.http.protocol.HttpCoreContext;
63  import org.apache.http.protocol.HttpProcessor;
64  import org.apache.http.protocol.HttpRequestExecutor;
65  import org.apache.http.protocol.ImmutableHttpProcessor;
66  import org.apache.http.protocol.RequestContent;
67  import org.apache.http.protocol.RequestTargetHost;
68  import org.apache.http.protocol.RequestUserAgent;
69  import org.apache.http.util.Args;
70  import org.apache.http.util.VersionInfo;
71  
72  import static org.apache.http.client.utils.URIUtils.DROP_FRAGMENT;
73  import static org.apache.http.client.utils.URIUtils.DROP_FRAGMENT_AND_NORMALIZE;
74  
75  /**
76   * Request executor that implements the most fundamental aspects of
77   * the HTTP specification and the most straight-forward request / response
78   * exchange with the target server. This executor does not support
79   * execution via proxy and will make no attempts to retry the request
80   * in case of a redirect, authentication challenge or I/O error.
81   *
82   * @since 4.3
83   */
84  @Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL)
85  public class MinimalClientExec implements ClientExecChain {
86  
87      private final Log log = LogFactory.getLog(getClass());
88  
89      private final HttpRequestExecutor requestExecutor;
90      private final HttpClientConnectionManager connManager;
91      private final ConnectionReuseStrategy reuseStrategy;
92      private final ConnectionKeepAliveStrategy keepAliveStrategy;
93      private final HttpProcessor httpProcessor;
94  
95      public MinimalClientExec(
96              final HttpRequestExecutor requestExecutor,
97              final HttpClientConnectionManager connManager,
98              final ConnectionReuseStrategy reuseStrategy,
99              final ConnectionKeepAliveStrategy keepAliveStrategy) {
100         Args.notNull(requestExecutor, "HTTP request executor");
101         Args.notNull(connManager, "Client connection manager");
102         Args.notNull(reuseStrategy, "Connection reuse strategy");
103         Args.notNull(keepAliveStrategy, "Connection keep alive strategy");
104         this.httpProcessor = new ImmutableHttpProcessor(
105                 new RequestContent(),
106                 new RequestTargetHost(),
107                 new RequestClientConnControl(),
108                 new RequestUserAgent(VersionInfo.getUserAgent(
109                         "Apache-HttpClient", "org.apache.http.client", getClass())));
110         this.requestExecutor    = requestExecutor;
111         this.connManager        = connManager;
112         this.reuseStrategy      = reuseStrategy;
113         this.keepAliveStrategy  = keepAliveStrategy;
114     }
115 
116     static void rewriteRequestURI(
117             final HttpRequestWrapper request,
118             final HttpRoute route,
119             final boolean normalizeUri) throws ProtocolException {
120         try {
121             URI uri = request.getURI();
122             if (uri != null) {
123                 // Make sure the request URI is relative
124                 if (uri.isAbsolute()) {
125                     uri = URIUtils.rewriteURI(uri, null, normalizeUri ? DROP_FRAGMENT_AND_NORMALIZE : DROP_FRAGMENT);
126                 } else {
127                     uri = URIUtils.rewriteURI(uri);
128                 }
129                 request.setURI(uri);
130             }
131         } catch (final URISyntaxException ex) {
132             throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex);
133         }
134     }
135 
136     @Override
137     public CloseableHttpResponse execute(
138             final HttpRoute route,
139             final HttpRequestWrapper request,
140             final HttpClientContext context,
141             final HttpExecutionAware execAware) throws IOException, HttpException {
142         Args.notNull(route, "HTTP route");
143         Args.notNull(request, "HTTP request");
144         Args.notNull(context, "HTTP context");
145 
146         rewriteRequestURI(request, route, context.getRequestConfig().isNormalizeUri());
147 
148         final ConnectionRequest connRequest = connManager.requestConnection(route, null);
149         if (execAware != null) {
150             if (execAware.isAborted()) {
151                 connRequest.cancel();
152                 throw new RequestAbortedException("Request aborted");
153             }
154             execAware.setCancellable(connRequest);
155         }
156 
157         final RequestConfig config = context.getRequestConfig();
158 
159         final HttpClientConnection managedConn;
160         try {
161             final int timeout = config.getConnectionRequestTimeout();
162             managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS);
163         } catch(final InterruptedException interrupted) {
164             Thread.currentThread().interrupt();
165             throw new RequestAbortedException("Request aborted", interrupted);
166         } catch(final ExecutionException ex) {
167             Throwable cause = ex.getCause();
168             if (cause == null) {
169                 cause = ex;
170             }
171             throw new RequestAbortedException("Request execution failed", cause);
172         }
173 
174         final ConnectionHolderlder.html#ConnectionHolder">ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn);
175         try {
176             if (execAware != null) {
177                 if (execAware.isAborted()) {
178                     releaseTrigger.close();
179                     throw new RequestAbortedException("Request aborted");
180                 }
181                 execAware.setCancellable(releaseTrigger);
182             }
183 
184             if (!managedConn.isOpen()) {
185                 final int timeout = config.getConnectTimeout();
186                 this.connManager.connect(
187                     managedConn,
188                     route,
189                     timeout > 0 ? timeout : 0,
190                     context);
191                 this.connManager.routeComplete(managedConn, route, context);
192             }
193             final int timeout = config.getSocketTimeout();
194             if (timeout >= 0) {
195                 managedConn.setSocketTimeout(timeout);
196             }
197 
198             HttpHost target = null;
199             final HttpRequest original = request.getOriginal();
200             if (original instanceof HttpUriRequest) {
201                 final URI uri = ((HttpUriRequest) original).getURI();
202                 if (uri.isAbsolute()) {
203                     target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
204                 }
205             }
206             if (target == null) {
207                 target = route.getTargetHost();
208             }
209 
210             context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
211             context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
212             context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn);
213             context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
214 
215             httpProcessor.process(request, context);
216             final HttpResponse response = requestExecutor.execute(request, managedConn, context);
217             httpProcessor.process(response, context);
218 
219             // The connection is in or can be brought to a re-usable state.
220             if (reuseStrategy.keepAlive(response, context)) {
221                 // Set the idle duration of this connection
222                 final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
223                 releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS);
224                 releaseTrigger.markReusable();
225             } else {
226                 releaseTrigger.markNonReusable();
227             }
228 
229             // check for entity, release connection if possible
230             final HttpEntity entity = response.getEntity();
231             if (entity == null || !entity.isStreaming()) {
232                 // connection not needed and (assumed to be) in re-usable state
233                 releaseTrigger.releaseConnection();
234                 return new HttpResponseProxy(response, null);
235             }
236             return new HttpResponseProxy(response, releaseTrigger);
237         } catch (final ConnectionShutdownException ex) {
238             final InterruptedIOException ioex = new InterruptedIOException(
239                     "Connection has been shut down");
240             ioex.initCause(ex);
241             throw ioex;
242         } catch (final HttpException ex) {
243             releaseTrigger.abortConnection();
244             throw ex;
245         } catch (final IOException ex) {
246             releaseTrigger.abortConnection();
247             throw ex;
248         } catch (final RuntimeException ex) {
249             releaseTrigger.abortConnection();
250             throw ex;
251         } catch (final Error error) {
252             connManager.shutdown();
253             throw error;
254         }
255     }
256 
257 }