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   * </p>
69   *
70   * @since 4.3
71   */
72  @Immutable
73  @SuppressWarnings("deprecation")
74  public class ProtocolExec implements ClientExecChain {
75  
76      private final Log log = LogFactory.getLog(getClass());
77  
78      private final ClientExecChain requestExecutor;
79      private final HttpProcessor httpProcessor;
80  
81      public ProtocolExec(final ClientExecChain requestExecutor, final HttpProcessor httpProcessor) {
82          Args.notNull(requestExecutor, "HTTP client request executor");
83          Args.notNull(httpProcessor, "HTTP protocol processor");
84          this.requestExecutor = requestExecutor;
85          this.httpProcessor = httpProcessor;
86      }
87  
88      void rewriteRequestURI(
89              final HttpRequestWrapper request,
90              final HttpRoute route) throws ProtocolException {
91          final URI uri = request.getURI();
92          if (uri != null) {
93              try {
94                  request.setURI(URIUtils.rewriteURIForRoute(uri, route));
95              } catch (final URISyntaxException ex) {
96                  throw new ProtocolException("Invalid URI: " + uri, ex);
97              }
98          }
99      }
100 
101     @Override
102     public CloseableHttpResponse execute(
103             final HttpRoute route,
104             final HttpRequestWrapper request,
105             final HttpClientContext context,
106             final HttpExecutionAware execAware) throws IOException,
107         HttpException {
108         Args.notNull(route, "HTTP route");
109         Args.notNull(request, "HTTP request");
110         Args.notNull(context, "HTTP context");
111 
112         final HttpRequest original = request.getOriginal();
113         URI uri = null;
114         if (original instanceof HttpUriRequest) {
115             uri = ((HttpUriRequest) original).getURI();
116         } else {
117             final String uriString = original.getRequestLine().getUri();
118             try {
119                 uri = URI.create(uriString);
120             } catch (final IllegalArgumentException ex) {
121                 if (this.log.isDebugEnabled()) {
122                     this.log.debug("Unable to parse '" + uriString + "' as a valid URI; " +
123                         "request URI and Host header may be inconsistent", ex);
124                 }
125             }
126 
127         }
128         request.setURI(uri);
129 
130         // Re-write request URI if needed
131         rewriteRequestURI(request, route);
132 
133         final HttpParams params = request.getParams();
134         HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST);
135         // HTTPCLIENT-1092 - add the port if necessary
136         if (virtualHost != null && virtualHost.getPort() == -1) {
137             final int port = route.getTargetHost().getPort();
138             if (port != -1) {
139                 virtualHost = new HttpHost(virtualHost.getHostName(), port,
140                     virtualHost.getSchemeName());
141             }
142             if (this.log.isDebugEnabled()) {
143                 this.log.debug("Using virtual host" + virtualHost);
144             }
145         }
146 
147         HttpHost target = null;
148         if (virtualHost != null) {
149             target = virtualHost;
150         } else {
151             if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
152                 target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
153             }
154         }
155         if (target == null) {
156             target = request.getTarget();
157         }
158         if (target == null) {
159             target = route.getTargetHost();
160         }
161 
162         // Get user info from the URI
163         if (uri != null) {
164             final String userinfo = uri.getUserInfo();
165             if (userinfo != null) {
166                 CredentialsProvider credsProvider = context.getCredentialsProvider();
167                 if (credsProvider == null) {
168                     credsProvider = new BasicCredentialsProvider();
169                     context.setCredentialsProvider(credsProvider);
170                 }
171                 credsProvider.setCredentials(
172                         new AuthScope(target),
173                         new UsernamePasswordCredentials(userinfo));
174             }
175         }
176 
177         // Run request protocol interceptors
178         context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
179         context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
180         context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
181 
182         this.httpProcessor.process(request, context);
183 
184         final CloseableHttpResponse response = this.requestExecutor.execute(route, request,
185             context, execAware);
186         try {
187             // Run response protocol interceptors
188             context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
189             this.httpProcessor.process(response, context);
190             return response;
191         } catch (final RuntimeException ex) {
192             response.close();
193             throw ex;
194         } catch (final IOException ex) {
195             response.close();
196             throw ex;
197         } catch (final HttpException ex) {
198             response.close();
199             throw ex;
200         }
201     }
202 
203 }