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.util.concurrent.TimeUnit;
32  import java.util.concurrent.atomic.AtomicLong;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.http.HttpClientConnection;
37  import org.apache.http.annotation.GuardedBy;
38  import org.apache.http.annotation.ThreadSafe;
39  import org.apache.http.conn.ClientConnectionManager;
40  import org.apache.http.conn.ClientConnectionOperator;
41  import org.apache.http.conn.ClientConnectionRequest;
42  import org.apache.http.conn.ManagedClientConnection;
43  import org.apache.http.conn.OperatedClientConnection;
44  import org.apache.http.conn.routing.HttpRoute;
45  import org.apache.http.conn.scheme.SchemeRegistry;
46  import org.apache.http.util.Args;
47  import org.apache.http.util.Asserts;
48  
49  /**
50   * A connection manager for a single connection. This connection manager maintains only one active
51   * connection. Even though this class is fully thread-safe it ought to be used by one execution
52   * thread only, as only one thread a time can lease the connection at a time.
53   * <p/>
54   * This connection manager will make an effort to reuse the connection for subsequent requests
55   * with the same {@link HttpRoute route}. It will, however, close the existing connection and
56   * open it for the given route, if the route of the persistent connection does not match that
57   * of the connection request. If the connection has been already been allocated
58   * {@link IllegalStateException} is thrown.
59   * <p/>
60   * This connection manager implementation should be used inside an EJB container instead of
61   * {@link PoolingClientConnectionManager}.
62   *
63   * @since 4.2
64   *
65   * @deprecated (4.3) use {@link BasicHttpClientConnectionManager}.
66   */
67  @ThreadSafe
68  @Deprecated
69  public class BasicClientConnectionManager implements ClientConnectionManager {
70  
71      private final Log log = LogFactory.getLog(getClass());
72  
73      private static final AtomicLong COUNTER = new AtomicLong();
74  
75      /** The message to be logged on multiple allocation. */
76      public final static String MISUSE_MESSAGE =
77      "Invalid use of BasicClientConnManager: connection still allocated.\n" +
78      "Make sure to release the connection before allocating another one.";
79  
80      /** The schemes supported by this connection manager. */
81      private final SchemeRegistry schemeRegistry;
82  
83      /** The operator for opening and updating connections. */
84      private final ClientConnectionOperator connOperator;
85  
86      /** The one and only entry in this pool. */
87      @GuardedBy("this")
88      private HttpPoolEntry poolEntry;
89  
90      /** The currently issued managed connection, if any. */
91      @GuardedBy("this")
92      private ManagedClientConnectionImpl conn;
93  
94      /** Indicates whether this connection manager is shut down. */
95      @GuardedBy("this")
96      private volatile boolean shutdown;
97  
98      /**
99       * Creates a new simple connection manager.
100      *
101      * @param schreg    the scheme registry
102      */
103     public BasicClientConnectionManager(final SchemeRegistry schreg) {
104         Args.notNull(schreg, "Scheme registry");
105         this.schemeRegistry = schreg;
106         this.connOperator = createConnectionOperator(schreg);
107     }
108 
109     public BasicClientConnectionManager() {
110         this(SchemeRegistryFactory.createDefault());
111     }
112 
113     @Override
114     protected void finalize() throws Throwable {
115         try {
116             shutdown();
117         } finally { // Make sure we call overridden method even if shutdown barfs
118             super.finalize();
119         }
120     }
121 
122     public SchemeRegistry getSchemeRegistry() {
123         return this.schemeRegistry;
124     }
125 
126     protected ClientConnectionOperator createConnectionOperator(final SchemeRegistry schreg) {
127         return new DefaultClientConnectionOperator(schreg);
128     }
129 
130     public final ClientConnectionRequest requestConnection(
131             final HttpRoute route,
132             final Object state) {
133 
134         return new ClientConnectionRequest() {
135 
136             public void abortRequest() {
137                 // Nothing to abort, since requests are immediate.
138             }
139 
140             public ManagedClientConnection getConnection(
141                     final long timeout, final TimeUnit tunit) {
142                 return BasicClientConnectionManager.this.getConnection(
143                         route, state);
144             }
145 
146         };
147     }
148 
149     private void assertNotShutdown() {
150         Asserts.check(!this.shutdown, "Connection manager has been shut down");
151     }
152 
153     ManagedClientConnection getConnection(final HttpRoute route, final Object state) {
154         Args.notNull(route, "Route");
155         synchronized (this) {
156             assertNotShutdown();
157             if (this.log.isDebugEnabled()) {
158                 this.log.debug("Get connection for route " + route);
159             }
160             Asserts.check(this.conn == null, MISUSE_MESSAGE);
161             if (this.poolEntry != null && !this.poolEntry.getPlannedRoute().equals(route)) {
162                 this.poolEntry.close();
163                 this.poolEntry = null;
164             }
165             if (this.poolEntry == null) {
166                 final String id = Long.toString(COUNTER.getAndIncrement());
167                 final OperatedClientConnection opconn = this.connOperator.createConnection();
168                 this.poolEntry = new HttpPoolEntry(this.log, id, route, opconn, 0, TimeUnit.MILLISECONDS);
169             }
170             final long now = System.currentTimeMillis();
171             if (this.poolEntry.isExpired(now)) {
172                 this.poolEntry.close();
173                 this.poolEntry.getTracker().reset();
174             }
175             this.conn = new ManagedClientConnectionImpl(this, this.connOperator, this.poolEntry);
176             return this.conn;
177         }
178     }
179 
180     private void shutdownConnection(final HttpClientConnection conn) {
181         try {
182             conn.shutdown();
183         } catch (final IOException iox) {
184             if (this.log.isDebugEnabled()) {
185                 this.log.debug("I/O exception shutting down connection", iox);
186             }
187         }
188     }
189 
190     public void releaseConnection(final ManagedClientConnection conn, final long keepalive, final TimeUnit tunit) {
191         Args.check(conn instanceof ManagedClientConnectionImpl, "Connection class mismatch, " +
192             "connection not obtained from this manager");
193         final ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn;
194         synchronized (managedConn) {
195             if (this.log.isDebugEnabled()) {
196                 this.log.debug("Releasing connection " + conn);
197             }
198             if (managedConn.getPoolEntry() == null) {
199                 return; // already released
200             }
201             final ClientConnectionManager manager = managedConn.getManager();
202             Asserts.check(manager == this, "Connection not obtained from this manager");
203             synchronized (this) {
204                 if (this.shutdown) {
205                     shutdownConnection(managedConn);
206                     return;
207                 }
208                 try {
209                     if (managedConn.isOpen() && !managedConn.isMarkedReusable()) {
210                         shutdownConnection(managedConn);
211                     }
212                     if (managedConn.isMarkedReusable()) {
213                         this.poolEntry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS);
214                         if (this.log.isDebugEnabled()) {
215                             final String s;
216                             if (keepalive > 0) {
217                                 s = "for " + keepalive + " " + tunit;
218                             } else {
219                                 s = "indefinitely";
220                             }
221                             this.log.debug("Connection can be kept alive " + s);
222                         }
223                     }
224                 } finally {
225                     managedConn.detach();
226                     this.conn = null;
227                     if (this.poolEntry.isClosed()) {
228                         this.poolEntry = null;
229                     }
230                 }
231             }
232         }
233     }
234 
235     public void closeExpiredConnections() {
236         synchronized (this) {
237             assertNotShutdown();
238             final long now = System.currentTimeMillis();
239             if (this.poolEntry != null && this.poolEntry.isExpired(now)) {
240                 this.poolEntry.close();
241                 this.poolEntry.getTracker().reset();
242             }
243         }
244     }
245 
246     public void closeIdleConnections(final long idletime, final TimeUnit tunit) {
247         Args.notNull(tunit, "Time unit");
248         synchronized (this) {
249             assertNotShutdown();
250             long time = tunit.toMillis(idletime);
251             if (time < 0) {
252                 time = 0;
253             }
254             final long deadline = System.currentTimeMillis() - time;
255             if (this.poolEntry != null && this.poolEntry.getUpdated() <= deadline) {
256                 this.poolEntry.close();
257                 this.poolEntry.getTracker().reset();
258             }
259         }
260     }
261 
262     public void shutdown() {
263         synchronized (this) {
264             this.shutdown = true;
265             try {
266                 if (this.poolEntry != null) {
267                     this.poolEntry.close();
268                 }
269             } finally {
270                 this.poolEntry = null;
271                 this.conn = null;
272             }
273         }
274     }
275 
276 }