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     @Override
117     public CloseableHttpResponse execute(
118             final HttpRoute route,
119             final HttpRequestWrapper request,
120             final HttpClientContext context,
121             final HttpExecutionAware execAware) throws IOException,
122         HttpException {
123         Args.notNull(route, "HTTP route");
124         Args.notNull(request, "HTTP request");
125         Args.notNull(context, "HTTP context");
126 
127         final HttpRequest original = request.getOriginal();
128         URI uri = null;
129         if (original instanceof HttpUriRequest) {
130             uri = ((HttpUriRequest) original).getURI();
131         } else {
132             final String uriString = original.getRequestLine().getUri();
133             try {
134                 uri = URI.create(uriString);
135             } catch (final IllegalArgumentException ex) {
136                 if (this.log.isDebugEnabled()) {
137                     this.log.debug("Unable to parse '" + uriString + "' as a valid URI; " +
138                         "request URI and Host header may be inconsistent", ex);
139                 }
140             }
141 
142         }
143         request.setURI(uri);
144 
145         // Re-write request URI if needed
146         rewriteRequestURI(request, route);
147 
148         final HttpParams params = request.getParams();
149         HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST);
150         // HTTPCLIENT-1092 - add the port if necessary
151         if (virtualHost != null && virtualHost.getPort() == -1) {
152             final int port = route.getTargetHost().getPort();
153             if (port != -1) {
154                 virtualHost = new HttpHost(virtualHost.getHostName(), port,
155                     virtualHost.getSchemeName());
156             }
157             if (this.log.isDebugEnabled()) {
158                 this.log.debug("Using virtual host" + virtualHost);
159             }
160         }
161 
162         HttpHost target = null;
163         if (virtualHost != null) {
164             target = virtualHost;
165         } else {
166             if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
167                 target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
168             }
169         }
170         if (target == null) {
171             target = request.getTarget();
172         }
173         if (target == null) {
174             target = route.getTargetHost();
175         }
176 
177         // Get user info from the URI
178         if (uri != null) {
179             final String userinfo = uri.getUserInfo();
180             if (userinfo != null) {
181                 CredentialsProvider credsProvider = context.getCredentialsProvider();
182                 if (credsProvider == null) {
183                     credsProvider = new BasicCredentialsProvider();
184                     context.setCredentialsProvider(credsProvider);
185                 }
186                 credsProvider.setCredentials(
187                         new AuthScope(target),
188                         new UsernamePasswordCredentials(userinfo));
189             }
190         }
191 
192         // Run request protocol interceptors
193         context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
194         context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
195         context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
196 
197         this.httpProcessor.process(request, context);
198 
199         final CloseableHttpResponse response = this.requestExecutor.execute(route, request,
200             context, execAware);
201         try {
202             // Run response protocol interceptors
203             context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
204             this.httpProcessor.process(response, context);
205             return response;
206         } catch (final RuntimeException ex) {
207             response.close();
208             throw ex;
209         } catch (final IOException ex) {
210             response.close();
211             throw ex;
212         } catch (final HttpException ex) {
213             response.close();
214             throw ex;
215         }
216     }
217 
218 }