File: BaseDataSource.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 (466 lines) | stat: -rw-r--r-- 13,849 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
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2008, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/ds/common/BaseDataSource.java,v 1.17 2009/06/20 15:19:40 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.ds.common;

import javax.naming.*;
import java.io.PrintWriter;
import java.sql.*;

import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;

/**
 * Base class for data sources and related classes.
 *
 * @author Aaron Mulder (ammulder@chariotsolutions.com)
 */
public abstract class BaseDataSource implements Referenceable
{
    // Load the normal driver, since we'll use it to actually connect to the
    // database.  That way we don't have to maintain the connecting code in
    // multiple places.
    static {
        try
        {
            Class.forName("org.postgresql.Driver");
        }
        catch (ClassNotFoundException e)
        {
            System.err.println("PostgreSQL DataSource unable to load PostgreSQL JDBC Driver");
        }
    }

    // Needed to implement the DataSource/ConnectionPoolDataSource interfaces
    private transient PrintWriter logger;

    // Standard properties, defined in the JDBC 2.0 Optional Package spec
    private String serverName = "localhost";
    private String databaseName;
    private String user;
    private String password;
    private int portNumber = 0;
    private int prepareThreshold = 5;
    private int unknownLength = Integer.MAX_VALUE;
    private int loginTimeout = 0; // in seconds
    private int socketTimeout = 0; // in seconds
    private boolean ssl = false;
    private String sslfactory;
    private boolean tcpKeepAlive = false;
    private String compatible;

    /**
     * Gets a connection to the PostgreSQL database.  The database is identified by the
     * DataSource properties serverName, databaseName, and portNumber. The user to
     * connect as is identified by the DataSource properties user and password.
     *
     * @return A valid database connection.
     * @throws SQLException
     *     Occurs when the database connection cannot be established.
     */
    public Connection getConnection() throws SQLException
    {
        return getConnection(user, password);
    }

    /**
     * Gets a connection to the PostgreSQL database.  The database is identified by the
     * DataSource properties serverName, databaseName, and portNumber. The user to
     * connect as is identified by the arguments user and password, which override
     * the DataSource properties by the same name.
     *
     * @return A valid database connection.
     * @throws SQLException
     *     Occurs when the database connection cannot be established.
     */
    public Connection getConnection(String user, String password) throws SQLException
    {
        try
        {
            Connection con = DriverManager.getConnection(getUrl(), user, password);
            if (logger != null)
            {
                logger.println("Created a non-pooled connection for " + user + " at " + getUrl());
            }
            return con;
        }
        catch (SQLException e)
        {
            if (logger != null)
            {
                logger.println("Failed to create a non-pooled connection for " + user + " at " + getUrl() + ": " + e);
            }
            throw e;
        }
    }

    /**
     * @return the login timeout, in seconds.
     */
    public int getLoginTimeout() throws SQLException
    {
        return loginTimeout;
    }

    /**
     * Set the login timeout, in seconds.
     */
    public void setLoginTimeout(int i) throws SQLException
    {
        this.loginTimeout = i;
    }

    /**
     * Gets the log writer used to log connections opened.
     */
    public PrintWriter getLogWriter() throws SQLException
    {
        return logger;
    }

    /**
     * The DataSource will note every connection opened to the provided log writer.
     */
    public void setLogWriter(PrintWriter printWriter) throws SQLException
    {
        logger = printWriter;
    }

    /**
     * Gets the name of the host the PostgreSQL database is running on.
     */
    public String getServerName()
    {
        return serverName;
    }

    /**
     * Sets the name of the host the PostgreSQL database is running on.  If this
     * is changed, it will only affect future calls to getConnection.  The default
     * value is <tt>localhost</tt>.
     */
    public void setServerName(String serverName)
    {
        if (serverName == null || serverName.equals(""))
        {
            this.serverName = "localhost";
        }
        else
        {
            this.serverName = serverName;
        }
    }

    public String getCompatible()
    {
        return compatible;
    }

    public void setCompatible(String compatible)
    {
        this.compatible = compatible;
    }

    /**
     * Gets the name of the PostgreSQL database, running on the server identified
     * by the serverName property.
     */
    public String getDatabaseName()
    {
        return databaseName;
    }

    /**
     * Sets the name of the PostgreSQL database, running on the server identified
     * by the serverName property. If this is changed, it will only affect
     * future calls to getConnection.
     */
    public void setDatabaseName(String databaseName)
    {
        this.databaseName = databaseName;
    }

    /**
     * Gets a description of this DataSource-ish thing.  Must be customized by
     * subclasses.
     */
    public abstract String getDescription();

    /**
     * Gets the user to connect as by default. If this is not specified, you must
     * use the getConnection method which takes a user and password as parameters.
     */
    public String getUser()
    {
        return user;
    }

    /**
     * Sets the user to connect as by default. If this is not specified, you must
     * use the getConnection method which takes a user and password as parameters.
     * If this is changed, it will only affect future calls to getConnection.
     */
    public void setUser(String user)
    {
        this.user = user;
    }

    /**
     * Gets the password to connect with by default.  If this is not specified but a
     * password is needed to log in, you must use the getConnection method which takes
     * a user and password as parameters.
     */
    public String getPassword()
    {
        return password;
    }

    /**
     * Sets the password to connect with by default.  If this is not specified but a
     * password is needed to log in, you must use the getConnection method which takes
     * a user and password as parameters.  If this is changed, it will only affect
     * future calls to getConnection.
     */
    public void setPassword(String password)
    {
        this.password = password;
    }

    /**
     * Gets the port which the PostgreSQL server is listening on for TCP/IP
     * connections.
     *
     * @return The port, or 0 if the default port will be used.
     */
    public int getPortNumber()
    {
        return portNumber;
    }

    /**
     * Gets the port which the PostgreSQL server is listening on for TCP/IP
     * connections.  Be sure the -i flag is passed to postmaster when PostgreSQL
     * is started. If this is not set, or set to 0, the default port will be used.
     */
    public void setPortNumber(int portNumber)
    {
        this.portNumber = portNumber;
    }

    /**
     * Sets the default threshold for enabling server-side prepare.
     * See {@link org.postgresql.PGConnection#setPrepareThreshold(int)} for details.
     *
     * @param count the number of times a statement object must be reused before server-side
     *   prepare is enabled.
     */
    public void setPrepareThreshold(int count)
    {
        this.prepareThreshold = count;
    }

    /**
     * Gets the default threshold for enabling server-side prepare.
     *
     * @see #setPrepareThreshold(int)
     */
    public int getPrepareThreshold()
    {
        return prepareThreshold;
    }

    public void setUnknownLength(int unknownLength)
    {
        this.unknownLength = unknownLength;
    }

    public int getUnknownLength()
    {
        return unknownLength;
    }

    /**
     * Sets the socket timeout (SOTimeout), in seconds 
     */
    public void setSocketTimeout(int seconds)
    {
        this.socketTimeout = seconds;
    }
    
    /**
     * @return the socket timeout (SOTimeout), in seconds
     */
    public int getSocketTimeout() 
    {
        return this.socketTimeout;
    }


    /**
     * Set whether the connection will be SSL encrypted or not.
     *
     * @param enabled if <CODE>true</CODE>, connect with SSL.
     */
    public void setSsl(boolean enabled)
    {
        this.ssl = enabled;
    }

    /**
     * Gets SSL encryption setting.
     *
     * @return <CODE>true</CODE> if connections will be encrypted with SSL.
     */
    public boolean getSsl()
    {
        return this.ssl;
    }

    /**
     * Set the name of the {@link javax.net.ssl.SSLSocketFactory} to use for connections.
     * Use <CODE>org.postgresql.ssl.NonValidatingFactory</CODE> if you don't want certificate validation.
     *
     * @param classname name of a subclass of <CODE>javax.net.ssl.SSLSocketFactory</CODE> or <CODE>null</CODE> for the default implementation.
     */
    public void setSslfactory(String classname)
    {
        this.sslfactory = classname;
    }

    /**
     * Gets the name of the {@link javax.net.ssl.SSLSocketFactory} used for connections.
     *
     * @return name of the class or <CODE>null</CODE> if the default implementation is used.
     */
    public String getSslfactory()
    {
        return this.sslfactory;
    }

    public void setTcpKeepAlive(boolean enabled)
    {
        tcpKeepAlive = enabled;
    }

    public boolean getTcpKeepAlive()
    {
        return tcpKeepAlive;
    }

    /**
     * Generates a DriverManager URL from the other properties supplied.
     */
    private String getUrl()
    {
        StringBuffer sb = new StringBuffer(100);
        sb.append("jdbc:postgresql://");
        sb.append(serverName);
        if (portNumber != 0) {
            sb.append(":").append(portNumber);
        }
        sb.append("/").append(databaseName);
        sb.append("?loginTimeout=").append(loginTimeout);
        sb.append("&socketTimeout=").append(socketTimeout);
        sb.append("&prepareThreshold=").append(prepareThreshold);
        sb.append("&unknownLength=").append(unknownLength);
        if (ssl) {
            sb.append("&ssl=true");
            if (sslfactory != null) {
                sb.append("&sslfactory=").append(sslfactory);
            }
        }
        sb.append("&tcpkeepalive=").append(tcpKeepAlive);
        if (compatible != null) {
            sb.append("&compatible="+compatible);
        }

        return sb.toString();
    }

    /**
     * Generates a reference using the appropriate object factory.
     */
    protected Reference createReference() {
        return new Reference(
                   getClass().getName(),
                   PGObjectFactory.class.getName(),
                   null);
    }

    public Reference getReference() throws NamingException
    {
        Reference ref = createReference();
        ref.add(new StringRefAddr("serverName", serverName));
        if (portNumber != 0)
        {
            ref.add(new StringRefAddr("portNumber", Integer.toString(portNumber)));
        }
        ref.add(new StringRefAddr("databaseName", databaseName));
        if (user != null)
        {
            ref.add(new StringRefAddr("user", user));
        }
        if (password != null)
        {
            ref.add(new StringRefAddr("password", password));
        }
        
        ref.add(new StringRefAddr("prepareThreshold", Integer.toString(prepareThreshold)));
        ref.add(new StringRefAddr("unknownLength", Integer.toString(unknownLength)));
        ref.add(new StringRefAddr("loginTimeout", Integer.toString(loginTimeout)));
        ref.add(new StringRefAddr("socketTimeout", Integer.toString(socketTimeout)));

        ref.add(new StringRefAddr("ssl", Boolean.toString(ssl)));
        ref.add(new StringRefAddr("sslfactory", sslfactory));

        ref.add(new StringRefAddr("tcpKeepAlive", Boolean.toString(tcpKeepAlive)));
        if (compatible != null)
        {
            ref.add(new StringRefAddr("compatible", compatible));
        }

        return ref;
    }

    protected void writeBaseObject(ObjectOutputStream out) throws IOException
    {
        out.writeObject(serverName);
        out.writeObject(databaseName);
        out.writeObject(user);
        out.writeObject(password);
        out.writeInt(portNumber);
        out.writeInt(prepareThreshold);
        out.writeInt(unknownLength);
        out.writeInt(loginTimeout);
        out.writeInt(socketTimeout);
        out.writeBoolean(ssl);
        out.writeObject(sslfactory);
        out.writeBoolean(tcpKeepAlive);
        out.writeObject(compatible);
    }

    protected void readBaseObject(ObjectInputStream in) throws IOException, ClassNotFoundException
    {
        serverName = (String)in.readObject();
        databaseName = (String)in.readObject();
        user = (String)in.readObject();
        password = (String)in.readObject();
        portNumber = in.readInt();
        prepareThreshold = in.readInt();
        unknownLength = in.readInt();
        loginTimeout = in.readInt();
        socketTimeout = in.readInt();
        ssl = in.readBoolean();
        sslfactory = (String)in.readObject();
        tcpKeepAlive = in.readBoolean();
        compatible = (String)in.readObject();
    }

}