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.Closeable;
31  import java.io.IOException;
32  import java.net.InetSocketAddress;
33  import java.util.Date;
34  import java.util.concurrent.TimeUnit;
35  import java.util.concurrent.atomic.AtomicBoolean;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.apache.http.HttpClientConnection;
40  import org.apache.http.HttpHost;
41  import org.apache.http.annotation.Contract;
42  import org.apache.http.annotation.ThreadingBehavior;
43  import org.apache.http.config.ConnectionConfig;
44  import org.apache.http.config.Lookup;
45  import org.apache.http.config.Registry;
46  import org.apache.http.config.RegistryBuilder;
47  import org.apache.http.config.SocketConfig;
48  import org.apache.http.conn.ConnectionRequest;
49  import org.apache.http.conn.DnsResolver;
50  import org.apache.http.conn.HttpClientConnectionManager;
51  import org.apache.http.conn.HttpClientConnectionOperator;
52  import org.apache.http.conn.HttpConnectionFactory;
53  import org.apache.http.conn.ManagedHttpClientConnection;
54  import org.apache.http.conn.SchemePortResolver;
55  import org.apache.http.conn.routing.HttpRoute;
56  import org.apache.http.conn.socket.ConnectionSocketFactory;
57  import org.apache.http.conn.socket.PlainConnectionSocketFactory;
58  import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
59  import org.apache.http.protocol.HttpContext;
60  import org.apache.http.util.Args;
61  import org.apache.http.util.Asserts;
62  import org.apache.http.util.LangUtils;
63  
64  /**
65   * A connection manager for a single connection. This connection manager maintains only one active
66   * connection. Even though this class is fully thread-safe it ought to be used by one execution
67   * thread only, as only one thread a time can lease the connection at a time.
68   * <p>
69   * This connection manager will make an effort to reuse the connection for subsequent requests
70   * with the same {@link HttpRoute route}. It will, however, close the existing connection and
71   * open it for the given route, if the route of the persistent connection does not match that
72   * of the connection request. If the connection has been already been allocated
73   * {@link IllegalStateException} is thrown.
74   * </p>
75   * <p>
76   * This connection manager implementation should be used inside an EJB container instead of
77   * {@link PoolingHttpClientConnectionManager}.
78   * </p>
79   *
80   * @since 4.3
81   */
82  @Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
83  public class BasicHttpClientConnectionManager implements HttpClientConnectionManager, Closeable {
84  
85      private final Log log = LogFactory.getLog(getClass());
86  
87      private final HttpClientConnectionOperator connectionOperator;
88      private final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory;
89  
90      private ManagedHttpClientConnection conn;
91      private HttpRoute route;
92      private Object state;
93      private long updated;
94      private long expiry;
95      private boolean leased;
96      private SocketConfig socketConfig;
97      private ConnectionConfig connConfig;
98  
99      private final AtomicBoolean isShutdown;
100 
101     private static Registry<ConnectionSocketFactory> getDefaultRegistry() {
102         return RegistryBuilder.<ConnectionSocketFactory>create()
103                 .register("http", PlainConnectionSocketFactory.getSocketFactory())
104                 .register("https", SSLConnectionSocketFactory.getSocketFactory())
105                 .build();
106     }
107 
108     public BasicHttpClientConnectionManager(
109         final Lookup<ConnectionSocketFactory> socketFactoryRegistry,
110         final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory,
111         final SchemePortResolver schemePortResolver,
112         final DnsResolver dnsResolver) {
113       this(
114           new DefaultHttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver),
115           connFactory
116       );
117     }
118 
119     /**
120      * @since 4.4
121      */
122     public BasicHttpClientConnectionManager(
123             final HttpClientConnectionOperator httpClientConnectionOperator,
124             final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory) {
125         super();
126         this.connectionOperator = Args.notNull(httpClientConnectionOperator, "Connection operator");
127         this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE;
128         this.expiry = Long.MAX_VALUE;
129         this.socketConfig = SocketConfig.DEFAULT;
130         this.connConfig = ConnectionConfig.DEFAULT;
131         this.isShutdown = new AtomicBoolean(false);
132     }
133 
134     public BasicHttpClientConnectionManager(
135             final Lookup<ConnectionSocketFactory> socketFactoryRegistry,
136             final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory) {
137         this(socketFactoryRegistry, connFactory, null, null);
138     }
139 
140     public BasicHttpClientConnectionManager(
141             final Lookup<ConnectionSocketFactory> socketFactoryRegistry) {
142         this(socketFactoryRegistry, null, null, null);
143     }
144 
145     public BasicHttpClientConnectionManager() {
146         this(getDefaultRegistry(), null, null, null);
147     }
148 
149     @Override
150     protected void finalize() throws Throwable {
151         try {
152             shutdown();
153         } finally { // Make sure we call overridden method even if shutdown barfs
154             super.finalize();
155         }
156     }
157 
158     @Override
159     public void close() {
160         shutdown();
161     }
162 
163     HttpRoute getRoute() {
164         return route;
165     }
166 
167     Object getState() {
168         return state;
169     }
170 
171     public synchronized SocketConfig getSocketConfig() {
172         return socketConfig;
173     }
174 
175     public synchronized void setSocketConfig(final SocketConfig socketConfig) {
176         this.socketConfig = socketConfig != null ? socketConfig : SocketConfig.DEFAULT;
177     }
178 
179     public synchronized ConnectionConfig getConnectionConfig() {
180         return connConfig;
181     }
182 
183     public synchronized void setConnectionConfig(final ConnectionConfig connConfig) {
184         this.connConfig = connConfig != null ? connConfig : ConnectionConfig.DEFAULT;
185     }
186 
187     @Override
188     public final ConnectionRequest requestConnection(
189             final HttpRoute route,
190             final Object state) {
191         Args.notNull(route, "Route");
192         return new ConnectionRequest() {
193 
194             @Override
195             public boolean cancel() {
196                 // Nothing to abort, since requests are immediate.
197                 return false;
198             }
199 
200             @Override
201             public HttpClientConnection get(final long timeout, final TimeUnit tunit) {
202                 return BasicHttpClientConnectionManager.this.getConnection(
203                         route, state);
204             }
205 
206         };
207     }
208 
209     private void closeConnection() {
210         if (this.conn != null) {
211             this.log.debug("Closing connection");
212             try {
213                 this.conn.close();
214             } catch (final IOException iox) {
215                 if (this.log.isDebugEnabled()) {
216                     this.log.debug("I/O exception closing connection", iox);
217                 }
218             }
219             this.conn = null;
220         }
221     }
222 
223     private void shutdownConnection() {
224         if (this.conn != null) {
225             this.log.debug("Shutting down connection");
226             try {
227                 this.conn.shutdown();
228             } catch (final IOException iox) {
229                 if (this.log.isDebugEnabled()) {
230                     this.log.debug("I/O exception shutting down connection", iox);
231                 }
232             }
233             this.conn = null;
234         }
235     }
236 
237     private void checkExpiry() {
238         if (this.conn != null && System.currentTimeMillis() >= this.expiry) {
239             if (this.log.isDebugEnabled()) {
240                 this.log.debug("Connection expired @ " + new Date(this.expiry));
241             }
242             closeConnection();
243         }
244     }
245 
246     synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) {
247         Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down");
248         if (this.log.isDebugEnabled()) {
249             this.log.debug("Get connection for route " + route);
250         }
251         Asserts.check(!this.leased, "Connection is still allocated");
252         if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) {
253             closeConnection();
254         }
255         this.route = route;
256         this.state = state;
257         checkExpiry();
258         if (this.conn == null) {
259             this.conn = this.connFactory.create(route, this.connConfig);
260         }
261         this.conn.setSocketTimeout(this.socketConfig.getSoTimeout());
262         this.leased = true;
263         return this.conn;
264     }
265 
266     @Override
267     public synchronized void releaseConnection(
268             final HttpClientConnection conn,
269             final Object state,
270             final long keepalive, final TimeUnit tunit) {
271         Args.notNull(conn, "Connection");
272         Asserts.check(conn == this.conn, "Connection not obtained from this manager");
273         if (this.log.isDebugEnabled()) {
274             this.log.debug("Releasing connection " + conn);
275         }
276         if (this.isShutdown.get()) {
277             return;
278         }
279         try {
280             this.updated = System.currentTimeMillis();
281             if (!this.conn.isOpen()) {
282                 this.conn = null;
283                 this.route = null;
284                 this.conn = null;
285                 this.expiry = Long.MAX_VALUE;
286             } else {
287                 this.state = state;
288                 this.conn.setSocketTimeout(0);
289                 if (this.log.isDebugEnabled()) {
290                     final String s;
291                     if (keepalive > 0) {
292                         s = "for " + keepalive + " " + tunit;
293                     } else {
294                         s = "indefinitely";
295                     }
296                     this.log.debug("Connection can be kept alive " + s);
297                 }
298                 if (keepalive > 0) {
299                     this.expiry = this.updated + tunit.toMillis(keepalive);
300                 } else {
301                     this.expiry = Long.MAX_VALUE;
302                 }
303             }
304         } finally {
305             this.leased = false;
306         }
307     }
308 
309     @Override
310     public void connect(
311             final HttpClientConnection conn,
312             final HttpRoute route,
313             final int connectTimeout,
314             final HttpContext context) throws IOException {
315         Args.notNull(conn, "Connection");
316         Args.notNull(route, "HTTP route");
317         Asserts.check(conn == this.conn, "Connection not obtained from this manager");
318         final HttpHost host;
319         if (route.getProxyHost() != null) {
320             host = route.getProxyHost();
321         } else {
322             host = route.getTargetHost();
323         }
324         final InetSocketAddress localAddress = route.getLocalSocketAddress();
325         this.connectionOperator.connect(this.conn, host, localAddress,
326                 connectTimeout, this.socketConfig, context);
327     }
328 
329     @Override
330     public void upgrade(
331             final HttpClientConnection conn,
332             final HttpRoute route,
333             final HttpContext context) throws IOException {
334         Args.notNull(conn, "Connection");
335         Args.notNull(route, "HTTP route");
336         Asserts.check(conn == this.conn, "Connection not obtained from this manager");
337         this.connectionOperator.upgrade(this.conn, route.getTargetHost(), context);
338     }
339 
340     @Override
341     public void routeComplete(
342             final HttpClientConnection conn,
343             final HttpRoute route,
344             final HttpContext context) throws IOException {
345     }
346 
347     @Override
348     public synchronized void closeExpiredConnections() {
349         if (this.isShutdown.get()) {
350             return;
351         }
352         if (!this.leased) {
353             checkExpiry();
354         }
355     }
356 
357     @Override
358     public synchronized void closeIdleConnections(final long idletime, final TimeUnit tunit) {
359         Args.notNull(tunit, "Time unit");
360         if (this.isShutdown.get()) {
361             return;
362         }
363         if (!this.leased) {
364             long time = tunit.toMillis(idletime);
365             if (time < 0) {
366                 time = 0;
367             }
368             final long deadline = System.currentTimeMillis() - time;
369             if (this.updated <= deadline) {
370                 closeConnection();
371             }
372         }
373     }
374 
375     @Override
376     public synchronized void shutdown() {
377         if (this.isShutdown.compareAndSet(false, true)) {
378             shutdownConnection();
379         }
380     }
381 
382 }