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  package org.apache.http.impl.conn;
28  
29  import java.io.IOException;
30  import java.net.ConnectException;
31  import java.net.NoRouteToHostException;
32  import java.net.InetAddress;
33  import java.net.InetSocketAddress;
34  import java.net.Socket;
35  import java.net.SocketTimeoutException;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.apache.http.HttpHost;
40  import org.apache.http.annotation.Immutable;
41  import org.apache.http.client.protocol.HttpClientContext;
42  import org.apache.http.config.Lookup;
43  import org.apache.http.config.SocketConfig;
44  import org.apache.http.conn.ConnectTimeoutException;
45  import org.apache.http.conn.DnsResolver;
46  import org.apache.http.conn.HttpClientConnectionOperator;
47  import org.apache.http.conn.HttpHostConnectException;
48  import org.apache.http.conn.ManagedHttpClientConnection;
49  import org.apache.http.conn.SchemePortResolver;
50  import org.apache.http.conn.UnsupportedSchemeException;
51  import org.apache.http.conn.socket.ConnectionSocketFactory;
52  import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
53  import org.apache.http.protocol.HttpContext;
54  import org.apache.http.util.Args;
55  
56  /**
57   * Default implementation of {@link HttpClientConnectionOperator} used as default in Http client,
58   * when no instance provided by user to {@link BasicHttpClientConnectionManager} or {@link
59   * PoolingHttpClientConnectionManager} constructor.
60   *
61   * @since 4.4
62   */
63  @Immutable
64  public class DefaultHttpClientConnectionOperator implements HttpClientConnectionOperator {
65  
66      static final String SOCKET_FACTORY_REGISTRY = "http.socket-factory-registry";
67  
68      private final Log log = LogFactory.getLog(getClass());
69  
70      private final Lookup<ConnectionSocketFactory> socketFactoryRegistry;
71      private final SchemePortResolver schemePortResolver;
72      private final DnsResolver dnsResolver;
73  
74      public DefaultHttpClientConnectionOperator(
75              final Lookup<ConnectionSocketFactory> socketFactoryRegistry,
76              final SchemePortResolver schemePortResolver,
77              final DnsResolver dnsResolver) {
78          super();
79          Args.notNull(socketFactoryRegistry, "Socket factory registry");
80          this.socketFactoryRegistry = socketFactoryRegistry;
81          this.schemePortResolver = schemePortResolver != null ? schemePortResolver :
82              DefaultSchemePortResolver.INSTANCE;
83          this.dnsResolver = dnsResolver != null ? dnsResolver :
84              SystemDefaultDnsResolver.INSTANCE;
85      }
86  
87      @SuppressWarnings("unchecked")
88      private Lookup<ConnectionSocketFactory> getSocketFactoryRegistry(final HttpContext context) {
89          Lookup<ConnectionSocketFactory> reg = (Lookup<ConnectionSocketFactory>) context.getAttribute(
90                  SOCKET_FACTORY_REGISTRY);
91          if (reg == null) {
92              reg = this.socketFactoryRegistry;
93          }
94          return reg;
95      }
96  
97      @Override
98      public void connect(
99              final ManagedHttpClientConnection conn,
100             final HttpHost host,
101             final InetSocketAddress localAddress,
102             final int connectTimeout,
103             final SocketConfig socketConfig,
104             final HttpContext context) throws IOException {
105         final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
106         final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
107         if (sf == null) {
108             throw new UnsupportedSchemeException(host.getSchemeName() +
109                     " protocol is not supported");
110         }
111         final InetAddress[] addresses = host.getAddress() != null ?
112                 new InetAddress[] { host.getAddress() } : this.dnsResolver.resolve(host.getHostName());
113         final int port = this.schemePortResolver.resolve(host);
114         for (int i = 0; i < addresses.length; i++) {
115             final InetAddress address = addresses[i];
116             final boolean last = i == addresses.length - 1;
117 
118             Socket sock = sf.createSocket(context);
119             sock.setSoTimeout(socketConfig.getSoTimeout());
120             sock.setReuseAddress(socketConfig.isSoReuseAddress());
121             sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
122             sock.setKeepAlive(socketConfig.isSoKeepAlive());
123             final int linger = socketConfig.getSoLinger();
124             if (linger >= 0) {
125                 sock.setSoLinger(true, linger);
126             }
127             conn.bind(sock);
128 
129             final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
130             if (this.log.isDebugEnabled()) {
131                 this.log.debug("Connecting to " + remoteAddress);
132             }
133             try {
134                 sock = sf.connectSocket(
135                         connectTimeout, sock, host, remoteAddress, localAddress, context);
136                 conn.bind(sock);
137                 if (this.log.isDebugEnabled()) {
138                     this.log.debug("Connection established " + conn);
139                 }
140                 return;
141             } catch (final SocketTimeoutException ex) {
142                 if (last) {
143                     throw new ConnectTimeoutException(ex, host, addresses);
144                 }
145             } catch (final ConnectException ex) {
146                 if (last) {
147                     final String msg = ex.getMessage();
148                     if ("Connection timed out".equals(msg)) {
149                         throw new ConnectTimeoutException(ex, host, addresses);
150                     } else {
151                         throw new HttpHostConnectException(ex, host, addresses);
152                     }
153                 }
154             } catch (final NoRouteToHostException ex) {
155                 if (last) {
156                     throw ex;
157                 }
158             }
159             if (this.log.isDebugEnabled()) {
160                 this.log.debug("Connect to " + remoteAddress + " timed out. " +
161                         "Connection will be retried using another IP address");
162             }
163         }
164     }
165 
166     @Override
167     public void upgrade(
168             final ManagedHttpClientConnection conn,
169             final HttpHost host,
170             final HttpContext context) throws IOException {
171         final HttpClientContext clientContext = HttpClientContext.adapt(context);
172         final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(clientContext);
173         final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
174         if (sf == null) {
175             throw new UnsupportedSchemeException(host.getSchemeName() +
176                     " protocol is not supported");
177         }
178         if (!(sf instanceof LayeredConnectionSocketFactory)) {
179             throw new UnsupportedSchemeException(host.getSchemeName() +
180                     " protocol does not support connection upgrade");
181         }
182         final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf;
183         Socket sock = conn.getSocket();
184         final int port = this.schemePortResolver.resolve(host);
185         sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context);
186         conn.bind(sock);
187     }
188 
189 }