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.net.URI;
32  import java.net.URISyntaxException;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.http.HttpException;
37  import org.apache.http.HttpHost;
38  import org.apache.http.HttpRequest;
39  import org.apache.http.ProtocolException;
40  import org.apache.http.annotation.Contract;
41  import org.apache.http.annotation.ThreadingBehavior;
42  import org.apache.http.auth.AuthScope;
43  import org.apache.http.auth.UsernamePasswordCredentials;
44  import org.apache.http.client.CredentialsProvider;
45  import org.apache.http.client.methods.CloseableHttpResponse;
46  import org.apache.http.client.methods.HttpExecutionAware;
47  import org.apache.http.client.methods.HttpRequestWrapper;
48  import org.apache.http.client.methods.HttpUriRequest;
49  import org.apache.http.client.params.ClientPNames;
50  import org.apache.http.client.protocol.HttpClientContext;
51  import org.apache.http.client.utils.URIUtils;
52  import org.apache.http.conn.routing.HttpRoute;
53  import org.apache.http.impl.client.BasicCredentialsProvider;
54  import org.apache.http.params.HttpParams;
55  import org.apache.http.protocol.HttpCoreContext;
56  import org.apache.http.protocol.HttpProcessor;
57  import org.apache.http.util.Args;
58  
59  /**
60   * Request executor in the request execution chain that is responsible
61   * for implementation of HTTP specification requirements.
62   * Internally this executor relies on a {@link HttpProcessor} to populate
63   * requisite HTTP request headers, process HTTP response headers and update
64   * session state in {@link HttpClientContext}.
65   * <p>
66   * Further responsibilities such as communication with the opposite
67   * endpoint is delegated to the next executor in the request execution
68   * chain.
69   * </p>
70   *
71   * @since 4.3
72   */
73  @Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL)
74  @SuppressWarnings("deprecation")
75  public class ProtocolExec implements ClientExecChain {
76  
77      private final Log log = LogFactory.getLog(getClass());
78  
79      private final ClientExecChain requestExecutor;
80      private final HttpProcessor httpProcessor;
81  
82      public ProtocolExec(final ClientExecChain requestExecutor, final HttpProcessor httpProcessor) {
83          Args.notNull(requestExecutor, "HTTP client request executor");
84          Args.notNull(httpProcessor, "HTTP protocol processor");
85          this.requestExecutor = requestExecutor;
86          this.httpProcessor = httpProcessor;
87      }
88  
89      void rewriteRequestURI(
90              final HttpRequestWrapper request,
91              final HttpRoute route) throws ProtocolException {
92          final URI uri = request.getURI();
93          if (uri != null) {
94              try {
95                  request.setURI(URIUtils.rewriteURIForRoute(uri, route));
96              } catch (final URISyntaxException ex) {
97                  throw new ProtocolException("Invalid URI: " + uri, ex);
98              }
99          }
100     }
101 
102     @Override
103     public CloseableHttpResponse execute(
104             final HttpRoute route,
105             final HttpRequestWrapper request,
106             final HttpClientContext context,
107             final HttpExecutionAware execAware) throws IOException,
108         HttpException {
109         Args.notNull(route, "HTTP route");
110         Args.notNull(request, "HTTP request");
111         Args.notNull(context, "HTTP context");
112 
113         final HttpRequest original = request.getOriginal();
114         URI uri = null;
115         if (original instanceof HttpUriRequest) {
116             uri = ((HttpUriRequest) original).getURI();
117         } else {
118             final String uriString = original.getRequestLine().getUri();
119             try {
120                 uri = URI.create(uriString);
121             } catch (final IllegalArgumentException ex) {
122                 if (this.log.isDebugEnabled()) {
123                     this.log.debug("Unable to parse '" + uriString + "' as a valid URI; " +
124                         "request URI and Host header may be inconsistent", ex);
125                 }
126             }
127 
128         }
129         request.setURI(uri);
130 
131         // Re-write request URI if needed
132         rewriteRequestURI(request, route);
133 
134         final HttpParams params = request.getParams();
135         HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST);
136         // HTTPCLIENT-1092 - add the port if necessary
137         if (virtualHost != null && virtualHost.getPort() == -1) {
138             final int port = route.getTargetHost().getPort();
139             if (port != -1) {
140                 virtualHost = new HttpHost(virtualHost.getHostName(), port,
141                     virtualHost.getSchemeName());
142             }
143             if (this.log.isDebugEnabled()) {
144                 this.log.debug("Using virtual host" + virtualHost);
145             }
146         }
147 
148         HttpHost target = null;
149         if (virtualHost != null) {
150             target = virtualHost;
151         } else {
152             if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
153                 target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
154             }
155         }
156         if (target == null) {
157             target = request.getTarget();
158         }
159         if (target == null) {
160             target = route.getTargetHost();
161         }
162 
163         // Get user info from the URI
164         if (uri != null) {
165             final String userinfo = uri.getUserInfo();
166             if (userinfo != null) {
167                 CredentialsProvider credsProvider = context.getCredentialsProvider();
168                 if (credsProvider == null) {
169                     credsProvider = new BasicCredentialsProvider();
170                     context.setCredentialsProvider(credsProvider);
171                 }
172                 credsProvider.setCredentials(
173                         new AuthScope(target),
174                         new UsernamePasswordCredentials(userinfo));
175             }
176         }
177 
178         // Run request protocol interceptors
179         context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
180         context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
181         context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
182 
183         this.httpProcessor.process(request, context);
184 
185         final CloseableHttpResponse response = this.requestExecutor.execute(route, request,
186             context, execAware);
187         try {
188             // Run response protocol interceptors
189             context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
190             this.httpProcessor.process(response, context);
191             return response;
192         } catch (final RuntimeException ex) {
193             response.close();
194             throw ex;
195         } catch (final IOException ex) {
196             response.close();
197             throw ex;
198         } catch (final HttpException ex) {
199             response.close();
200             throw ex;
201         }
202     }
203 
204 }