summaryrefslogtreecommitdiffstats
path: root/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/SingleClientConnManager.java
blob: c2b6c879958e136cbc10aca5b16ea3e4386ed9a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package ch.boye.httpclientandroidlib.impl.conn;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
/* LogFactory removed by HttpClient for Android script. */
import ch.boye.httpclientandroidlib.annotation.GuardedBy;
import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
import ch.boye.httpclientandroidlib.conn.ClientConnectionOperator;
import ch.boye.httpclientandroidlib.conn.ClientConnectionRequest;
import ch.boye.httpclientandroidlib.conn.ManagedClientConnection;
import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
import ch.boye.httpclientandroidlib.conn.routing.RouteTracker;
import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
import ch.boye.httpclientandroidlib.params.HttpParams;
import ch.boye.httpclientandroidlib.util.Args;
import ch.boye.httpclientandroidlib.util.Asserts;

/**
 * A connection manager for a single connection. This connection manager
 * maintains only one active connection at a time. Even though this class
 * is thread-safe it ought to be used by one execution thread only.
 * <p>
 * SingleClientConnManager will make an effort to reuse the connection
 * for subsequent requests with the same {@link HttpRoute route}.
 * It will, however, close the existing connection and open it
 * for the given route, if the route of the persistent connection does
 * not match that of the connection request. If the connection has been
 * already been allocated {@link IllegalStateException} is thrown.
 *
 * @since 4.0
 *
 * @deprecated (4.2)  use {@link BasicClientConnectionManager}
 */
@ThreadSafe
@Deprecated
public class SingleClientConnManager implements ClientConnectionManager {

    public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());

    /** The message to be logged on multiple allocation. */
    public final static String MISUSE_MESSAGE =
    "Invalid use of SingleClientConnManager: connection still allocated.\n" +
    "Make sure to release the connection before allocating another one.";

    /** The schemes supported by this connection manager. */
    protected final SchemeRegistry schemeRegistry;

    /** The operator for opening and updating connections. */
    protected final ClientConnectionOperator connOperator;

    /** Whether the connection should be shut down  on release. */
    protected final boolean alwaysShutDown;

    /** The one and only entry in this pool. */
    @GuardedBy("this")
    protected volatile PoolEntry uniquePoolEntry;

    /** The currently issued managed connection, if any. */
    @GuardedBy("this")
    protected volatile ConnAdapter managedConn;

    /** The time of the last connection release, or -1. */
    @GuardedBy("this")
    protected volatile long lastReleaseTime;

    /** The time the last released connection expires and shouldn't be reused. */
    @GuardedBy("this")
    protected volatile long connectionExpiresTime;

    /** Indicates whether this connection manager is shut down. */
    protected volatile boolean isShutDown;

    /**
     * Creates a new simple connection manager.
     *
     * @param params    the parameters for this manager
     * @param schreg    the scheme registry
     *
     * @deprecated (4.1)  use {@link SingleClientConnManager#SingleClientConnManager(SchemeRegistry)}
     */
    @Deprecated
    public SingleClientConnManager(final HttpParams params,
                                   final SchemeRegistry schreg) {
        this(schreg);
    }
    /**
     * Creates a new simple connection manager.
     *
     * @param schreg    the scheme registry
     */
    public SingleClientConnManager(final SchemeRegistry schreg) {
        Args.notNull(schreg, "Scheme registry");
        this.schemeRegistry  = schreg;
        this.connOperator    = createConnectionOperator(schreg);
        this.uniquePoolEntry = new PoolEntry();
        this.managedConn     = null;
        this.lastReleaseTime = -1L;
        this.alwaysShutDown  = false; //@@@ from params? as argument?
        this.isShutDown      = false;
    }

    /**
     * @since 4.1
     */
    public SingleClientConnManager() {
        this(SchemeRegistryFactory.createDefault());
    }

    @Override
    protected void finalize() throws Throwable {
        try {
            shutdown();
        } finally { // Make sure we call overridden method even if shutdown barfs
            super.finalize();
        }
    }

    public SchemeRegistry getSchemeRegistry() {
        return this.schemeRegistry;
    }

    /**
     * Hook for creating the connection operator.
     * It is called by the constructor.
     * Derived classes can override this method to change the
     * instantiation of the operator.
     * The default implementation here instantiates
     * {@link DefaultClientConnectionOperator DefaultClientConnectionOperator}.
     *
     * @param schreg    the scheme registry to use, or <code>null</code>
     *
     * @return  the connection operator to use
     */
    protected ClientConnectionOperator
        createConnectionOperator(final SchemeRegistry schreg) {
        return new DefaultClientConnectionOperator(schreg);
    }

    /**
     * Asserts that this manager is not shut down.
     *
     * @throws IllegalStateException    if this manager is shut down
     */
    protected final void assertStillUp() throws IllegalStateException {
        Asserts.check(!this.isShutDown, "Manager is shut down");
    }

    public final ClientConnectionRequest requestConnection(
            final HttpRoute route,
            final Object state) {

        return new ClientConnectionRequest() {

            public void abortRequest() {
                // Nothing to abort, since requests are immediate.
            }

            public ManagedClientConnection getConnection(
                    final long timeout, final TimeUnit tunit) {
                return SingleClientConnManager.this.getConnection(
                        route, state);
            }

        };
    }

    /**
     * Obtains a connection.
     *
     * @param route     where the connection should point to
     *
     * @return  a connection that can be used to communicate
     *          along the given route
     */
    public ManagedClientConnection getConnection(final HttpRoute route, final Object state) {
        Args.notNull(route, "Route");
        assertStillUp();

        if (log.isDebugEnabled()) {
            log.debug("Get connection for route " + route);
        }

        synchronized (this) {

            Asserts.check(managedConn == null, MISUSE_MESSAGE);

            // check re-usability of the connection
            boolean recreate = false;
            boolean shutdown = false;

            // Kill the connection if it expired.
            closeExpiredConnections();

            if (uniquePoolEntry.connection.isOpen()) {
                final RouteTracker tracker = uniquePoolEntry.tracker;
                shutdown = (tracker == null || // can happen if method is aborted
                            !tracker.toRoute().equals(route));
            } else {
                // If the connection is not open, create a new PoolEntry,
                // as the connection may have been marked not reusable,
                // due to aborts -- and the PoolEntry should not be reused
                // either.  There's no harm in recreating an entry if
                // the connection is closed.
                recreate = true;
            }

            if (shutdown) {
                recreate = true;
                try {
                    uniquePoolEntry.shutdown();
                } catch (final IOException iox) {
                    log.debug("Problem shutting down connection.", iox);
                }
            }

            if (recreate) {
                uniquePoolEntry = new PoolEntry();
            }

            managedConn = new ConnAdapter(uniquePoolEntry, route);

            return managedConn;
        }
    }

    public void releaseConnection(
            final ManagedClientConnection conn,
            final long validDuration, final TimeUnit timeUnit) {
        Args.check(conn instanceof ConnAdapter, "Connection class mismatch, " +
            "connection not obtained from this manager");
        assertStillUp();

        if (log.isDebugEnabled()) {
            log.debug("Releasing connection " + conn);
        }

        final ConnAdapter sca = (ConnAdapter) conn;
        synchronized (sca) {
            if (sca.poolEntry == null)
             {
                return; // already released
            }
            final ClientConnectionManager manager = sca.getManager();
            Asserts.check(manager == this, "Connection not obtained from this manager");
            try {
                // make sure that the response has been read completely
                if (sca.isOpen() && (this.alwaysShutDown ||
                                     !sca.isMarkedReusable())
                    ) {
                    if (log.isDebugEnabled()) {
                        log.debug
                            ("Released connection open but not reusable.");
                    }

                    // make sure this connection will not be re-used
                    // we might have gotten here because of a shutdown trigger
                    // shutdown of the adapter also clears the tracked route
                    sca.shutdown();
                }
            } catch (final IOException iox) {
                if (log.isDebugEnabled()) {
                    log.debug("Exception shutting down released connection.",
                              iox);
                }
            } finally {
                sca.detach();
                synchronized (this) {
                    managedConn = null;
                    lastReleaseTime = System.currentTimeMillis();
                    if(validDuration > 0) {
                        connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime;
                    } else {
                        connectionExpiresTime = Long.MAX_VALUE;
                    }
                }
            }
        }
    }

    public void closeExpiredConnections() {
        final long time = connectionExpiresTime;
        if (System.currentTimeMillis() >= time) {
            closeIdleConnections(0, TimeUnit.MILLISECONDS);
        }
    }

    public void closeIdleConnections(final long idletime, final TimeUnit tunit) {
        assertStillUp();

        // idletime can be 0 or negative, no problem there
        Args.notNull(tunit, "Time unit");

        synchronized (this) {
            if ((managedConn == null) && uniquePoolEntry.connection.isOpen()) {
                final long cutoff =
                    System.currentTimeMillis() - tunit.toMillis(idletime);
                if (lastReleaseTime <= cutoff) {
                    try {
                        uniquePoolEntry.close();
                    } catch (final IOException iox) {
                        // ignore
                        log.debug("Problem closing idle connection.", iox);
                    }
                }
            }
        }
    }

    public void shutdown() {
        this.isShutDown = true;
        synchronized (this) {
            try {
                if (uniquePoolEntry != null) {
                    uniquePoolEntry.shutdown();
                }
            } catch (final IOException iox) {
                // ignore
                log.debug("Problem while shutting down manager.", iox);
            } finally {
                uniquePoolEntry = null;
                managedConn = null;
            }
        }
    }

    protected void revokeConnection() {
        final ConnAdapter conn = managedConn;
        if (conn == null) {
            return;
        }
        conn.detach();

        synchronized (this) {
            try {
                uniquePoolEntry.shutdown();
            } catch (final IOException iox) {
                // ignore
                log.debug("Problem while shutting down connection.", iox);
            }
        }
    }

    /**
     * The pool entry for this connection manager.
     */
    protected class PoolEntry extends AbstractPoolEntry {

        /**
         * Creates a new pool entry.
         *
         */
        protected PoolEntry() {
            super(SingleClientConnManager.this.connOperator, null);
        }

        /**
         * Closes the connection in this pool entry.
         */
        protected void close() throws IOException {
            shutdownEntry();
            if (connection.isOpen()) {
                connection.close();
            }
        }

        /**
         * Shuts down the connection in this pool entry.
         */
        protected void shutdown() throws IOException {
            shutdownEntry();
            if (connection.isOpen()) {
                connection.shutdown();
            }
        }

    }

    /**
     * The connection adapter used by this manager.
     */
    protected class ConnAdapter extends AbstractPooledConnAdapter {

        /**
         * Creates a new connection adapter.
         *
         * @param entry   the pool entry for the connection being wrapped
         * @param route   the planned route for this connection
         */
        protected ConnAdapter(final PoolEntry entry, final HttpRoute route) {
            super(SingleClientConnManager.this, entry);
            markReusable();
            entry.route = route;
        }

    }

}