summaryrefslogtreecommitdiff
path: root/src/interfaces/jdbc/org/postgresql/PostgresqlDataSource.java
blob: 26dddfbf3deb58eb49ae038b06a2803667255246 (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
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
/**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
*	 statements and notices.  Redistributions must also contain a
*	 copy of this document.
*
* 2. Redistributions in binary form must reproduce the
*	 above copyright notice, this list of conditions and the
*	 following disclaimer in the documentation and/or other
*	 materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
*	 products derived from this Software without prior written
*	 permission of Exoffice Technologies.  For written permission,
*	 please contact info@exolab.org.
*
* 4. Products derived from this Software may not be called "Exolab"
*	 nor may "Exolab" appear in their names without prior written
*	 permission of Exoffice Technologies. Exolab is a registered
*	 trademark of Exoffice Technologies.
*
* 5. Due credit should be given to the Exolab Project
*	 (http://www.exolab.org/).
*
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.	IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
*
* $Id: PostgresqlDataSource.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
*/


package org.postgresql;


import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Properties;
import java.util.Hashtable;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.rmi.Remote;
import javax.sql.DataSource;
import javax.naming.Referenceable;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.naming.RefAddr;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.spi.ObjectFactory;
// FIXME
//import postgresql.util.PSQLException;
//import postgresql.xa.XADataSourceImpl;
import org.postgresql.util.PSQLException;
import org.postgresql.xa.XADataSourceImpl;
//---------

/**
 * Implements a JDBC 2.0 {@link javax.sql.DataSource} for the
 * PostgreSQL driver with JNDI persistance support. XA and pooled
 * connection support is also available, but the application must
 * used the designated DataSource interface to obtain them.
 * <p>
 * The supported data source properties are:
 * <pre>
 * description		   (optional)
 * databaseName		   (required)
 * loginTimeout		   (optional)
 * user				   (optional)
 * password			   (optional)
 * serverName		   (optional)
 * portNumber		   (optional)
 * transactionTimeout  (optional for XA connections)
 * </pre>
 * This data source may be serialized and stored in a JNDI
 * directory. Example of how to create a new data source and
 * register it with JNDI:
 * <pre>
 * PostgresqlDataSource ds;
 * InitialContext		ctx;
 *
 * ds = new PostgresqlDataSource();
 * ds.setDatabaseName( "test" );
 * ds.setUser( "me" );
 * ds.setPassword( "secret" );
 * ctx = new InitialContext();
 * ctx.rebind( "/comp/jdbc/test", ds );
 * </pre>
 * Example for obtaining the data source from JNDI and
 * opening a new connections:
 * <pre>
 * InitialContext		ctx;
 * DataSource			ds;
 *
 * ctx = new InitialContext();
 * ds = (DataSource) ctx.lookup( "/comp/jdbc/test" );
 * ds.getConnection();
 * </pre>
 *
 *
 * @author <a href="arkin@exoffice.com">Assaf Arkin</a>
 * @version 1.0
 * @see XADataSourceImpl
 * @see DataSource
 * @see Connection
 */
public class PostgresqlDataSource
			extends XADataSourceImpl
			implements DataSource, Referenceable,
			ObjectFactory, Serializable
{


	/**
	 * Holds the timeout for opening a new connection, specified
	 * in seconds. The default is obtained from the JDBC driver.
	 */
	private int _loginTimeout;


	/**
	 * Holds the user's account name.
	 */
	private String _user;


	/**
	 * Holds the database password.
	 */
	private String _password;


	/**
	 * Holds the name of the particular database on the server.
	 */
	private String _databaseName;


	/**
	 * Description of this datasource.
	 */
	private String _description = "PostgreSQL DataSource";


	/**
	 * Holds the database server name. If null, this is
	 * assumed to be the localhost.
	 */
	private String _serverName;


	/**
	 * Holds the port number where a server is listening.
	 * The default value will open a connection with an
	 * unspecified port.
	 */
	private int _portNumber = DEFAULT_PORT;


	/**
	 * The default port number. Since we open the connection
	 * without specifying the port if it's the default one,
	 * this value can be meaningless.
	 */
	private static final int DEFAULT_PORT = 0;


	/**
	 * Holds the log writer to which all messages should be
	 * printed. The default writer is obtained from the driver
	 * manager, but it can be specified at the datasource level
	 * and will be passed to the driver. May be null.
	 */
	private transient PrintWriter _logWriter;


	/**
	 * Each datasource maintains it's own driver, in case of
	 * driver-specific setup (e.g. pools, log writer).
	 */
	// FIXME
	//	  private transient postgresql.Driver _driver;
	private transient org.postgresql.Driver _driver;
	//---------



	public PostgresqlDataSource()
	{
		_logWriter = DriverManager.getLogWriter();
		_loginTimeout = DriverManager.getLoginTimeout();
	}


	public Connection getConnection()
	throws SQLException
	{
		// Uses the username and password specified for the datasource.
		return getConnection( _user, _password );
	}


	public synchronized Connection getConnection( String user, String password )
	throws SQLException
	{
		Connection conn;
		Properties info;
		String url;

		if ( _driver == null )
		{
			try
			{
				// Constructs a driver for use just by this data source
				// which will produce TwoPhaseConnection-s. This driver
				// is not registered with the driver manager.
				// FIXME
				//		_driver = new postgresql.Driver();
				_driver = new org.postgresql.Driver();
				//-----------

				//FIXME
				//		_driver.setLogWriter( _logWriter );
				// Method seems to be unavailable. Just commented it out.
				//----------
			}
			catch ( SQLException except )
			{
				if ( _logWriter != null )
					_logWriter.println( "DataSource: Failed to initialize JDBC driver: " + except );
				throw except;
			}
		}

		// Use info to supply properties that are not in the URL.
		info = new Properties();
		info.put( "loginTimeout", Integer.toString( _loginTimeout ) );

		// DriverManager will do that and not rely on the URL alone.
		if ( user == null )
		{
			user = _user;
			password = _password;
		}
		if ( user == null || password == null )
			throw new PSQLException( "postgresql.ds.userpswd" );
		info.put( "user", user );
		info.put( "password", password );

		if ( _serverName != null )
			info.put( "PGHOST", _serverName );
		if ( _portNumber != DEFAULT_PORT )
			info.put( "PGPORT", Integer.toString( _portNumber ) );
		if ( _databaseName != null )
			info.put( "PGDBNAME", _databaseName );

		// Construct the URL suitable for this driver.
		url = "jdbc:postgresql:";

		// Attempt to establish a connection. Report a successful
		// attempt or a failure.
		try
		{
			conn = _driver.connect( url, info );
			// FIXME
			//		if ( ! ( conn instanceof postgresql.jdbc2.Connection ) ) {
			if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) )
			{
				//--------
				if ( _logWriter != null )
					_logWriter.println( "DataSource: JDBC 1 connections not supported" );
				throw new PSQLException( "postgresql.ds.onlyjdbc2" );
			}
		}
		catch ( SQLException except )
		{
			if ( _logWriter != null )
				_logWriter.println( "DataSource: getConnection failed " + except );
			throw except;
		}
		if ( conn != null && _logWriter != null )
			_logWriter.println( "DataSource: getConnection returning " + conn );
		return conn;
	}


	public PrintWriter getLogWriter()
	{
		return _logWriter;
	}


	public synchronized void setLogWriter( PrintWriter writer )
	{
		// Once a log writer has been set, we cannot set it since some
		// thread might be conditionally accessing it right now without
		// synchronizing.
		if ( writer != null )
		{
			if ( _driver != null )
				// FIXME
				//		_driver.setLogWriter( writer );
				// Method seems to be unavailable. Commented it out.
				//----------
				_logWriter = writer;
		}
	}


	public void setLoginTimeout( int seconds )
	{
		_loginTimeout = seconds;
	}


	public synchronized int getLoginTimeout()
	{
		return _loginTimeout;
	}


	/**
	 * Sets the name of the particular database on the server.
	 * The standard name for this property is <tt>databaseName</tt>.
	 *
	 * @param databaseName The name of the particular database on the server
	 */
	public synchronized void setDatabaseName( String databaseName )
	{
		if ( databaseName == null )
			throw new NullPointerException( "DataSource: Argument 'databaseName' is null" );
		_databaseName = databaseName;
	}


	/**
	 * Returns the name of the particular database on the server.
	 * The standard name for this property is <tt>databaseName</tt>.
	 *
	 * @return The name of the particular database on the server
	 */
	public String getDatabaseName()
	{
		return _databaseName;
	}


	/**
	 * Sets the description of this datasource.
	 * The standard name for this property is <tt>description</tt>.
	 *
	 * @param description The description of this datasource
	 */
	public synchronized void setDescription( String description )
	{
		if ( description == null )
			throw new NullPointerException( "DataSource: Argument 'description' is null" );
		_description = description;
	}


	/**
	 * Returns the description of this datasource.
	 * The standard name for this property is <tt>description</tt>.
	 *
	 * @return The description of this datasource
	 */
	public String getDescription()
	{
		return _description;
	}


	/**
	 * Sets the database password.
	 * The standard name for this property is <tt>password</tt>.
	 *
	 * @param password The database password
	 */
	public synchronized void setPassword( String password )
	{
		_password = password;
	}


	/**
	 * Returns the database password.
	 * The standard name for this property is <tt>password</tt>.
	 *
	 * @return The database password
	 */
	public String getPassword()
	{
		return _password;
	}


	/**
	 * Sets the port number where a server is listening.
	 * The standard name for this property is <tt>portNumber</tt>.
	 *
	 * @param portNumber The port number where a server is listening
	 */
	public synchronized void setPortNumber( int portNumber )
	{
		_portNumber = portNumber;
	}


	/**
	 * Returns the port number where a server is listening.
	 * The standard name for this property is <tt>portNumber</tt>.
	 *
	 * @return The port number where a server is listening
	 */
	public int getPortNumber()
	{
		return _portNumber;
	}


	/**
	 * Sets the database server name.

	 * The standard name for this property is <tt>serverName</tt>.
	 *
	 * @param serverName The database server name
	 */
	public synchronized void setServerName( String serverName )
	{
		_serverName = serverName;
	}


	/**
	 * Returns the database server name.
	 * The standard name for this property is <tt>serverName</tt>.
	 *
	 * @return The database server name
	 */
	public String getServerName()
	{
		return _serverName;
	}


	/**
	 * Sets the user's account name.
	 * The standard name for this property is <tt>user</tt>.
	 *
	 * @param user The user's account name
	 */
	public synchronized void setUser( String user )
	{
		_user = user;
	}


	/**
	 * Returns the user's account name.
	 * The standard name for this property is <tt>user</tt>.
	 *
	 * @return The user's account name
	 */
	public String getUser()
	{
		return _user;
	}


	/**
	 * Returns true if this datasource and the other are equal.
	 * The two datasources are equal if and only if they will produce
	 * the exact same connections. Connection properties like database
	 * name, user name, etc are comapred. Setup properties like
	 * description, log writer, etc are not compared.
	 */
	public synchronized boolean equals( Object other )
	{
		if ( other == this )
			return true;
		if ( other == null || ! ( other instanceof PostgresqlDataSource ) )
			return false;

		PostgresqlDataSource with;

		with = (PostgresqlDataSource) other;
		if ( _databaseName != null && _databaseName.equals( with._databaseName ) )
			if ( _portNumber == with._portNumber &&
					( ( _serverName == null && with._serverName == null ) ||
					  ( _serverName != null && _serverName.equals( with._serverName ) ) ) )
				if ( ( _user == null && with._user == null ) ||
						( _user != null && _password != null && _user.equals( with._user ) &&
						  _password.equals( with._password ) ) )
					return true;
		return false;
	}


	public String toString()
	{
		if ( _description != null )
			return _description;
		else
		{
			String url;

			url = "jdbc:postgresql:";
			if ( _serverName != null )
			{
				if ( _portNumber == DEFAULT_PORT )
					url = url + "//" + _serverName + "/";
				else
					url = url + "//" + _serverName + ":" + _portNumber + "/";
			}
			else if ( _portNumber != DEFAULT_PORT )
				url = url + "//localhost:" + _portNumber + "/";
			if ( _databaseName != null )
				url = url + _databaseName;
			return "DataSource " + url;
		}
	}


	public synchronized Reference getReference()
	{
		Reference ref;

		// We use same object as factory.
		ref = new Reference( getClass().getName(), getClass().getName(), null );
		// Mandatory properties
		ref.add( new StringRefAddr( "description", _description ) );
		ref.add( new StringRefAddr( "databaseName", _databaseName ) );
		ref.add( new StringRefAddr( "loginTimeout", Integer.toString( _loginTimeout ) ) );
		// Optional properties
		if ( _user != null )
			ref.add( new StringRefAddr( "user", _user ) );
		if ( _password != null )
			ref.add( new StringRefAddr( "password", _password ) );
		if ( _serverName != null )
			ref.add( new StringRefAddr( "serverName", _serverName ) );
		if ( _portNumber != DEFAULT_PORT )
			ref.add( new StringRefAddr( "portNumber", Integer.toString( _portNumber ) ) );
		ref.add( new StringRefAddr( "transactionTimeout", Integer.toString( getTransactionTimeout() ) ) );
		return ref;
	}


	public Object getObjectInstance( Object refObj, Name name, Context nameCtx, Hashtable env )
	throws NamingException
	{
		Reference ref;

		// Can only reconstruct from a reference.
		if ( refObj instanceof Reference )
		{
			ref = (Reference) refObj;
			// Make sure reference is of datasource class.
			if ( ref.getClassName().equals( getClass().getName() ) )
			{

				PostgresqlDataSource ds;
				RefAddr addr;

				try
				{
					ds = (PostgresqlDataSource) Class.forName( ref.getClassName() ).newInstance();
				}
				catch ( Exception except )
				{
					throw new NamingException( except.toString() );
				}
				// Mandatory properties
				ds._description = (String) ref.get( "description" ).getContent();
				ds._databaseName = (String) ref.get( "databaseName" ).getContent();
				ds._loginTimeout = Integer.parseInt( (String) ref.get( "loginTimeout" ).getContent() );
				// Optional properties
				addr = ref.get( "user" );
				if ( addr != null )
					ds._user = (String) addr.getContent();
				addr = ref.get( "password" );
				if ( addr != null )
					ds._password = (String) addr.getContent();
				addr = ref.get( "serverName" );
				if ( addr != null )
					ds._serverName = (String) addr.getContent();
				addr = ref.get( "portNumber" );
				if ( addr != null )
					ds._portNumber = Integer.parseInt( (String) addr.getContent() );
				addr = ref.get( "transactionTimeout" );
				if ( addr != null )
					setTransactionTimeout( Integer.parseInt( (String) addr.getContent() ) );
				return ds;

			}
			else
				throw new NamingException( "DataSource: Reference not constructed from class " + getClass().getName() );
		}
		else if ( refObj instanceof Remote )
			return refObj;
		else
			return null;
	}


}