KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mysql > jdbc > NonRegisteringDriver


1 /*
2    Copyright (C) 2002 MySQL AB
3
4       This program is free software; you can redistribute it and/or modify
5       it under the terms of the GNU General Public License as published by
6       the Free Software Foundation; either version 2 of the License, or
7       (at your option) any later version.
8
9       This program is distributed in the hope that it will be useful,
10       but WITHOUT ANY WARRANTY; without even the implied warranty of
11       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12       GNU General Public License for more details.
13
14       You should have received a copy of the GNU General Public License
15       along with this program; if not, write to the Free Software
16       Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
18  */

19 package com.mysql.jdbc;
20
21 import java.sql.DriverPropertyInfo JavaDoc;
22 import java.sql.SQLException JavaDoc;
23
24 import java.util.Properties JavaDoc;
25 import java.util.StringTokenizer JavaDoc;
26
27
28 /**
29  * The Java SQL framework allows for multiple database drivers. Each driver
30  * should supply a class that implements the Driver interface
31  *
32  * <p>
33  * The DriverManager will try to load as many drivers as it can find and then
34  * for any given connection request, it will ask each driver in turn to try to
35  * connect to the target URL.
36  * </p>
37  *
38  * <p>
39  * It is strongly recommended that each Driver class should be small and
40  * standalone so that the Driver class can be loaded and queried without
41  * bringing in vast quantities of supporting code.
42  * </p>
43  *
44  * <p>
45  * When a Driver class is loaded, it should create an instance of itself and
46  * register it with the DriverManager. This means that a user can load and
47  * register a driver by doing Class.forName("foo.bah.Driver")
48  * </p>
49  *
50  * @author Mark Matthews
51  * @version $Id: NonRegisteringDriver.java,v 1.1.2.10 2004/02/13 22:31:53 mmatthew Exp $
52  *
53  * @see org.gjt.mm.mysql.Connection
54  * @see java.sql.Driver
55  */

56 public class NonRegisteringDriver implements java.sql.Driver JavaDoc {
57     /** Should the driver generate debugging output? */
58     public static final boolean DEBUG = false;
59
60     /** Should the driver generate method-call traces? */
61     public static final boolean TRACE = false;
62
63     /**
64      * Construct a new driver and register it with DriverManager
65      *
66      * @throws java.sql.SQLException if a database error occurs.
67      */

68     public NonRegisteringDriver() throws java.sql.SQLException JavaDoc {
69         // Required for Class.forName().newInstance()
70
}
71
72     /**
73      * Gets the drivers major version number
74      *
75      * @return the drivers major version number
76      */

77     public int getMajorVersion() {
78         return getMajorVersionInternal();
79     }
80
81     /**
82      * Get the drivers minor version number
83      *
84      * @return the drivers minor version number
85      */

86     public int getMinorVersion() {
87         return getMinorVersionInternal();
88     }
89
90     /**
91      * The getPropertyInfo method is intended to allow a generic GUI tool to
92      * discover what properties it should prompt a human for in order to get
93      * enough information to connect to a database.
94      *
95      * <p>
96      * Note that depending on the values the human has supplied so far,
97      * additional values may become necessary, so it may be necessary to
98      * iterate through several calls to getPropertyInfo
99      * </p>
100      *
101      * @param url the Url of the database to connect to
102      * @param info a proposed list of tag/value pairs that will be sent on
103      * connect open.
104      *
105      * @return An array of DriverPropertyInfo objects describing possible
106      * properties. This array may be an empty array if no properties
107      * are required
108      *
109      * @exception java.sql.SQLException if a database-access error occurs
110      *
111      * @see java.sql.Driver#getPropertyInfo
112      */

113     public DriverPropertyInfo JavaDoc[] getPropertyInfo(String JavaDoc url, Properties JavaDoc info)
114         throws java.sql.SQLException JavaDoc {
115         if (info == null) {
116             info = new Properties JavaDoc();
117         }
118
119         if ((url != null) && url.startsWith("jdbc:mysql://")) {
120             info = parseURL(url, info);
121         }
122
123         DriverPropertyInfo JavaDoc hostProp = new DriverPropertyInfo JavaDoc("HOST",
124                 info.getProperty("HOST"));
125         hostProp.required = true;
126         hostProp.description = "Hostname of MySQL Server";
127
128         DriverPropertyInfo JavaDoc portProp = new DriverPropertyInfo JavaDoc("PORT",
129                 info.getProperty("PORT", "3306"));
130         portProp.required = false;
131         portProp.description = "Port number of MySQL Server";
132
133         DriverPropertyInfo JavaDoc dbProp = new DriverPropertyInfo JavaDoc("DBNAME",
134                 info.getProperty("DBNAME"));
135         dbProp.required = false;
136         dbProp.description = "Database name";
137
138         DriverPropertyInfo JavaDoc userProp = new DriverPropertyInfo JavaDoc("user",
139                 info.getProperty("user"));
140         userProp.required = true;
141         userProp.description = "Username to authenticate as";
142
143         DriverPropertyInfo JavaDoc passwordProp = new DriverPropertyInfo JavaDoc("password",
144                 info.getProperty("password"));
145         passwordProp.required = true;
146         passwordProp.description = "Password to use for authentication";
147
148         DriverPropertyInfo JavaDoc autoReconnect = new DriverPropertyInfo JavaDoc("autoReconnect",
149                 info.getProperty("autoReconnect", "false"));
150         autoReconnect.required = false;
151         autoReconnect.choices = new String JavaDoc[] { "true", "false" };
152         autoReconnect.description = "Should the driver try to re-establish bad connections?";
153
154         DriverPropertyInfo JavaDoc maxReconnects = new DriverPropertyInfo JavaDoc("maxReconnects",
155                 info.getProperty("maxReconnects", "3"));
156         maxReconnects.required = false;
157         maxReconnects.description = "Maximum number of reconnects to attempt if autoReconnect is true";
158         ;
159
160         DriverPropertyInfo JavaDoc initialTimeout = new DriverPropertyInfo JavaDoc("initialTimeout",
161                 info.getProperty("initialTimeout", "2"));
162         initialTimeout.required = false;
163         initialTimeout.description = "Initial timeout (seconds) to wait between failed connections";
164
165         DriverPropertyInfo JavaDoc profileSql = new DriverPropertyInfo JavaDoc("profileSql",
166                 info.getProperty("profileSql", "false"));
167         profileSql.required = false;
168         profileSql.choices = new String JavaDoc[] { "true", "false" };
169         profileSql.description = "Trace queries and their execution/fetch times on STDERR (true/false) defaults to false";
170         ;
171
172         DriverPropertyInfo JavaDoc socketTimeout = new DriverPropertyInfo JavaDoc("socketTimeout",
173                 info.getProperty("socketTimeout", "0"));
174         socketTimeout.required = false;
175         socketTimeout.description = "Timeout on network socket operations (0 means no timeout)";
176         ;
177
178         DriverPropertyInfo JavaDoc useSSL = new DriverPropertyInfo JavaDoc("useSSL",
179                 info.getProperty("useSSL", "false"));
180         useSSL.required = false;
181         useSSL.choices = new String JavaDoc[] { "true", "false" };
182         useSSL.description = "Use SSL when communicating with the server?";
183         ;
184
185         DriverPropertyInfo JavaDoc useCompression = new DriverPropertyInfo JavaDoc("useCompression",
186                 info.getProperty("useCompression", "false"));
187         useCompression.required = false;
188         useCompression.choices = new String JavaDoc[] { "true", "false" };
189         useCompression.description = "Use zlib compression when communicating with the server?";
190         ;
191
192         DriverPropertyInfo JavaDoc paranoid = new DriverPropertyInfo JavaDoc("paranoid",
193                 info.getProperty("paranoid", "false"));
194         paranoid.required = false;
195         paranoid.choices = new String JavaDoc[] { "true", "false" };
196         paranoid.description = "Expose sensitive information in error messages and clear "
197             + "data structures holding sensitiven data when possible?";
198         ;
199
200         DriverPropertyInfo JavaDoc useHostsInPrivileges = new DriverPropertyInfo JavaDoc("useHostsInPrivileges",
201                 info.getProperty("useHostsInPrivileges", "true"));
202         useHostsInPrivileges.required = false;
203         useHostsInPrivileges.choices = new String JavaDoc[] { "true", "false" };
204         useHostsInPrivileges.description = "Add '@hostname' to users in DatabaseMetaData.getColumn/TablePrivileges()";
205         ;
206
207         DriverPropertyInfo JavaDoc interactiveClient = new DriverPropertyInfo JavaDoc("interactiveClient",
208                 info.getProperty("interactiveClient", "false"));
209         interactiveClient.required = false;
210         interactiveClient.choices = new String JavaDoc[] { "true", "false" };
211         interactiveClient.description = "Set the CLIENT_INTERACTIVE flag, which tells MySQL "
212             + "to timeout connections based on INTERACTIVE_TIMEOUT instead of WAIT_TIMEOUT";
213         ;
214
215         DriverPropertyInfo JavaDoc useTimezone = new DriverPropertyInfo JavaDoc("useTimezone",
216                 info.getProperty("useTimezone", "false"));
217         useTimezone.required = false;
218         useTimezone.choices = new String JavaDoc[] { "true", "false" };
219         useTimezone.description = "Convert time/date types between client and server timezones";
220
221         DriverPropertyInfo JavaDoc serverTimezone = new DriverPropertyInfo JavaDoc("serverTimezone",
222                 info.getProperty("serverTimezone", ""));
223         serverTimezone.required = false;
224         serverTimezone.description = "Override detection/mapping of timezone. Used when timezone from server doesn't map to Java timezone";
225
226         DriverPropertyInfo JavaDoc connectTimeout = new DriverPropertyInfo JavaDoc("connectTimeout",
227                 info.getProperty("connectTimeout", "0"));
228         connectTimeout.required = false;
229         connectTimeout.description = "Timeout for socket connect (in milliseconds), with 0 being no timeout. Only works on JDK-1.4 or newer. Defaults to '0'.";
230
231         DriverPropertyInfo JavaDoc queriesBeforeRetryMaster = new DriverPropertyInfo JavaDoc("queriesBeforeRetryMaster",
232                 info.getProperty("queriesBeforeRetryMaster", "50"));
233         queriesBeforeRetryMaster.required = false;
234         queriesBeforeRetryMaster.description = "Number of queries to issue before falling back to master when failed over "
235             + "(when using multi-host failover). Whichever condition is met first, "
236             + "'queriesBeforeRetryMaster' or 'secondsBeforeRetryMaster' will cause an "
237             + "attempt to be made to reconnect to the master. Defaults to 50.";
238         ;
239
240         DriverPropertyInfo JavaDoc secondsBeforeRetryMaster = new DriverPropertyInfo JavaDoc("secondsBeforeRetryMaster",
241                 info.getProperty("secondsBeforeRetryMaster", "30"));
242         secondsBeforeRetryMaster.required = false;
243         secondsBeforeRetryMaster.description = "How long should the driver wait, when failed over, before attempting "
244             + "to reconnect to the master server? Whichever condition is met first, "
245             + "'queriesBeforeRetryMaster' or 'secondsBeforeRetryMaster' will cause an "
246             + "attempt to be made to reconnect to the master. Time in seconds, defaults to 30";
247
248         DriverPropertyInfo JavaDoc useStreamLengthsInPrepStmts = new DriverPropertyInfo JavaDoc("useStreamLengthsInPrepStmts",
249                 info.getProperty("useStreamLengthsInPrepStmts", "true"));
250         useStreamLengthsInPrepStmts.required = false;
251         useStreamLengthsInPrepStmts.choices = new String JavaDoc[] { "true", "false" };
252         useStreamLengthsInPrepStmts.description = "Honor stream length parameter in "
253             + "PreparedStatement/ResultSet.setXXXStream() method calls (defaults to 'true')";
254
255         DriverPropertyInfo JavaDoc continueBatchOnError = new DriverPropertyInfo JavaDoc("continueBatchOnError",
256                 info.getProperty("continueBatchOnError", "true"));
257         continueBatchOnError.required = false;
258         continueBatchOnError.choices = new String JavaDoc[] { "true", "false" };
259         continueBatchOnError.description = "Should the driver continue processing batch commands if "
260             + "one statement fails. The JDBC spec allows either way (defaults to 'true').";
261
262         DriverPropertyInfo JavaDoc allowLoadLocalInfile = new DriverPropertyInfo JavaDoc("allowLoadLocalInfile",
263                 info.getProperty("allowLoadLocalInfile", "true"));
264         allowLoadLocalInfile.required = false;
265         allowLoadLocalInfile.choices = new String JavaDoc[] { "true", "false" };
266         allowLoadLocalInfile.description = "Should the driver allow use of 'LOAD DATA LOCAL INFILE...' (defaults to 'true').";
267
268         DriverPropertyInfo JavaDoc strictUpdates = new DriverPropertyInfo JavaDoc("strictUpdates",
269                 info.getProperty("strictUpdates", "true"));
270         strictUpdates.required = false;
271         strictUpdates.choices = new String JavaDoc[] { "true", "false" };
272         strictUpdates.description = "Should the driver do strict checking (all primary keys selected) of updatable result sets?...' (defaults to 'true').";
273
274         DriverPropertyInfo JavaDoc ignoreNonTxTables = new DriverPropertyInfo JavaDoc("ignoreNonTxTables",
275                 info.getProperty("ignoreNonTxTables", "false"));
276         ignoreNonTxTables.required = false;
277         ignoreNonTxTables.choices = new String JavaDoc[] { "true", "false" };
278         ignoreNonTxTables.description = "Ignore non-transactional table warning for rollback? (defaults to 'false').";
279
280         DriverPropertyInfo JavaDoc clobberStreamingResults = new DriverPropertyInfo JavaDoc("clobberStreamingResults",
281                 info.getProperty("clobberStreamingResults", "false"));
282         clobberStreamingResults.required = false;
283         clobberStreamingResults.choices = new String JavaDoc[] { "true", "false" };
284         clobberStreamingResults.description = "This will cause a 'streaming' ResultSet to be automatically closed, "
285             + "and any oustanding data still streaming from the server to be discarded if another query is executed "
286             + "before all the data has been read from the server.";
287
288         DriverPropertyInfo JavaDoc reconnectAtTxEnd = new DriverPropertyInfo JavaDoc("reconnectAtTxEnd",
289                 info.getProperty("reconnectAtTxEnd", "false"));
290         reconnectAtTxEnd.required = false;
291         reconnectAtTxEnd.choices = new String JavaDoc[] { "true", "false" };
292         reconnectAtTxEnd.description = "If autoReconnect is set to true, should the driver attempt reconnections"
293             + "at the end of every transaction? (true/false, defaults to false)";
294
295         DriverPropertyInfo JavaDoc alwaysClearStream = new DriverPropertyInfo JavaDoc("alwaysClearStream",
296                 info.getProperty("alwaysClearStream", "false"));
297         alwaysClearStream.required = false;
298         alwaysClearStream.choices = new String JavaDoc[] { "true", "false" };
299         alwaysClearStream.description = "Should the driver clear any remaining data from the input stream before issuing"
300             + " a query? Normally not needed (approx 1-2% perf. penalty, true/false, defaults to false)";
301
302         DriverPropertyInfo JavaDoc cachePrepStmts = new DriverPropertyInfo JavaDoc("cachePrepStmts",
303                 info.getProperty("cachePrepStmts", "false"));
304         cachePrepStmts.required = false;
305         cachePrepStmts.choices = new String JavaDoc[] { "true", "false" };
306         cachePrepStmts.description = "Should the driver cache the parsing stage of PreparedStatements (true/false, default is 'false')";
307
308         DriverPropertyInfo JavaDoc prepStmtCacheSize = new DriverPropertyInfo JavaDoc("prepStmtCacheSize",
309                 info.getProperty("prepStmtCacheSize", "25"));
310         prepStmtCacheSize.required = false;
311         prepStmtCacheSize.description = "If prepared statement caching is enabled, "
312             + "how many prepared statements should be cached? (default is '25')";
313
314         DriverPropertyInfo JavaDoc prepStmtCacheSqlLimit = new DriverPropertyInfo JavaDoc("prepStmtCacheSqlLimit",
315                 info.getProperty("prepStmtCacheSqlLimit", "256"));
316         prepStmtCacheSqlLimit.required = false;
317         prepStmtCacheSqlLimit.description = "If prepared statement caching is enabled, "
318             + "what's the largest SQL the driver will cache the parsing for? (in chars, default is '256')";
319
320         DriverPropertyInfo JavaDoc useUnbufferedInput = new DriverPropertyInfo JavaDoc("useUnbufferedInput",
321                 info.getProperty("useUnbufferedInput", "true"));
322         useUnbufferedInput.required = false;
323         useUnbufferedInput.description = "Don't use BufferedInputStream for reading data from the server true/false (default is 'true')";
324
325         DriverPropertyInfo JavaDoc[] dpi = {
326             hostProp, portProp, dbProp, userProp, passwordProp, autoReconnect,
327             maxReconnects, initialTimeout, profileSql, socketTimeout, useSSL,
328             paranoid, useHostsInPrivileges, interactiveClient, useCompression,
329             useTimezone, serverTimezone, connectTimeout,
330             secondsBeforeRetryMaster, queriesBeforeRetryMaster,
331             useStreamLengthsInPrepStmts, continueBatchOnError,
332             allowLoadLocalInfile, strictUpdates, ignoreNonTxTables,
333             reconnectAtTxEnd, alwaysClearStream, cachePrepStmts,
334             prepStmtCacheSize, prepStmtCacheSqlLimit, useUnbufferedInput
335         };
336
337         return dpi;
338     }
339
340     /**
341      * Typically, drivers will return true if they understand the subprotocol
342      * specified in the URL and false if they don't. This driver's protocols
343      * start with jdbc:mysql:
344      *
345      * @param url the URL of the driver
346      *
347      * @return true if this driver accepts the given URL
348      *
349      * @exception java.sql.SQLException if a database-access error occurs
350      *
351      * @see java.sql.Driver#acceptsURL
352      */

353     public boolean acceptsURL(String JavaDoc url) throws java.sql.SQLException JavaDoc {
354         return (parseURL(url, null) != null);
355     }
356
357     /**
358      * Try to make a database connection to the given URL. The driver should
359      * return "null" if it realizes it is the wrong kind of driver to connect
360      * to the given URL. This will be common, as when the JDBC driverManager
361      * is asked to connect to a given URL, it passes the URL to each loaded
362      * driver in turn.
363      *
364      * <p>
365      * The driver should raise an java.sql.SQLException if it is the right
366      * driver to connect to the given URL, but has trouble connecting to the
367      * database.
368      * </p>
369      *
370      * <p>
371      * The java.util.Properties argument can be used to pass arbitrary string
372      * tag/value pairs as connection arguments.
373      * </p>
374      *
375      * <p>
376      * My protocol takes the form:
377      * <PRE>
378      * jdbc:mysql://host:port/database
379      * </PRE>
380      * </p>
381      *
382      * @param url the URL of the database to connect to
383      * @param info a list of arbitrary tag/value pairs as connection arguments
384      *
385      * @return a connection to the URL or null if it isnt us
386      *
387      * @exception java.sql.SQLException if a database access error occurs
388      * @throws SQLException DOCUMENT ME!
389      *
390      * @see java.sql.Driver#connect
391      */

392     public java.sql.Connection JavaDoc connect(String JavaDoc url, Properties JavaDoc info)
393         throws java.sql.SQLException JavaDoc {
394         Properties JavaDoc props = null;
395
396         if ((props = parseURL(url, info)) == null) {
397             return null;
398         } else {
399             try {
400                 Connection newConn = new com.mysql.jdbc.Connection(host(props),
401                         port(props), props, database(props), url, this);
402
403                 return (java.sql.Connection JavaDoc) newConn;
404             } catch (SQLException JavaDoc sqlEx) {
405                 // Don't wrap SQLExceptions, throw
406
// them un-changed.
407
throw sqlEx;
408             } catch (Exception JavaDoc ex) {
409                 throw new SQLException JavaDoc(
410                     "Cannot load connection class because of underlying exception: '"
411                     + ex.toString() + "'.",
412                     SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE);
413             }
414         }
415     }
416
417     //
418
// return the database name property
419
//
420

421     /**
422      * Returns the database property from <code>props</code>
423      *
424      * @param props the Properties to look for the database property.
425      *
426      * @return the database name.
427      */

428     public String JavaDoc database(Properties JavaDoc props) {
429         return props.getProperty("DBNAME");
430     }
431
432     /**
433      * Returns the hostname property
434      *
435      * @param props the java.util.Properties instance to retrieve the hostname
436      * from.
437      *
438      * @return the hostname
439      */

440     public String JavaDoc host(Properties JavaDoc props) {
441         return props.getProperty("HOST", "localhost");
442     }
443
444     /**
445      * Report whether the driver is a genuine JDBC compliant driver. A driver
446      * may only report "true" here if it passes the JDBC compliance tests,
447      * otherwise it is required to return false. JDBC compliance requires
448      * full support for the JDBC API and full support for SQL 92 Entry Level.
449      *
450      * <p>
451      * MySQL is not SQL92 compliant
452      * </p>
453      *
454      * @return is this driver JDBC compliant?
455      */

456     public boolean jdbcCompliant() {
457         return false;
458     }
459
460     /**
461      * Returns the port number property
462      *
463      * @param props the properties to get the port number from
464      *
465      * @return the port number
466      */

467     public int port(Properties JavaDoc props) {
468         return Integer.parseInt(props.getProperty("PORT", "3306"));
469     }
470
471     //
472
// return the value of any property this driver knows about
473
//
474

475     /**
476      * Returns the given property from <code>props</code>
477      *
478      * @param name the property name
479      * @param props the property instance to look in
480      *
481      * @return the property value, or null if not found.
482      */

483     public String JavaDoc property(String JavaDoc name, Properties JavaDoc props) {
484         return props.getProperty(name);
485     }
486
487     /**
488      * Gets the drivers major version number
489      *
490      * @return the drivers major version number
491      */

492     static int getMajorVersionInternal() {
493         return safeIntParse("3");
494     }
495
496     /**
497      * Get the drivers minor version number
498      *
499      * @return the drivers minor version number
500      */

501     static int getMinorVersionInternal() {
502         return safeIntParse("0");
503     }
504
505     /**
506      * Constructs a new DriverURL, splitting the specified URL into its
507      * component parts
508      *
509      * @param url JDBC URL to parse
510      * @param defaults Default properties
511      *
512      * @return Properties with elements added from the url
513      *
514      * @exception java.sql.SQLException
515      */

516
517     //
518
// This is a new URL-parser. This file no longer contains any
519
// Postgresql code.
520
//
521
Properties JavaDoc parseURL(String JavaDoc url, Properties JavaDoc defaults)
522         throws java.sql.SQLException JavaDoc {
523         Properties JavaDoc urlProps = new Properties JavaDoc(defaults);
524
525         if (url == null) {
526             return null;
527         } else {
528             /*
529              * Parse parameters after the ? in the URL and remove
530              * them from the original URL.
531              */

532             int index = url.indexOf("?");
533
534             if (index != -1) {
535                 String JavaDoc paramString = url.substring(index + 1, url.length());
536                 url = url.substring(0, index);
537
538                 StringTokenizer JavaDoc queryParams = new StringTokenizer JavaDoc(paramString,
539                         "&");
540
541                 while (queryParams.hasMoreTokens()) {
542                     StringTokenizer JavaDoc vp = new StringTokenizer JavaDoc(queryParams
543                             .nextToken(), "=");
544                     String JavaDoc param = "";
545
546                     if (vp.hasMoreTokens()) {
547                         param = vp.nextToken();
548                     }
549
550                     String JavaDoc value = "";
551
552                     if (vp.hasMoreTokens()) {
553                         value = vp.nextToken();
554                     }
555
556                     if ((value.length() > 0) && (param.length() > 0)) {
557                         urlProps.put(param, value);
558                     }
559                 }
560             }
561
562             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(url, ":/", true);
563
564             if (st.hasMoreTokens()) {
565                 String JavaDoc protocol = st.nextToken();
566
567                 if (protocol != null) {
568                     if (!protocol.equalsIgnoreCase("jdbc")) {
569                         return null;
570                     }
571                 } else {
572                     return null;
573                 }
574             } else {
575                 return null;
576             }
577
578             // Look for the colon following 'jdbc'
579
if (st.hasMoreTokens()) {
580                 String JavaDoc colon = st.nextToken();
581
582                 if (colon != null) {
583                     if (!colon.equals(":")) {
584                         return null;
585                     }
586                 } else {
587                     return null;
588                 }
589             } else {
590                 return null;
591             }
592
593             // Look for sub-protocol to be mysql
594
if (st.hasMoreTokens()) {
595                 String JavaDoc subProto = st.nextToken();
596
597                 if (subProto != null) {
598                     if (!subProto.equalsIgnoreCase("mysql")) {
599                         return null;
600                     }
601                 } else {
602                     return null;
603                 }
604             } else {
605                 return null;
606             }
607
608             // Look for the colon following 'mysql'
609
if (st.hasMoreTokens()) {
610                 String JavaDoc colon = st.nextToken();
611
612                 if (colon != null) {
613                     if (!colon.equals(":")) {
614                         return null;
615                     }
616                 } else {
617                     return null;
618                 }
619             } else {
620                 return null;
621             }
622
623             // Look for the "//" of the URL
624
if (st.hasMoreTokens()) {
625                 String JavaDoc slash = st.nextToken();
626                 String JavaDoc slash2 = "";
627
628                 if (st.hasMoreTokens()) {
629                     slash2 = st.nextToken();
630                 }
631
632                 if ((slash != null) && (slash2 != null)) {
633                     if (!slash.equals("/") && !slash2.equals("/")) {
634                         return null;
635                     }
636                 } else {
637                     return null;
638                 }
639             } else {
640                 return null;
641             }
642
643             // Okay the next one is a candidate for many things
644
if (st.hasMoreTokens()) {
645                 String JavaDoc token = st.nextToken();
646
647                 if (token != null) {
648                     if (!token.equals(":") && !token.equals("/")) {
649                         // Must be hostname
650
urlProps.put("HOST", token);
651
652                         if (st.hasMoreTokens()) {
653                             token = st.nextToken();
654                         } else {
655                             return null;
656                         }
657                     }
658
659                     // Check for Port spec
660
if (token.equals(":")) {
661                         if (st.hasMoreTokens()) {
662                             token = st.nextToken();
663                             urlProps.put("PORT", token);
664
665                             if (st.hasMoreTokens()) {
666                                 token = st.nextToken();
667                             }
668                         }
669                     }
670
671                     if (token.equals("/")) {
672                         if (st.hasMoreTokens()) {
673                             token = st.nextToken();
674                             urlProps.put("DBNAME", token);
675
676                             // We're done
677
return urlProps;
678                         } else {
679                             urlProps.put("DBNAME", "");
680
681                             return urlProps;
682                         }
683                     }
684                 } else {
685                     return null;
686                 }
687             } else {
688                 return null;
689             }
690         }
691
692         return urlProps;
693     }
694
695     private static int safeIntParse(String JavaDoc intAsString) {
696         try {
697             return Integer.parseInt(intAsString);
698         } catch (NumberFormatException JavaDoc nfe) {
699             return 0;
700         }
701     }
702 }
703
Popular Tags