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</code> where <code>n</code> 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     public OperatedClientConnection createConnection() {
132         return new DefaultClientConnection();
133     }
134 
135     private SchemeRegistry getSchemeRegistry(final HttpContext context) {
136         SchemeRegistry reg = (SchemeRegistry) context.getAttribute(
137                 ClientContext.SCHEME_REGISTRY);
138         if (reg == null) {
139             reg = this.schemeRegistry;
140         }
141         return reg;
142     }
143 
144     public void openConnection(
145             final OperatedClientConnection conn,
146             final HttpHost target,
147             final InetAddress local,
148             final HttpContext context,
149             final HttpParams params) throws IOException {
150         Args.notNull(conn, "Connection");
151         Args.notNull(target, "Target host");
152         Args.notNull(params, "HTTP parameters");
153         Asserts.check(!conn.isOpen(), "Connection must not be open");
154 
155         final SchemeRegistry registry = getSchemeRegistry(context);
156         final Scheme schm = registry.getScheme(target.getSchemeName());
157         final SchemeSocketFactory sf = schm.getSchemeSocketFactory();
158 
159         final InetAddress[] addresses = resolveHostname(target.getHostName());
160         final int port = schm.resolvePort(target.getPort());
161         for (int i = 0; i < addresses.length; i++) {
162             final InetAddress address = addresses[i];
163             final boolean last = i == addresses.length - 1;
164 
165             Socket sock = sf.createSocket(params);
166             conn.opening(sock, target);
167 
168             final InetSocketAddress remoteAddress = new HttpInetSocketAddress(target, address, port);
169             InetSocketAddress localAddress = null;
170             if (local != null) {
171                 localAddress = new InetSocketAddress(local, 0);
172             }
173             if (this.log.isDebugEnabled()) {
174                 this.log.debug("Connecting to " + remoteAddress);
175             }
176             try {
177                 final Socket connsock = sf.connectSocket(sock, remoteAddress, localAddress, params);
178                 if (sock != connsock) {
179                     sock = connsock;
180                     conn.opening(sock, target);
181                 }
182                 prepareSocket(sock, context, params);
183                 conn.openCompleted(sf.isSecure(sock), params);
184                 return;
185             } catch (final ConnectException ex) {
186                 if (last) {
187                     throw ex;
188                 }
189             } catch (final ConnectTimeoutException ex) {
190                 if (last) {
191                     throw ex;
192                 }
193             }
194             if (this.log.isDebugEnabled()) {
195                 this.log.debug("Connect to " + remoteAddress + " timed out. " +
196                         "Connection will be retried using another IP address");
197             }
198         }
199     }
200 
201     public void updateSecureConnection(
202             final OperatedClientConnection conn,
203             final HttpHost target,
204             final HttpContext context,
205             final HttpParams params) throws IOException {
206         Args.notNull(conn, "Connection");
207         Args.notNull(target, "Target host");
208         Args.notNull(params, "Parameters");
209         Asserts.check(conn.isOpen(), "Connection must be open");
210 
211         final SchemeRegistry registry = getSchemeRegistry(context);
212         final Scheme schm = registry.getScheme(target.getSchemeName());
213         Asserts.check(schm.getSchemeSocketFactory() instanceof SchemeLayeredSocketFactory,
214             "Socket factory must implement SchemeLayeredSocketFactory");
215         final SchemeLayeredSocketFactory lsf = (SchemeLayeredSocketFactory) schm.getSchemeSocketFactory();
216         final Socket sock = lsf.createLayeredSocket(
217                 conn.getSocket(), target.getHostName(), schm.resolvePort(target.getPort()), params);
218         prepareSocket(sock, context, params);
219         conn.update(sock, target, lsf.isSecure(sock), params);
220     }
221 
222     /**
223      * Performs standard initializations on a newly created socket.
224      *
225      * @param sock      the socket to prepare
226      * @param context   the context for the connection
227      * @param params    the parameters from which to prepare the socket
228      *
229      * @throws IOException      in case of an IO problem
230      */
231     protected void prepareSocket(
232             final Socket sock,
233             final HttpContext context,
234             final HttpParams params) throws IOException {
235         sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
236         sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
237 
238         final int linger = HttpConnectionParams.getLinger(params);
239         if (linger >= 0) {
240             sock.setSoLinger(linger > 0, linger);
241         }
242     }
243 
244     /**
245      * Resolves the given host name to an array of corresponding IP addresses, based on the
246      * configured name service on the provided DNS resolver. If one wasn't provided, the system
247      * configuration is used.
248      *
249      * @param host host name to resolve
250      * @return array of IP addresses
251      * @exception  UnknownHostException  if no IP address for the host could be determined.
252      *
253      * @see DnsResolver
254      * @see SystemDefaultDnsResolver
255      *
256      * @since 4.1
257      */
258     protected InetAddress[] resolveHostname(final String host) throws UnknownHostException {
259             return dnsResolver.resolve(host);
260     }
261 
262 }
263