File: AbstractJdbc23PoolingDataSource.java

package info (click to toggle)
libpgjava 8.4-701-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 3,532 kB
  • ctags: 4,162
  • sloc: java: 33,948; xml: 3,158; makefile: 14; sh: 10
file content (515 lines) | stat: -rw-r--r-- 17,966 bytes parent folder | download
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2008, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/ds/jdbc23/AbstractJdbc23PoolingDataSource.java,v 1.2 2008/01/08 06:56:27 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.ds.jdbc23;

import javax.sql.*;
import javax.naming.*;
import java.util.*;
import java.sql.Connection;
import java.sql.SQLException;

import org.postgresql.util.GT;
import org.postgresql.util.PSQLState;
import org.postgresql.util.PSQLException;
import org.postgresql.ds.*;
import org.postgresql.ds.common.*;

/**
 * DataSource which uses connection pooling.  <font color="red">Don't use this if
 * your server/middleware vendor provides a connection pooling implementation
 * which interfaces with the PostgreSQL ConnectionPoolDataSource implementation!</font>
 * This class is provided as a convenience, but the JDBC Driver is really not
 * supposed to handle the connection pooling algorithm.  Instead, the server or
 * middleware product is supposed to handle the mechanics of connection pooling,
 * and use the PostgreSQL implementation of ConnectionPoolDataSource to provide
 * the connections to pool.
 *
 * <p>If you're sure you want to use this, then you must set the properties
 * dataSourceName, databaseName, user, and password (if required for the user).
 * The settings for serverName, portNumber, initialConnections, and
 * maxConnections are optional.  Note that <i>only connections
 * for the default user will be pooled!</i>  Connections for other users will
 * be normal non-pooled connections, and will not count against the maximum pool
 * size limit.</p>
 *
 * <p>If you put this DataSource in JNDI, and access it from different JVMs (or
 * otherwise load this class from different ClassLoaders), you'll end up with one
 * pool per ClassLoader or VM. This is another area where a server-specific
 * implementation may provide advanced features, such as using a single pool
 * across all VMs in a cluster.</p>
 *
 * <p>This implementation supports JDK 1.3 and higher.</p>
 *
 * @author Aaron Mulder (ammulder@chariotsolutions.com)
 */
public abstract class AbstractJdbc23PoolingDataSource extends BaseDataSource 
{
    protected static Map dataSources = new HashMap();

    public static PGPoolingDataSource getDataSource(String name)
    {
        return (PGPoolingDataSource)dataSources.get(name);
    }

    // Additional Data Source properties
    protected String dataSourceName;  // Must be protected for subclasses to sync updates to it
    private int initialConnections = 0;
    private int maxConnections = 0;
    // State variables
    private boolean initialized = false;
    private Stack available = new Stack();
    private Stack used = new Stack();
    private Object lock = new Object()
                              ;
    private PGConnectionPoolDataSource source;

    /**
     * Gets a description of this DataSource.
     */
    public String getDescription()
    {
        return "Pooling DataSource '" + dataSourceName + " from " + org.postgresql.Driver.getVersion();
    }

    /**
     * Ensures the DataSource properties are not changed after the DataSource has
     * been used.
     *
     * @throws java.lang.IllegalStateException
     *     The Server Name cannot be changed after the DataSource has been
     *     used.
     */
    public void setServerName(String serverName)
    {
        if (initialized)
        {
            throw new IllegalStateException("Cannot set Data Source properties after DataSource has been used");
        }
        super.setServerName(serverName);
    }

    /**
     * Ensures the DataSource properties are not changed after the DataSource has
     * been used.
     *
     * @throws java.lang.IllegalStateException
     *     The Database Name cannot be changed after the DataSource has been
     *     used.
     */
    public void setDatabaseName(String databaseName)
    {
        if (initialized)
        {
            throw new IllegalStateException("Cannot set Data Source properties after DataSource has been used");
        }
        super.setDatabaseName(databaseName);
    }

    /**
     * Ensures the DataSource properties are not changed after the DataSource has
     * been used.
     *
     * @throws java.lang.IllegalStateException
     *     The User cannot be changed after the DataSource has been
     *     used.
     */
    public void setUser(String user)
    {
        if (initialized)
        {
            throw new IllegalStateException("Cannot set Data Source properties after DataSource has been used");
        }
        super.setUser(user);
    }

    /**
     * Ensures the DataSource properties are not changed after the DataSource has
     * been used.
     *
     * @throws java.lang.IllegalStateException
     *     The Password cannot be changed after the DataSource has been
     *     used.
     */
    public void setPassword(String password)
    {
        if (initialized)
        {
            throw new IllegalStateException("Cannot set Data Source properties after DataSource has been used");
        }
        super.setPassword(password);
    }

    /**
     * Ensures the DataSource properties are not changed after the DataSource has
     * been used.
     *
     * @throws java.lang.IllegalStateException
     *     The Port Number cannot be changed after the DataSource has been
     *     used.
     */
    public void setPortNumber(int portNumber)
    {
        if (initialized)
        {
            throw new IllegalStateException("Cannot set Data Source properties after DataSource has been used");
        }
        super.setPortNumber(portNumber);
    }

    /**
     * Gets the number of connections that will be created when this DataSource
     * is initialized. If you do not call initialize explicitly, it will be
     * initialized the first time a connection is drawn from it.
     */
    public int getInitialConnections()
    {
        return initialConnections;
    }

    /**
     * Sets the number of connections that will be created when this DataSource
     * is initialized. If you do not call initialize explicitly, it will be
     * initialized the first time a connection is drawn from it.
     *
     * @throws java.lang.IllegalStateException
     *     The Initial Connections cannot be changed after the DataSource has been
     *     used.
     */
    public void setInitialConnections(int initialConnections)
    {
        if (initialized)
        {
            throw new IllegalStateException("Cannot set Data Source properties after DataSource has been used");
        }
        this.initialConnections = initialConnections;
    }

    /**
     * Gets the maximum number of connections that the pool will allow.  If a request
     * comes in and this many connections are in use, the request will block until a
     * connection is available.  Note that connections for a user other than the
     * default user will not be pooled and don't count against this limit.
     *
     * @return The maximum number of pooled connection allowed, or 0 for no maximum.
     */
    public int getMaxConnections()
    {
        return maxConnections;
    }

    /**
     * Sets the maximum number of connections that the pool will allow.  If a request
     * comes in and this many connections are in use, the request will block until a
     * connection is available.  Note that connections for a user other than the
     * default user will not be pooled and don't count against this limit.
     *
     * @param maxConnections The maximum number of pooled connection to allow, or
     *    0 for no maximum.
     *
     * @throws java.lang.IllegalStateException
     *     The Maximum Connections cannot be changed after the DataSource has been
     *     used.
     */
    public void setMaxConnections(int maxConnections)
    {
        if (initialized)
        {
            throw new IllegalStateException("Cannot set Data Source properties after DataSource has been used");
        }
        this.maxConnections = maxConnections;
    }

    /**
     * Gets the name of this DataSource.  This uniquely identifies the DataSource.
     * You cannot use more than one DataSource in the same VM with the same name.
     */
    public String getDataSourceName()
    {
        return dataSourceName;
    }

    /**
     * Sets the name of this DataSource.  This is required, and uniquely identifies
     * the DataSource. You cannot create or use more than one DataSource in the
     * same VM with the same name.
     *
     * @throws java.lang.IllegalStateException
     *     The Data Source Name cannot be changed after the DataSource has been
     *     used.
     * @throws java.lang.IllegalArgumentException
     *     Another PoolingDataSource with the same dataSourceName already
     *     exists.
     */
    public void setDataSourceName(String dataSourceName)
    {
        if (initialized)
        {
            throw new IllegalStateException("Cannot set Data Source properties after DataSource has been used");
        }
        if (this.dataSourceName != null && dataSourceName != null && dataSourceName.equals(this.dataSourceName))
        {
            return ;
        }
        synchronized (dataSources)
        {
            if (getDataSource(dataSourceName) != null)
            {
                throw new IllegalArgumentException("DataSource with name '" + dataSourceName + "' already exists!");
            }
            if (this.dataSourceName != null)
            {
                dataSources.remove(this.dataSourceName);
            }
            this.dataSourceName = dataSourceName;
            addDataSource(dataSourceName);
        }
    }

    /**
     * Initializes this DataSource.  If the initialConnections is greater than zero,
     * that number of connections will be created. After this method is called,
     * the DataSource properties cannot be changed.  If you do not call this
     * explicitly, it will be called the first time you get a connection from the
     * DataSource.
     * @throws java.sql.SQLException
     *     Occurs when the initialConnections is greater than zero, but the
     *     DataSource is not able to create enough physical connections.
     */
    public void initialize() throws SQLException
    {
        synchronized (lock )
        {
            source = createConnectionPool();
            source.setDatabaseName(getDatabaseName());
            source.setPassword(getPassword());
            source.setPortNumber(getPortNumber());
            source.setServerName(getServerName());
            source.setUser(getUser());
            while (available.size() < initialConnections)
            {
                available.push(source.getPooledConnection());
            }
            initialized = true;
        }
    }

    protected boolean isInitialized() {
        return initialized;
    }

    /**
     * Creates the appropriate ConnectionPool to use for this DataSource.
     */
    protected PGConnectionPoolDataSource createConnectionPool() {
        return new PGConnectionPoolDataSource();
    }

    /**
     * Gets a <b>non-pooled</b> connection, unless the user and password are the
     * same as the default values for this connection pool.
     *
     * @return A pooled connection.
     * @throws SQLException
     *     Occurs when no pooled connection is available, and a new physical
     *     connection cannot be created.
     */
    public Connection getConnection(String user, String password) throws SQLException
    {
        // If this is for the default user/password, use a pooled connection
        if (user == null ||
                (user.equals(getUser()) && ((password == null && getPassword() == null) || (password != null && password.equals(getPassword())))))
        {
            return getConnection();
        }
        // Otherwise, use a non-pooled connection
        if (!initialized)
        {
            initialize();
        }
        return super.getConnection(user, password);
    }

    /**
     * Gets a connection from the connection pool.
     *
     * @return A pooled connection.
     * @throws SQLException
     *     Occurs when no pooled connection is available, and a new physical
     *     connection cannot be created.
     */
    public Connection getConnection() throws SQLException
    {
        if (!initialized)
        {
            initialize();
        }
        return getPooledConnection();
    }

    /**
     * Closes this DataSource, and all the pooled connections, whether in use or not.
     */
    public void close()
    {
        synchronized (lock )
        {
            while (available.size() > 0)
            {
                PGPooledConnection pci = (PGPooledConnection)available.pop();
                try
                {
                    pci.close();
                }
                catch (SQLException e)
                {
                }
            }
            available = null;
            while (used.size() > 0)
            {
                PGPooledConnection pci = (PGPooledConnection)used.pop();
                pci.removeConnectionEventListener(connectionEventListener);
                try
                {
                    pci.close();
                }
                catch (SQLException e)
                {
                }
            }
            used = null;
        }
        removeStoredDataSource();
    }

    protected void removeStoredDataSource() {
        synchronized (dataSources)
        {
            dataSources.remove(dataSourceName);
        }
    }

    protected abstract void addDataSource(String dataSourceName);

    /**
    * Gets a connection from the pool.  Will get an available one if
    * present, or create a new one if under the max limit.  Will
    * block if all used and a new one would exceed the max.
    */
    private Connection getPooledConnection() throws SQLException
    {
        PooledConnection pc = null;
        synchronized (lock )
        {
            if (available == null)
            {
                throw new PSQLException(GT.tr("DataSource has been closed."),
                                        PSQLState.CONNECTION_DOES_NOT_EXIST);
            }
            while (true)
            {
                if (available.size() > 0)
                {
                    pc = (PooledConnection)available.pop();
                    used.push(pc);
                    break;
                }
                if (maxConnections == 0 || used.size() < maxConnections)
                {
                    pc = source.getPooledConnection();
                    used.push(pc);
                    break;
                }
                else
                {
                    try
                    {
                        // Wake up every second at a minimum
                        lock.wait(1000L);
                    }
                    catch (InterruptedException e)
                    {
                    }
                }
            }
        }
        pc.addConnectionEventListener(connectionEventListener);
        return pc.getConnection();
    }

    /**
     * Notified when a pooled connection is closed, or a fatal error occurs
     * on a pooled connection. This is the only way connections are marked
     * as unused.
     */
    private ConnectionEventListener connectionEventListener = new ConnectionEventListener()
            {
                public void connectionClosed(ConnectionEvent event)
                {
                    ((PooledConnection)event.getSource()).removeConnectionEventListener(this);
                    synchronized (lock )
                    {
                        if (available == null)
                        {
                            return ; // DataSource has been closed
                        }
                        boolean removed = used.remove(event.getSource());
                        if (removed)
                        {
                            available.push(event.getSource());
                            // There's now a new connection available
                            lock.notify();
                        }
                        else
                        {
                            // a connection error occured
                        }
                    }
                }

                /**
                 * This is only called for fatal errors, where the physical connection is
                 * useless afterward and should be removed from the pool.
                 */
                public void connectionErrorOccurred(ConnectionEvent event)
                {
                    ((PooledConnection) event.getSource()).removeConnectionEventListener(this);
                    synchronized (lock )
                    {
                        if (available == null)
                        {
                            return ; // DataSource has been closed
                        }
                        used.remove(event.getSource());
                        // We're now at least 1 connection under the max
                        lock.notify();
                    }
                }
            };

    /**
     * Adds custom properties for this DataSource to the properties defined in
     * the superclass.
     */
    public Reference getReference() throws NamingException
    {
        Reference ref = super.getReference();
        ref.add(new StringRefAddr("dataSourceName", dataSourceName));
        if (initialConnections > 0)
        {
            ref.add(new StringRefAddr("initialConnections", Integer.toString(initialConnections)));
        }
        if (maxConnections > 0)
        {
            ref.add(new StringRefAddr("maxConnections", Integer.toString(maxConnections)));
        }
        return ref;
    }
}