KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > module > database > JDBC


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9  */

10 package org.mmbase.module.database;
11
12 import java.util.*;
13 import java.sql.*;
14 import java.sql.DriverManager JavaDoc;
15
16 import org.mmbase.util.*;
17 import org.mmbase.module.*;
18
19 import org.mmbase.util.logging.*;
20
21 /**
22  * JDBC Module.
23  * The module that provides you access to the loaded JDBC interfaces.
24  * We use this as the base to get multiplexes/pooled JDBC connects.
25  *
26  * @deprecation-used drop reference to {@link JDBCInterface}
27  * @author vpro
28  * @version $Id: JDBC.java,v 1.47.2.3 2006/10/04 15:30:40 michiel Exp $
29  */

30 public class JDBC extends ProcessorModule implements JDBCInterface {
31
32     private static final Logger log = Logging.getLoggerInstance(JDBC.class);
33
34     private Class JavaDoc classdriver;
35     private Driver driver;
36     private String JavaDoc jdbcDriver;
37     private String JavaDoc jdbcURL;
38     private String JavaDoc jdbcHost;
39     private int jdbcPort = -1;
40     private int maxConnections;
41     private int maxQueries;
42     private String JavaDoc jdbcDatabase;
43     private String JavaDoc databaseSupportClass;
44     private DatabaseSupport databaseSupport;
45     private MultiPoolHandler poolHandler;
46     private JDBCProbe probe = null;
47     private String JavaDoc defaultName;
48     private String JavaDoc defaultPassword;
49     private long probeTime;
50     private long maxLifeTime = 120000;
51
52     {
53         addFunction(new GetNodeListFunction("POOLS", PARAMS_PAGEINFO));
54         addFunction(new GetNodeListFunction("CONNECTIONS", PARAMS_PAGEINFO));
55     }
56
57     public void onload() {
58         getProps();
59         getDriver();
60         loadSupport();
61         poolHandler = new MultiPoolHandler(databaseSupport, maxConnections, maxQueries);
62         poolHandler.setMaxLifeTime(maxLifeTime);
63     }
64
65     /*
66      * Initialize the properties and get the driver used
67      */

68     public void init() {
69         // This is now called in onload(), which is called before init()
70
// getProps();
71
probe = new JDBCProbe(this, probeTime);
72         log.info("Module JDBC started (" + this + ")");
73
74     }
75
76     /**
77      * {@inheritDoc}
78      * Reload the properties and driver
79      */

80     public void reload() {
81         getProps();
82
83        /* This doesn't work, have to figure out why
84         try {
85         DriverManager.deregisterDriver(driver);
86         } catch (SQLException e) {
87         debug("reload(): JDBC Module: Can't deregister driver");
88         }
89          */

90         loadSupport();
91         getDriver();
92     }
93
94     public void unload() {
95     }
96     protected void shutdown() {
97         poolHandler.shutdown();
98     }
99
100     /**
101      * Get the driver as specified in our properties
102      */

103     private void getDriver() {
104
105         driver = null;
106         try {
107             classdriver = Class.forName(jdbcDriver);
108
109             // marmaa@vpro.nl:
110
// This is how McKoi's JDBC drivers wants itself
111
// to be registered; should have no effect on other drivers
112
Class.forName(jdbcDriver).newInstance();
113
114             log.service("Loaded JDBC driver: " + jdbcDriver);
115
116         } catch (Exception JavaDoc e) {
117             log.fatal("JDBC driver not found: " + jdbcDriver , e);
118         }
119
120         if (log.isDebugEnabled()) {
121             log.debug("makeUrl(): " + makeUrl());
122         }
123
124         /* Also get the instance to unload it later */
125         for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) {
126             Driver d = (Driver) e.nextElement();
127             if (log.isDebugEnabled()) {
128                 log.debug("Driver " + d);
129             }
130             if (classdriver == d.getClass()) {
131                 driver = d;
132                 break;
133             }
134         }
135         if (driver == null) {
136             log.warn("getDriver(): the jdbc driver specified in jdbc.xml does not match the actual loaded driver ");
137         }
138     }
139
140     /**
141      * Get the driver as specified in our properties
142      */

143     private void loadSupport() {
144         try {
145             Class JavaDoc cl = Class.forName(databaseSupportClass);
146             databaseSupport = (DatabaseSupport)cl.newInstance();
147             databaseSupport.init();
148             log.debug("Loaded load class : " + databaseSupportClass);
149         } catch (Exception JavaDoc e) {
150             log.error("Can't load class : " + databaseSupportClass + " " + e.getMessage(), e);
151         }
152     }
153
154     /**
155      * Get the properties
156      */

157     private void getProps() {
158
159         jdbcDriver = getInitParameter("driver");
160         jdbcURL = getInitParameter("url");
161         jdbcHost = getInitParameter("host");
162         defaultName = getInitParameter("user");
163         defaultPassword = getInitParameter("password");
164         databaseSupportClass = getInitParameter("supportclass");
165         probeTime = 30000;
166         String JavaDoc tmp = getInitParameter("probetime");
167         if (tmp != null) {
168             try {
169                 probeTime = (long) (Float.parseFloat(tmp) * 1000f);
170                 log.info("Set jdbc-probeTime to " + probeTime + " ms");
171             } catch (NumberFormatException JavaDoc e) {
172                 log.warn("Specified probetime is not a invalid float :" + e + "(using default " + (probeTime / 1000) + " s)");
173             }
174         }
175
176
177         tmp = getInitParameter("maxlifetime");
178         if (tmp != null) {
179             try {
180                 maxLifeTime = (long) (Float.parseFloat(tmp) * 1000f);
181                 log.service("Set jdbc max life time to " + maxLifeTime + " ms");
182             } catch (NumberFormatException JavaDoc e) {
183                 log.warn("Specified max life time is not a invalid float :" + e + "(using default " + (maxLifeTime / 1000) + " s)");
184             }
185         }
186
187         /*
188         log.trace("jdbcDriver="+jdbcDriver +
189                   "\njdbcURL="+jdbcURL +
190                   "\njdbcHost="+jdbcHost +
191                   "\ndefaultName="+defaultName +
192                   "\ndefaultPassword="+defaultPassword +
193                   "\ndatabaseSupportClass="+databaseSupportClass);
194         */

195
196         if (defaultName == null) {
197             defaultName = "wwwtech";
198             log.warn("name was not set, using default: '" + defaultName +"'");
199         }
200         if (defaultPassword == null) {
201             defaultPassword="xxxxxx";
202             log.warn("name was not set, using default: '" + defaultPassword +"'");
203         }
204         tmp = getInitParameter("port");
205         if (tmp != null) {
206             try {
207                 jdbcPort=Integer.parseInt(getInitParameter("port"));
208             } catch (NumberFormatException JavaDoc e) {
209                 jdbcPort = 0;
210                 log.warn("portnumber was not set or a invalid integer :" + e + "(using default " + jdbcPort + ")");
211             }
212         }
213         try {
214             maxConnections=Integer.parseInt(getInitParameter("connections"));
215         } catch (Exception JavaDoc e) {
216             maxConnections = 8;
217             log.warn("connections was not set or a invalid integer :" + e + "(using default " + maxConnections + ")");
218         }
219         try {
220             maxQueries = Integer.parseInt(getInitParameter("queries"));
221         } catch (Exception JavaDoc f) {
222             try {
223                 maxQueries = Integer.parseInt(getInitParameter("querys")); //fall back backward compatible
224
} catch (Exception JavaDoc e) {
225                 maxQueries = 500;
226                 log.warn("querys was not set or a invalid integer :" + e + "(using default " + maxQueries + ")");
227             }
228         }
229         jdbcDatabase = getInitParameter("database");
230         if (databaseSupportClass == null || databaseSupportClass.length() == 0) {
231             databaseSupportClass="org.mmbase.module.database.DatabaseSupportShim";
232             log.warn("database supportclass was not known, using default: " + databaseSupportClass);
233         }
234     }
235
236     /**
237      * Routine build the url to give to the DriverManager
238      * to open the connection. This way a servlet/module
239      * doesn't need to care about what database it talks to.
240      * @see java.sql.DriverManager#getConnection(java.lang.String)
241      */

242     public String JavaDoc makeUrl() {
243         return makeUrl(jdbcHost, jdbcPort, jdbcDatabase);
244     }
245
246     /**
247      * Routine build the url to give to the DriverManager
248      * to open the connection. This way a servlet/module
249      * doesn't need to care about what database it talks to.
250      * @see java.sql.DriverManager#getConnection(java.lang.String)
251      */

252     public String JavaDoc makeUrl(String JavaDoc dbm) {
253         return makeUrl(jdbcHost, jdbcPort, dbm);
254     }
255
256     /**
257      * Routine build the url to give to the DriverManager
258      * to open the connection. This way a servlet/module
259      * doesn't need to care about what database it talks to.
260      * @see java.sql.DriverManager#getConnection(java.lang.String)
261      */

262     public String JavaDoc makeUrl(String JavaDoc host,String JavaDoc dbm) {
263         return makeUrl(host, jdbcPort, dbm);
264     }
265
266     /**
267      * Routine build the url to give to the DriverManager
268      * to open the connection. This way a servlet/module
269      * doesn't need to care about what database it talks to.
270      * @see java.sql.DriverManager#getConnection(java.lang.String)
271      */

272     public String JavaDoc makeUrl(String JavaDoc host, int port, String JavaDoc dbm) {
273         String JavaDoc url = jdbcURL;
274         // $HOST $DBM $PORT
275

276         url = url.replaceAll("\\$DBM", dbm);
277         url = url.replaceAll("\\$HOST", host);
278         url = url.replaceAll("\\$PORT", "" + port);
279
280         return url;
281     }
282
283     /**
284      * @javadoc
285      */

286     public MultiConnection getConnection(String JavaDoc url, String JavaDoc name, String JavaDoc password) throws SQLException {
287         return poolHandler.getConnection(url, name, password);
288     }
289
290     /**
291      * @javadoc
292      */

293     public MultiConnection getConnection(String JavaDoc url) throws SQLException {
294         return poolHandler.getConnection(url, defaultName, defaultPassword);
295     }
296
297     /**
298      * @javadoc
299      */

300     public Connection getDirectConnection(String JavaDoc url,String JavaDoc name,String JavaDoc password) throws SQLException {
301         return DriverManager.getConnection(url, name, password);
302     }
303
304     /**
305      * @javadoc
306      */

307     public Connection getDirectConnection(String JavaDoc url) throws SQLException {
308         return DriverManager.getConnection(url, defaultName, defaultPassword);
309     }
310
311     /**
312      * @javadoc
313      */

314     public synchronized void checkTime() {
315         try {
316             if (poolHandler != null) poolHandler.checkTime();
317         } catch(Exception JavaDoc e) {
318             log.error("could not check the time: " + e, e);
319         }
320     }
321
322     /**
323      * User interface stuff
324      * @javadoc
325      */

326     public Vector getList(PageInfo sp, StringTagger tagger, String JavaDoc value) {
327         String JavaDoc line = Strip.DoubleQuote(value,Strip.BOTH);
328         StringTokenizer tok = new StringTokenizer(line,"-\n\r");
329         if (tok.hasMoreTokens()) {
330             String JavaDoc cmd = tok.nextToken();
331             if (cmd.equals("POOLS")) return listPools(tagger);
332             if (cmd.equals("CONNECTIONS")) return listConnections(tagger);
333         }
334         return null;
335     }
336
337     // Strips senssitive info (such as password and username) from the
338
// database name
339
private String JavaDoc stripSensistive(String JavaDoc name) {
340         // strip either after the first '?', or the first ',',
341
// whichever comes first
342
int i = name.indexOf('?');
343         int j = name.indexOf(',');
344         if ((i > j) && (j != -1)) i = j;
345         if (i !=- 1) {
346             return name.substring(0,i);
347         } else {
348             return name;
349         }
350     }
351
352     /**
353      * @javadoc
354      */

355     public Vector listPools(StringTagger tagger) {
356         Vector results = new Vector();
357         for (Iterator i = poolHandler.keySet().iterator(); i.hasNext();) {
358             String JavaDoc name = (String JavaDoc) i.next();
359             MultiPool pool = poolHandler.get(name);
360             results.addElement(stripSensistive(name));
361             results.addElement("" + pool.getSize());
362             results.addElement("" + pool.getTotalConnectionsCreated());
363         }
364         tagger.setValue("ITEMS", "3");
365         return results;
366     }
367
368     /**
369      * @javadoc
370      */

371     public Vector listConnections(StringTagger tagger) {
372         Vector results = new Vector();
373         for (Iterator i = poolHandler.keySet().iterator(); i.hasNext();) {
374             String JavaDoc name= (String JavaDoc) i.next();
375             MultiPool pool = poolHandler.get(name);
376             for (Iterator f = pool.getBusyPool(); f.hasNext();) {
377                 MultiConnection realcon=(MultiConnection)f.next();
378                 results.addElement(stripSensistive(name.substring(name.lastIndexOf('/')+1)));
379                 results.addElement(realcon.getStateString());
380                 results.addElement("" + realcon.getLastSQL());
381                 results.addElement("" + realcon.getUsage());
382                 //results.addElement(""+pool.getStatementsCreated(realcon));
383
}
384             for (Iterator f=pool.getPool();f.hasNext();) {
385                 MultiConnection realcon=(MultiConnection)f.next();
386                 results.addElement(stripSensistive(name.substring(name.lastIndexOf('/')+1)));
387                 results.addElement(realcon.getStateString());
388                 results.addElement("" + realcon.getLastSQL());
389                 results.addElement("" + realcon.getUsage());
390                 //results.addElement(""+pool.getStatementsCreated(realcon));
391
}
392         }
393         tagger.setValue("ITEMS", "4");
394         return results;
395     }
396
397     /**
398      * @javadoc
399      */

400     public String JavaDoc getUser() {
401         return defaultName;
402     }
403
404     /**
405      * @javadoc
406      */

407     public String JavaDoc getPassword() {
408         return defaultPassword;
409     }
410
411     /**
412      * @javadoc
413      */

414     public String JavaDoc getDatabaseName() {
415         return getInitParameter("database");
416     }
417
418     /**
419      * Give some info about the jdbc connection
420      * @return a <code>String</code> whith some information about the connection
421      */

422     public String JavaDoc toString() {
423         return "host: '" + jdbcHost + "' port: '" + jdbcPort + "' database: '" + jdbcDatabase + "' user: '" + defaultName + "'" + (driver != null ? " driver: " + driver.getClass().getName() + "'" : "") + " max life time: " + maxLifeTime + " ms probe time: " + probeTime + " ms";
424      }
425 }
426
Popular Tags