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