KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > jdc > JDCConnection


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oņa, 107 1š2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.jdc;
34
35 import java.util.Map JavaDoc;
36 import java.util.Date JavaDoc;
37
38 import java.sql.SQLException JavaDoc;
39 import java.sql.SQLWarning JavaDoc;
40 import java.sql.DatabaseMetaData JavaDoc;
41 import java.sql.Statement JavaDoc;
42 import java.sql.PreparedStatement JavaDoc;
43 import java.sql.CallableStatement JavaDoc;
44 import java.sql.ResultSet JavaDoc;
45 import java.sql.Connection JavaDoc;
46 import java.sql.Savepoint JavaDoc;
47
48 import com.knowgate.debug.DebugFile;
49
50 /**
51  * JDBC Connection Wrapper
52  * @author Sergio Montoro Ten
53  * @version 2.2
54  */

55 public final class JDCConnection implements Connection JavaDoc {
56
57     public static final short IdClass = 100;
58
59     public static final int DBMS_GENERIC = 0;
60     public static final int DBMS_MYSQL = 1;
61     public static final int DBMS_POSTGRESQL = 2;
62     public static final int DBMS_MSSQL = 3;
63     public static final int DBMS_ORACLE = 5;
64
65     private static final int DBMS_UNKNOWN = -1;
66     private static final int DBMS_SYBASE = 4;
67     private static final int DBMS_B2 = 6;
68     private static final int DBMS_INFORMIX = 7;
69     private static final int DBMS_CLOUDSCAPE = 8;
70
71     private JDCConnectionPool pool;
72     private Connection JavaDoc conn;
73     private boolean inuse;
74     private long timestamp;
75     private int dbms;
76     private String JavaDoc name;
77     private String JavaDoc schema;
78
79     private static final String JavaDoc DBMSNAME_MSSQL = "Microsoft SQL Server";
80     private static final String JavaDoc DBMSNAME_POSTGRESQL = "PostgreSQL";
81     private static final String JavaDoc DBMSNAME_ORACLE = "Oracle";
82     private static final String JavaDoc DBMSNAME_MYSQL = "MySQL";
83
84     public JDCConnection(Connection JavaDoc conn, JDCConnectionPool pool, String JavaDoc schemaname) {
85         this.dbms = DBMS_UNKNOWN;
86         this.conn=conn;
87         this.pool=pool;
88         this.inuse=false;
89         this.timestamp=0;
90         this.name = null;
91         this.schema=schemaname;
92     }
93
94     public JDCConnection(Connection JavaDoc conn, JDCConnectionPool pool) {
95         this.dbms = DBMS_UNKNOWN;
96         this.conn=conn;
97         this.pool=pool;
98         this.inuse=false;
99         this.timestamp=0;
100         this.name = null;
101         this.schema=null;
102     }
103
104     public boolean lease(String JavaDoc sConnectionName) {
105        if (inuse) {
106            return false;
107        } else {
108           inuse=true;
109           name = sConnectionName;
110           timestamp=System.currentTimeMillis();
111           return true;
112        }
113     }
114
115     public boolean validate() {
116       boolean bValid;
117
118       if (DebugFile.trace) {
119         DebugFile.writeln("Begin JDCConnection.validate()");
120         DebugFile.incIdent();
121       }
122       try {
123         conn.getMetaData();
124         bValid = true;
125       } catch (Exception JavaDoc e) {
126         DebugFile.writeln(new Date JavaDoc().toString() + " " + e.getMessage());
127         bValid = false;
128       }
129
130       if (DebugFile.trace) {
131         DebugFile.decIdent();
132         DebugFile.writeln("End JDCConnection.validate()");
133       }
134
135       return bValid;
136     }
137
138     public boolean inUse() {
139         return inuse;
140     }
141
142     public JDCConnectionPool getPool() {
143         return pool;
144     }
145
146     public long getLastUse() {
147         return timestamp;
148     }
149
150     public String JavaDoc getName() {
151         return name;
152     }
153
154     public int getDataBaseProduct() throws SQLException JavaDoc {
155       DatabaseMetaData JavaDoc mdat;
156       String JavaDoc prod;
157
158       if (DBMS_UNKNOWN==dbms) {
159         try {
160           mdat = conn.getMetaData();
161           prod = mdat.getDatabaseProductName();
162
163           if (prod.equals(DBMSNAME_MSSQL))
164             dbms = DBMS_MSSQL;
165           else if (prod.equals(DBMSNAME_POSTGRESQL))
166             dbms = DBMS_POSTGRESQL;
167           else if (prod.equals(DBMSNAME_ORACLE))
168             dbms = DBMS_ORACLE;
169           else if (prod.equals(DBMSNAME_MYSQL))
170             dbms = DBMS_MYSQL;
171           else
172             dbms = DBMS_GENERIC;
173         }
174         catch (NullPointerException JavaDoc npe) {
175           if (DebugFile.trace) DebugFile.writeln("NullPointerException at JDCConnection.getDataBaseProduct()");
176           dbms = DBMS_GENERIC;
177         }
178       }
179       return dbms;
180     }
181
182     public String JavaDoc getSchemaName() throws SQLException JavaDoc {
183       String JavaDoc sname;
184
185       if (null==schema) {
186         DatabaseMetaData JavaDoc mdat = conn.getMetaData();
187         ResultSet JavaDoc rset = mdat.getSchemas();
188
189         if (rset.next())
190           sname = rset.getString(1);
191         else
192           sname = null;
193
194         rset.close();
195       }
196       else
197         sname = schema;
198
199       return sname;
200     }
201
202    public void setSchemaName(String JavaDoc sname) {
203      schema = sname;
204    }
205
206    public void close() throws SQLException JavaDoc {
207       if (DebugFile.trace) {
208         DebugFile.writeln("Begin JDCConnection.close()");
209         DebugFile.incIdent();
210       }
211
212       if (pool==null) {
213         inuse = false;
214         name = null;
215         conn.close();
216       }
217       else {
218         pool.returnConnection(this);
219       }
220
221       if (DebugFile.trace) {
222         DebugFile.decIdent();
223         DebugFile.writeln("End JDCConnection.close()");
224       }
225     }
226
227     public void close(String JavaDoc sCaller) throws SQLException JavaDoc {
228       if (DebugFile.trace) {
229         DebugFile.writeln("Begin JDCConnection.close("+sCaller+")");
230         DebugFile.incIdent();
231       }
232       if (pool==null) {
233         inuse = false;
234         name = null;
235         conn.close();
236       }
237       else {
238         pool.returnConnection(this, sCaller);
239       }
240
241       if (DebugFile.trace) {
242         DebugFile.decIdent();
243         DebugFile.writeln("End JDCConnection.close("+sCaller+")");
244       }
245     }
246
247     protected void expireLease() {
248         inuse=false;
249         name =null ;
250     }
251
252     protected Connection JavaDoc getConnection() {
253         return conn;
254     }
255
256     public Statement JavaDoc createStatement(int i, int j) throws SQLException JavaDoc {
257         return conn.createStatement(i,j);
258     }
259
260     public Statement JavaDoc createStatement(int i, int j, int k) throws SQLException JavaDoc {
261         return conn.createStatement(i,j,k);
262     }
263
264     public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql) throws SQLException JavaDoc {
265         return conn.prepareStatement(sql);
266     }
267
268     public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql, String JavaDoc[] params) throws SQLException JavaDoc {
269         return conn.prepareStatement(sql,params);
270     }
271
272     public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql, int i) throws SQLException JavaDoc {
273         return conn.prepareStatement(sql,i);
274     }
275
276     public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql, int i, int j) throws SQLException JavaDoc {
277         return conn.prepareStatement(sql,i,j);
278     }
279
280     public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql, int i, int j, int k) throws SQLException JavaDoc {
281         return conn.prepareStatement(sql,i,j,k);
282     }
283
284     public PreparedStatement JavaDoc prepareStatement(String JavaDoc sql, int[] params) throws SQLException JavaDoc {
285         return conn.prepareStatement(sql,params);
286     }
287
288     public CallableStatement JavaDoc prepareCall(String JavaDoc sql) throws SQLException JavaDoc {
289         return conn.prepareCall(sql);
290     }
291
292     public CallableStatement JavaDoc prepareCall(String JavaDoc sql, int i, int j) throws SQLException JavaDoc {
293         return conn.prepareCall(sql, i , j);
294     }
295
296     public CallableStatement JavaDoc prepareCall(String JavaDoc sql, int i, int j, int k) throws SQLException JavaDoc {
297         return conn.prepareCall(sql, i , j, k);
298     }
299
300     public Statement JavaDoc createStatement() throws SQLException JavaDoc {
301         return conn.createStatement();
302     }
303
304     public String JavaDoc nativeSQL(String JavaDoc sql) throws SQLException JavaDoc {
305         return conn.nativeSQL(sql);
306     }
307
308     public void setAutoCommit(boolean autoCommit) throws SQLException JavaDoc {
309         conn.setAutoCommit(autoCommit);
310     }
311
312     public boolean getAutoCommit() throws SQLException JavaDoc {
313         return conn.getAutoCommit();
314     }
315
316     public int getHoldability() throws SQLException JavaDoc {
317         return conn.getHoldability();
318     }
319
320     public void setHoldability(int h) throws SQLException JavaDoc {
321         conn.setHoldability(h);
322     }
323
324     public Savepoint JavaDoc setSavepoint() throws SQLException JavaDoc {
325         return conn.setSavepoint();
326     }
327
328     public Savepoint JavaDoc setSavepoint(String JavaDoc s) throws SQLException JavaDoc {
329         return conn.setSavepoint(s);
330     }
331
332     public void commit() throws SQLException JavaDoc {
333         conn.commit();
334     }
335
336     public void rollback() throws SQLException JavaDoc {
337         conn.rollback();
338     }
339
340     public void rollback(Savepoint JavaDoc p) throws SQLException JavaDoc {
341         conn.rollback(p);
342     }
343
344     public boolean isClosed() throws SQLException JavaDoc {
345         return conn.isClosed();
346     }
347
348     public DatabaseMetaData JavaDoc getMetaData() throws SQLException JavaDoc {
349         return conn.getMetaData();
350     }
351
352     public void setReadOnly(boolean readOnly) throws SQLException JavaDoc {
353         conn.setReadOnly(readOnly);
354     }
355
356     public boolean isReadOnly() throws SQLException JavaDoc {
357         return conn.isReadOnly();
358     }
359
360     public void setCatalog(String JavaDoc catalog) throws SQLException JavaDoc {
361         conn.setCatalog(catalog);
362     }
363
364     public String JavaDoc getCatalog() throws SQLException JavaDoc {
365         return conn.getCatalog();
366     }
367
368     public void setTransactionIsolation(int level) throws SQLException JavaDoc {
369         conn.setTransactionIsolation(level);
370     }
371
372     public int getTransactionIsolation() throws SQLException JavaDoc {
373         return conn.getTransactionIsolation();
374     }
375
376     public Map JavaDoc getTypeMap() throws SQLException JavaDoc {
377       return conn.getTypeMap();
378     }
379
380     public void setTypeMap(Map JavaDoc typemap) throws SQLException JavaDoc {
381       conn.setTypeMap(typemap);
382     }
383
384     public SQLWarning JavaDoc getWarnings() throws SQLException JavaDoc {
385         return conn.getWarnings();
386     }
387
388     public void clearWarnings() throws SQLException JavaDoc {
389         conn.clearWarnings();
390     }
391
392     public void releaseSavepoint(Savepoint JavaDoc p) throws SQLException JavaDoc {
393         conn.releaseSavepoint(p);
394     }
395
396     /**
397      * Checks if an object exists at database
398      * Checking is done directly against database catalog tables,
399      * if current user does not have enought priviledges for reading
400      * database catalog tables methos may fail or return a wrong result.
401      * @param sObjectName Objeto name
402      * @param sObjectType Objeto type
403      * C = CHECK constraint
404      * D = Default or DEFAULT constraint
405      * F = FOREIGN KEY constraint
406      * L = Log
407      * P = Stored procedure
408      * PK = PRIMARY KEY constraint (type is K)
409      * RF = Replication filter stored procedure
410      * S = System table
411      * TR = Trigger
412      * U = User table
413      * UQ = UNIQUE constraint (type is K)
414      * V = View
415      * X = Extended stored procedure
416      * @return <b>true</b> if object exists, <b>false</b> otherwise
417      * @throws SQLException
418      * @throws UnsupportedOperationException If current database management system is not supported for this method
419      */

420
421     public boolean exists(String JavaDoc sObjectName, String JavaDoc sObjectType)
422       throws SQLException JavaDoc, UnsupportedOperationException JavaDoc {
423       boolean bRetVal;
424       PreparedStatement JavaDoc oStmt;
425       ResultSet JavaDoc oRSet;
426
427       if (DebugFile.trace) {
428         DebugFile.writeln("Begin JDCConnection.exists([Connection], " + sObjectName + ", " + sObjectType + ")");
429         DebugFile.incIdent();
430       }
431
432       switch (this.getDataBaseProduct()) {
433
434         case JDCConnection.DBMS_MSSQL:
435           if (DebugFile.trace)
436             DebugFile.writeln ("Connection.prepareStatement(SELECT id FROM sysobjects WHERE name='" + sObjectName + "' AND xtype='" + sObjectType + "' OPTION (FAST 1))");
437
438           oStmt = this.prepareStatement("SELECT id FROM sysobjects WHERE name=? AND xtype=? OPTION (FAST 1)", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
439           oStmt.setString(1, sObjectName);
440           oStmt.setString(2, sObjectType);
441           oRSet = oStmt.executeQuery();
442           bRetVal = oRSet.next();
443           oRSet.close();
444           oStmt.close();
445           break;
446
447         case JDCConnection.DBMS_POSTGRESQL:
448           if (DebugFile.trace)
449             DebugFile.writeln ("Conenction.prepareStatement(SELECT relname FROM pg_class WHERE relname='" + sObjectName + "')");
450
451           oStmt = this.prepareStatement("SELECT tablename FROM pg_tables WHERE tablename=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
452           oStmt.setString(1, sObjectName);
453           oRSet = oStmt.executeQuery();
454           bRetVal = oRSet.next();
455           oRSet.close();
456           oStmt.close();
457           break;
458
459         case JDCConnection.DBMS_ORACLE:
460           if (DebugFile.trace)
461             DebugFile.writeln ("Conenction.prepareStatement(SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME='" + sObjectName + "')");
462
463           oStmt = this.prepareStatement("SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
464           oStmt.setString(1, sObjectName.toUpperCase());
465           oRSet = oStmt.executeQuery();
466           bRetVal = oRSet.next();
467           oRSet.close();
468           oStmt.close();
469           break;
470
471         case JDCConnection.DBMS_MYSQL:
472           if (DebugFile.trace)
473             DebugFile.writeln ("Conenction.prepareStatement(SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_name='"+sObjectName+"')");
474
475           oStmt = this.prepareStatement("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_name=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
476           oStmt.setString(1, sObjectName);
477           oRSet = oStmt.executeQuery();
478           bRetVal = oRSet.next();
479           bRetVal = false;
480           oRSet.close();
481           oStmt.close();
482           break;
483
484         default:
485           throw new UnsupportedOperationException JavaDoc ("Unsupported DBMS");
486       } // end switch()
487

488       if (DebugFile.trace) {
489         DebugFile.decIdent();
490         DebugFile.writeln("End JDCConnection.exists() : " + String.valueOf(bRetVal));
491       }
492
493       return bRetVal;
494     } // exists()
495

496     /**
497      * <p>Get operating system process identifier for this connection</p>
498      * @return String For PostgreSQL the id of the UNIX process attending this connection.
499      * For Oracle a Session Id.
500      * @throws SQLException
501      * @since 2.2
502      */

503     public String JavaDoc pid() throws SQLException JavaDoc {
504       Statement JavaDoc oStmt;
505       ResultSet JavaDoc oRSet;
506       String JavaDoc sPId = null;
507       switch (getDataBaseProduct()) {
508         case DBMS_POSTGRESQL:
509           oStmt = createStatement();
510           oRSet = oStmt.executeQuery("SELECT pg_backend_pid()");
511           if (oRSet.next())
512             sPId = String.valueOf(oRSet.getInt(1));
513           oRSet.close();
514           oStmt.close();
515           break;
516         case DBMS_ORACLE:
517           oStmt = createStatement();
518           oRSet = oStmt.executeQuery("SELECT SYS_CONTEXT('USERENV','SESIONID') FROM DUAL");
519           if (oRSet.next())
520             sPId = oRSet.getString(1);
521           oRSet.close();
522           oStmt.close();
523           break;
524       }
525       return sPId;
526     } // pid
527
}
528
Popular Tags