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