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.NoRouteToHostException;
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             if (socketConfig.getRcvBufSize() > 0) {
124                 sock.setReceiveBufferSize(socketConfig.getRcvBufSize());
125             }
126             if (socketConfig.getSndBufSize() > 0) {
127                 sock.setSendBufferSize(socketConfig.getSndBufSize());
128             }
129 
130             final int linger = socketConfig.getSoLinger();
131             if (linger >= 0) {
132                 sock.setSoLinger(true, linger);
133             }
134             conn.bind(sock);
135 
136             final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
137             if (this.log.isDebugEnabled()) {
138                 this.log.debug("Connecting to " + remoteAddress);
139             }
140             try {
141                 sock = sf.connectSocket(
142                         connectTimeout, sock, host, remoteAddress, localAddress, context);
143                 conn.bind(sock);
144                 if (this.log.isDebugEnabled()) {
145                     this.log.debug("Connection established " + conn);
146                 }
147                 return;
148             } catch (final SocketTimeoutException ex) {
149                 if (last) {
150                     throw new ConnectTimeoutException(ex, host, addresses);
151                 }
152             } catch (final ConnectException ex) {
153                 if (last) {
154                     final String msg = ex.getMessage();
155                     if ("Connection timed out".equals(msg)) {
156                         throw new ConnectTimeoutException(ex, host, addresses);
157                     } else {
158                         throw new HttpHostConnectException(ex, host, addresses);
159                     }
160                 }
161             } catch (final NoRouteToHostException ex) {
162                 if (last) {
163                     throw ex;
164                 }
165             }
166             if (this.log.isDebugEnabled()) {
167                 this.log.debug("Connect to " + remoteAddress + " timed out. " +
168                         "Connection will be retried using another IP address");
169             }
170         }
171     }
172 
173     @Override
174     public void upgrade(
175             final ManagedHttpClientConnection conn,
176             final HttpHost host,
177             final HttpContext context) throws IOException {
178         final HttpClientContext clientContext = HttpClientContext.adapt(context);
179         final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(clientContext);
180         final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
181         if (sf == null) {
182             throw new UnsupportedSchemeException(host.getSchemeName() +
183                     " protocol is not supported");
184         }
185         if (!(sf instanceof LayeredConnectionSocketFactory)) {
186             throw new UnsupportedSchemeException(host.getSchemeName() +
187                     " protocol does not support connection upgrade");
188         }
189         final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf;
190         Socket sock = conn.getSocket();
191         final int port = this.schemePortResolver.resolve(host);
192         sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context);
193         conn.bind(sock);
194     }
195 
196 }