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