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.conn;
29  
30  import java.io.IOException;
31  import java.net.ConnectException;
32  import java.net.InetAddress;
33  import java.net.InetSocketAddress;
34  import java.net.Socket;
35  import java.net.UnknownHostException;
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.ThreadSafe;
41  import org.apache.http.client.protocol.ClientContext;
42  import org.apache.http.conn.ClientConnectionOperator;
43  import org.apache.http.conn.ConnectTimeoutException;
44  import org.apache.http.conn.DnsResolver;
45  import org.apache.http.conn.HttpInetSocketAddress;
46  import org.apache.http.conn.OperatedClientConnection;
47  import org.apache.http.conn.scheme.Scheme;
48  import org.apache.http.conn.scheme.SchemeLayeredSocketFactory;
49  import org.apache.http.conn.scheme.SchemeRegistry;
50  import org.apache.http.conn.scheme.SchemeSocketFactory;
51  import org.apache.http.params.HttpConnectionParams;
52  import org.apache.http.params.HttpParams;
53  import org.apache.http.protocol.HttpContext;
54  import org.apache.http.util.Args;
55  import org.apache.http.util.Asserts;
56  
57  /**
58   * Default implementation of a {@link ClientConnectionOperator}. It uses a {@link SchemeRegistry}
59   * to look up {@link SchemeSocketFactory} objects.
60   * <p>
61   * This connection operator is multihome network aware and will attempt to retry failed connects
62   * against all known IP addresses sequentially until the connect is successful or all known
63   * addresses fail to respond. Please note the same
64   * {@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT} value will be used
65   * for each connection attempt, so in the worst case the total elapsed time before timeout
66   * can be {@code CONNECTION_TIMEOUT * n} where {@code n} is the number of IP addresses
67   * of the given host. One can disable multihome support by overriding
68   * the {@link #resolveHostname(String)} method and returning only one IP address for the given
69   * host name.
70   * <p>
71   * The following parameters can be used to customize the behavior of this
72   * class:
73   * <ul>
74   *  <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
75   *  <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
76   *  <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
77   *  <li>{@link org.apache.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
78   *  <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
79   *  <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
80   *  <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
81   *  <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
82   * </ul>
83   *
84   * @since 4.0
85   *
86   * @deprecated (4.3) use {@link PoolingHttpClientConnectionManager}.
87   */
88  @Deprecated
89  @ThreadSafe
90  public class DefaultClientConnectionOperator implements ClientConnectionOperator {
91  
92      private final Log log = LogFactory.getLog(getClass());
93  
94      /** The scheme registry for looking up socket factories. */
95      protected final SchemeRegistry schemeRegistry; // @ThreadSafe
96  
97      /** the custom-configured DNS lookup mechanism. */
98      protected final DnsResolver dnsResolver;
99  
100     /**
101      * Creates a new client connection operator for the given scheme registry.
102      *
103      * @param schemes   the scheme registry
104      *
105      * @since 4.2
106      */
107     public DefaultClientConnectionOperator(final SchemeRegistry schemes) {
108         Args.notNull(schemes, "Scheme registry");
109         this.schemeRegistry = schemes;
110         this.dnsResolver = new SystemDefaultDnsResolver();
111     }
112 
113     /**
114     * Creates a new client connection operator for the given scheme registry
115     * and the given custom DNS lookup mechanism.
116     *
117     * @param schemes
118     *            the scheme registry
119     * @param dnsResolver
120     *            the custom DNS lookup mechanism
121     */
122     public DefaultClientConnectionOperator(final SchemeRegistry schemes,final DnsResolver dnsResolver) {
123         Args.notNull(schemes, "Scheme registry");
124 
125         Args.notNull(dnsResolver, "DNS resolver");
126 
127         this.schemeRegistry = schemes;
128         this.dnsResolver = dnsResolver;
129     }
130 
131     @Override
132     public OperatedClientConnection createConnection() {
133         return new DefaultClientConnection();
134     }
135 
136     private SchemeRegistry getSchemeRegistry(final HttpContext context) {
137         SchemeRegistry reg = (SchemeRegistry) context.getAttribute(
138                 ClientContext.SCHEME_REGISTRY);
139         if (reg == null) {
140             reg = this.schemeRegistry;
141         }
142         return reg;
143     }
144 
145     @Override
146     public void openConnection(
147             final OperatedClientConnection conn,
148             final HttpHost target,
149             final InetAddress local,
150             final HttpContext context,
151             final HttpParams params) throws IOException {
152         Args.notNull(conn, "Connection");
153         Args.notNull(target, "Target host");
154         Args.notNull(params, "HTTP parameters");
155         Asserts.check(!conn.isOpen(), "Connection must not be open");
156 
157         final SchemeRegistry registry = getSchemeRegistry(context);
158         final Scheme schm = registry.getScheme(target.getSchemeName());
159         final SchemeSocketFactory sf = schm.getSchemeSocketFactory();
160 
161         final InetAddress[] addresses = resolveHostname(target.getHostName());
162         final int port = schm.resolvePort(target.getPort());
163         for (int i = 0; i < addresses.length; i++) {
164             final InetAddress address = addresses[i];
165             final boolean last = i == addresses.length - 1;
166 
167             Socket sock = sf.createSocket(params);
168             conn.opening(sock, target);
169 
170             final InetSocketAddress remoteAddress = new HttpInetSocketAddress(target, address, port);
171             InetSocketAddress localAddress = null;
172             if (local != null) {
173                 localAddress = new InetSocketAddress(local, 0);
174             }
175             if (this.log.isDebugEnabled()) {
176                 this.log.debug("Connecting to " + remoteAddress);
177             }
178             try {
179                 final Socket connsock = sf.connectSocket(sock, remoteAddress, localAddress, params);
180                 if (sock != connsock) {
181                     sock = connsock;
182                     conn.opening(sock, target);
183                 }
184                 prepareSocket(sock, context, params);
185                 conn.openCompleted(sf.isSecure(sock), params);
186                 return;
187             } catch (final ConnectException ex) {
188                 if (last) {
189                     throw ex;
190                 }
191             } catch (final ConnectTimeoutException ex) {
192                 if (last) {
193                     throw ex;
194                 }
195             }
196             if (this.log.isDebugEnabled()) {
197                 this.log.debug("Connect to " + remoteAddress + " timed out. " +
198                         "Connection will be retried using another IP address");
199             }
200         }
201     }
202 
203     @Override
204     public void updateSecureConnection(
205             final OperatedClientConnection conn,
206             final HttpHost target,
207             final HttpContext context,
208             final HttpParams params) throws IOException {
209         Args.notNull(conn, "Connection");
210         Args.notNull(target, "Target host");
211         Args.notNull(params, "Parameters");
212         Asserts.check(conn.isOpen(), "Connection must be open");
213 
214         final SchemeRegistry registry = getSchemeRegistry(context);
215         final Scheme schm = registry.getScheme(target.getSchemeName());
216         Asserts.check(schm.getSchemeSocketFactory() instanceof SchemeLayeredSocketFactory,
217             "Socket factory must implement SchemeLayeredSocketFactory");
218         final SchemeLayeredSocketFactory lsf = (SchemeLayeredSocketFactory) schm.getSchemeSocketFactory();
219         final Socket sock = lsf.createLayeredSocket(
220                 conn.getSocket(), target.getHostName(), schm.resolvePort(target.getPort()), params);
221         prepareSocket(sock, context, params);
222         conn.update(sock, target, lsf.isSecure(sock), params);
223     }
224 
225     /**
226      * Performs standard initializations on a newly created socket.
227      *
228      * @param sock      the socket to prepare
229      * @param context   the context for the connection
230      * @param params    the parameters from which to prepare the socket
231      *
232      * @throws IOException      in case of an IO problem
233      */
234     protected void prepareSocket(
235             final Socket sock,
236             final HttpContext context,
237             final HttpParams params) throws IOException {
238         sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
239         sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
240 
241         final int linger = HttpConnectionParams.getLinger(params);
242         if (linger >= 0) {
243             sock.setSoLinger(linger > 0, linger);
244         }
245     }
246 
247     /**
248      * Resolves the given host name to an array of corresponding IP addresses, based on the
249      * configured name service on the provided DNS resolver. If one wasn't provided, the system
250      * configuration is used.
251      *
252      * @param host host name to resolve
253      * @return array of IP addresses
254      * @exception  UnknownHostException  if no IP address for the host could be determined.
255      *
256      * @see DnsResolver
257      * @see SystemDefaultDnsResolver
258      *
259      * @since 4.1
260      */
261     protected InetAddress[] resolveHostname(final String host) throws UnknownHostException {
262             return dnsResolver.resolve(host);
263     }
264 
265 }
266