1. /*
  2. * @(#)DriverManager.java 1.38 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.sql;
  8. /**
  9. * <P>The basic service for managing a set of JDBC drivers.<br>
  10. * <B>NOTE:</B> The {@link <code>DataSource</code>} interface, new in the
  11. * JDBC 2.0 API, provides another way to connect to a data source.
  12. * The use of a <code>DataSource</code> object is the preferred means of
  13. * connecting to a data source.
  14. *
  15. * <P>As part of its initialization, the <code>DriverManager</code> class will
  16. * attempt to load the driver classes referenced in the "jdbc.drivers"
  17. * system property. This allows a user to customize the JDBC Drivers
  18. * used by their applications. For example in your
  19. * ~/.hotjava/properties file you might specify:
  20. * <pre>
  21. * <CODE>jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver</CODE>
  22. * </pre>
  23. *
  24. * A program can also explicitly load JDBC drivers at any time. For
  25. * example, the my.sql.Driver is loaded with the following statement:
  26. * <pre>
  27. * <CODE>Class.forName("my.sql.Driver");</CODE>
  28. * </pre>
  29. *
  30. * <P>When the method <code>getConnection</code> is called,
  31. * the <code>DriverManager</code> will attempt to
  32. * locate a suitable driver from amongst those loaded at
  33. * initialization and those loaded explicitly using the same classloader
  34. * as the current applet or application.
  35. * <P>
  36. * Starting with the Java 2 SDK, Standard Edition, version 1.3, a
  37. * logging stream can be set only if the proper
  38. * permission has been granted. Normally this will be done with
  39. * the tool PolicyTool, which can be used to grant <code>permission
  40. * java.sql.SQLPermission "setLog"</code>.
  41. * @see Driver
  42. * @see Connection
  43. */
  44. public class DriverManager {
  45. /**
  46. * The <code>SQLPermission</code> constant that allows the
  47. * setting of the logging stream.
  48. * @since 1.3
  49. */
  50. final static SQLPermission SET_LOG_PERMISSION =
  51. new SQLPermission("setLog");
  52. //--------------------------JDBC 2.0-----------------------------
  53. /**
  54. * Retrieves the log writer.
  55. *
  56. * The <code>getLogWriter</code> and <code>setLogWriter</code>
  57. * methods should be used instead
  58. * of the <code>get/setlogStream</code> methods, which are deprecated.
  59. * @return a <code>java.io.PrintWriter</code> object
  60. * @see #setLogWriter
  61. * @since 1.2
  62. */
  63. public static java.io.PrintWriter getLogWriter() {
  64. synchronized (logSync) {
  65. return logWriter;
  66. }
  67. }
  68. /**
  69. * Sets the logging/tracing <code>PrintWriter</code> object
  70. * that is used by the <code>DriverManager</code> and all drivers.
  71. * <P>
  72. * There is a minor versioning problem created by the introduction
  73. * of the method <code>setLogWriter</code>. The
  74. * method <code>setLogWriter</code> cannot create a <code>PrintStream</code> object
  75. * that will be returned by <code>getLogStream</code>---the Java platform does
  76. * not provide a backward conversion. As a result, a new application
  77. * that uses <code>setLogWriter</code> and also uses a JDBC 1.0 driver that uses
  78. * <code>getLogStream</code> will likely not see debugging information written
  79. * by that driver.
  80. *<P>
  81. * In the Java 2 SDK, Standard Edition, version 1.3 release, this method checks
  82. * to see that there is an <code>SQLPermission</code> object before setting
  83. * the logging stream. If a <code>SecurityManager</code> exists and its
  84. * <code>checkPermission</code> method denies setting the log writer, this
  85. * method throws a <code>java.lang.SecurityException</code>.
  86. *
  87. * @param out the new logging/tracing <code>PrintStream</code> object;
  88. * <code>null</code> to disable logging and tracing
  89. * @throws SecurityException
  90. * if a security manager exists and its
  91. * <code>checkPermission</code> method denies
  92. * setting the log writer
  93. *
  94. * @see SecurityManager#checkPermission
  95. * @see #getLogWriter
  96. * @since 1.2
  97. */
  98. public static void setLogWriter(java.io.PrintWriter out) {
  99. SecurityManager sec = System.getSecurityManager();
  100. if (sec != null) {
  101. sec.checkPermission(SET_LOG_PERMISSION);
  102. }
  103. synchronized (logSync) {
  104. logStream = null;
  105. logWriter = out;
  106. }
  107. }
  108. //---------------------------------------------------------------
  109. /**
  110. * Attempts to establish a connection to the given database URL.
  111. * The <code>DriverManager</code> attempts to select an appropriate driver from
  112. * the set of registered JDBC drivers.
  113. *
  114. * @param url a database url of the form
  115. * <code> jdbc:<em>subprotocol</em>:<em>subname</em></code>
  116. * @param info a list of arbitrary string tag/value pairs as
  117. * connection arguments; normally at least a "user" and
  118. * "password" property should be included
  119. * @return a Connection to the URL
  120. * @exception SQLException if a database access error occurs
  121. */
  122. public static synchronized Connection getConnection(String url,
  123. java.util.Properties info) throws SQLException {
  124. // Gets the classloader of the code that called this method, may
  125. // be null.
  126. ClassLoader callerCL = DriverManager.getCallerClassLoader();
  127. return (getConnection(url, info, callerCL));
  128. }
  129. /**
  130. * Attempts to establish a connection to the given database URL.
  131. * The <code>DriverManager</code> attempts to select an appropriate driver from
  132. * the set of registered JDBC drivers.
  133. *
  134. * @param url a database url of the form
  135. * <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
  136. * @param user the database user on whose behalf the connection is being
  137. * made
  138. * @param password the user's password
  139. * @return a connection to the URL
  140. * @exception SQLException if a database access error occurs
  141. */
  142. public static synchronized Connection getConnection(String url,
  143. String user, String password) throws SQLException {
  144. java.util.Properties info = new java.util.Properties();
  145. // Gets the classloader of the code that called this method, may
  146. // be null.
  147. ClassLoader callerCL = DriverManager.getCallerClassLoader();
  148. if (user != null) {
  149. info.put("user", user);
  150. }
  151. if (password != null) {
  152. info.put("password", password);
  153. }
  154. return (getConnection(url, info, callerCL));
  155. }
  156. /**
  157. * Attempts to establish a connection to the given database URL.
  158. * The <code>DriverManager</code> attempts to select an appropriate driver from
  159. * the set of registered JDBC drivers.
  160. *
  161. * @param url a database url of the form
  162. * <code> jdbc:<em>subprotocol</em>:<em>subname</em></code>
  163. * @return a connection to the URL
  164. * @exception SQLException if a database access error occurs
  165. */
  166. public static synchronized Connection getConnection(String url)
  167. throws SQLException {
  168. java.util.Properties info = new java.util.Properties();
  169. // Gets the classloader of the code that called this method, may
  170. // be null.
  171. ClassLoader callerCL = DriverManager.getCallerClassLoader();
  172. return (getConnection(url, info, callerCL));
  173. }
  174. /**
  175. * Attempts to locate a driver that understands the given URL.
  176. * The <code>DriverManager</code> attempts to select an appropriate driver from
  177. * the set of registered JDBC drivers.
  178. *
  179. * @param url a database URL of the form
  180. * <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
  181. * @return a <code>Driver</code> object representing a driver
  182. * that can connect to the given URL
  183. * @exception SQLException if a database access error occurs
  184. */
  185. public static synchronized Driver getDriver(String url)
  186. throws SQLException {
  187. println("DriverManager.getDriver(\"" + url + "\")");
  188. if (!initialized) {
  189. initialize();
  190. }
  191. // Gets the classloader of the code that called this method, may
  192. // be null.
  193. ClassLoader callerCL = DriverManager.getCallerClassLoader();
  194. // Walk through the loaded drivers attempting to locate someone
  195. // who understands the given URL.
  196. for (int i = 0; i < drivers.size(); i++) {
  197. DriverInfo di = (DriverInfo)drivers.elementAt(i);
  198. // If the caller does not have permission to load the driver then
  199. // skip it.
  200. if ( getCallerClass(callerCL, di.driverClassName ) !=
  201. di.driverClass ) {
  202. println(" skipping: " + di);
  203. continue;
  204. }
  205. try {
  206. println(" trying " + di);
  207. if (di.driver.acceptsURL(url)) {
  208. // Success!
  209. println("getDriver returning " + di);
  210. return (di.driver);
  211. }
  212. } catch (SQLException ex) {
  213. // Drop through and try the next driver.
  214. }
  215. }
  216. println("getDriver: no suitable driver");
  217. throw new SQLException("No suitable driver", "08001");
  218. }
  219. /**
  220. * Registers the given driver with the <code>DriverManager</code>.
  221. * A newly-loaded driver class should call
  222. * the method <code>registerDriver</code> to make itself
  223. * known to the <code>DriverManager</code>.
  224. *
  225. * @param driver the new JDBC Driver that is to be registered with the
  226. * <code>DriverManager</code>
  227. * @exception SQLException if a database access error occurs
  228. */
  229. public static synchronized void registerDriver(java.sql.Driver driver)
  230. throws SQLException {
  231. if (!initialized) {
  232. initialize();
  233. }
  234. DriverInfo di = new DriverInfo();
  235. di.driver = driver;
  236. di.driverClass = driver.getClass();
  237. di.driverClassName = di.driverClass.getName();
  238. drivers.addElement(di);
  239. println("registerDriver: " + di);
  240. }
  241. /**
  242. * Drops a driver from the <code>DriverManager</code>'s list. Applets can only
  243. * deregister drivers from their own classloaders.
  244. *
  245. * @param driver the JDBC Driver to drop
  246. * @exception SQLException if a database access error occurs
  247. */
  248. public static synchronized void deregisterDriver(Driver driver)
  249. throws SQLException {
  250. // Gets the classloader of the code that called this method, may
  251. // be null.
  252. ClassLoader callerCL = DriverManager.getCallerClassLoader();
  253. println("DriverManager.deregisterDriver: " + driver);
  254. // Walk through the loaded drivers.
  255. int i;
  256. DriverInfo di = null;
  257. for (i = 0; i < drivers.size(); i++) {
  258. di = (DriverInfo)drivers.elementAt(i);
  259. if (di.driver == driver) {
  260. break;
  261. }
  262. }
  263. // If we can't find the driver just return.
  264. if (i >= drivers.size()) {
  265. println(" couldn't find driver to unload");
  266. return;
  267. }
  268. // If the caller does not have permission to load the driver then
  269. // throw a security exception.
  270. if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) {
  271. throw new SecurityException();
  272. }
  273. // Remove the driver. Other entries in drivers get shuffled down.
  274. drivers.removeElementAt(i);
  275. }
  276. /**
  277. * Retrieves an Enumeration with all of the currently loaded JDBC drivers
  278. * to which the current caller has access.
  279. *
  280. * <P><B>Note:</B> The classname of a driver can be found using
  281. * <CODE>d.getClass().getName()</CODE>
  282. *
  283. * @return the list of JDBC Drivers loaded by the caller's class loader
  284. */
  285. public static synchronized java.util.Enumeration getDrivers() {
  286. java.util.Vector result = new java.util.Vector();
  287. if (!initialized) {
  288. initialize();
  289. }
  290. // Gets the classloader of the code that called this method, may
  291. // be null.
  292. ClassLoader callerCL = DriverManager.getCallerClassLoader();
  293. // Walk through the loaded drivers.
  294. for (int i = 0; i < drivers.size(); i++) {
  295. DriverInfo di = (DriverInfo)drivers.elementAt(i);
  296. // If the caller does not have permission to load the driver then
  297. // skip it.
  298. if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) {
  299. println(" skipping: " + di);
  300. continue;
  301. }
  302. result.addElement(di.driver);
  303. }
  304. return (result.elements());
  305. }
  306. /**
  307. * Sets the maximum time in seconds that a driver will wait
  308. * while attempting to connect to a database.
  309. *
  310. * @param seconds the login time limit in seconds
  311. * @see #getLoginTimeout
  312. */
  313. public static void setLoginTimeout(int seconds) {
  314. loginTimeout = seconds;
  315. }
  316. /**
  317. * Gets the maximum time in seconds that a driver can wait
  318. * when attempting to log in to a database.
  319. *
  320. * @return the driver login time limit in seconds
  321. * @see #setLoginTimeout
  322. */
  323. public static int getLoginTimeout() {
  324. return (loginTimeout);
  325. }
  326. /**
  327. * Sets the logging/tracing PrintStream that is used
  328. * by the <code>DriverManager</code>
  329. * and all drivers.
  330. *<P>
  331. * In the Java 2 SDK, Standard Edition, version 1.3 release, this method checks
  332. * to see that there is an <code>SQLPermission</code> object before setting
  333. * the logging stream. If a <code>SecurityManager</code> exists and its
  334. * <code>checkPermission</code> method denies setting the log writer, this
  335. * method throws a <code>java.lang.SecurityException</code>.
  336. *
  337. * @param out the new logging/tracing PrintStream; to disable, set to <code>null</code>
  338. * @deprecated
  339. * @throws SecurityException if a security manager exists and its
  340. * <code>checkPermission</code> method denies setting the log stream
  341. *
  342. * @see SecurityManager#checkPermission
  343. * @see #getLogStream
  344. */
  345. public static synchronized void setLogStream(java.io.PrintStream out) {
  346. SecurityManager sec = System.getSecurityManager();
  347. if (sec != null) {
  348. sec.checkPermission(SET_LOG_PERMISSION);
  349. }
  350. logStream = out;
  351. if ( out != null )
  352. logWriter = new java.io.PrintWriter(out);
  353. else
  354. logWriter = null;
  355. }
  356. /**
  357. * Retrieves the logging/tracing PrintStream that is used by the <code>DriverManager</code>
  358. * and all drivers.
  359. *
  360. * @return the logging/tracing PrintStream; if disabled, is <code>null</code>
  361. * @deprecated
  362. * @see #setLogStream
  363. */
  364. public static java.io.PrintStream getLogStream() {
  365. return logStream;
  366. }
  367. /**
  368. * Prints a message to the current JDBC log stream.
  369. *
  370. * @param message a log or tracing message
  371. */
  372. public static void println(String message) {
  373. synchronized (logSync) {
  374. if (logWriter != null) {
  375. logWriter.println(message);
  376. // automatic flushing is never enabled, so we must do it ourselves
  377. logWriter.flush();
  378. }
  379. }
  380. }
  381. //------------------------------------------------------------------------
  382. // Returns the class object that would be created if the code calling the
  383. // driver manager had loaded the driver class, or null if the class
  384. // is inaccessible.
  385. private static Class getCallerClass(ClassLoader callerClassLoader,
  386. String driverClassName) {
  387. Class callerC = null;
  388. try {
  389. callerC = Class.forName(driverClassName, true, callerClassLoader);
  390. }
  391. catch (Exception ex) {
  392. callerC = null; // being very careful
  393. }
  394. return callerC;
  395. }
  396. private static void loadInitialDrivers() {
  397. String drivers;
  398. try {
  399. drivers = (String) java.security.AccessController.doPrivileged(
  400. new sun.security.action.GetPropertyAction("jdbc.drivers"));
  401. } catch (Exception ex) {
  402. drivers = null;
  403. }
  404. println("DriverManager.initialize: jdbc.drivers = " + drivers);
  405. if (drivers == null) {
  406. return;
  407. }
  408. while (drivers.length() != 0) {
  409. int x = drivers.indexOf(':');
  410. String driver;
  411. if (x < 0) {
  412. driver = drivers;
  413. drivers = "";
  414. } else {
  415. driver = drivers.substring(0, x);
  416. drivers = drivers.substring(x+1);
  417. }
  418. if (driver.length() == 0) {
  419. continue;
  420. }
  421. try {
  422. println("DriverManager.Initialize: loading " + driver);
  423. Class.forName(driver, true,
  424. ClassLoader.getSystemClassLoader());
  425. } catch (Exception ex) {
  426. println("DriverManager.Initialize: load failed: " + ex);
  427. }
  428. }
  429. }
  430. // Worker method called by the public getConnection() methods.
  431. private static synchronized Connection getConnection(
  432. String url, java.util.Properties info, ClassLoader callerCL) throws SQLException {
  433. if(url == null) {
  434. throw new SQLException("The url cannot be null", "08001");
  435. }
  436. println("DriverManager.getConnection(\"" + url + "\")");
  437. if (!initialized) {
  438. initialize();
  439. }
  440. // Walk through the loaded drivers attempting to make a connection.
  441. // Remember the first exception that gets raised so we can reraise it.
  442. SQLException reason = null;
  443. for (int i = 0; i < drivers.size(); i++) {
  444. DriverInfo di = (DriverInfo)drivers.elementAt(i);
  445. // If the caller does not have permission to load the driver then
  446. // skip it.
  447. if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) {
  448. println(" skipping: " + di);
  449. continue;
  450. }
  451. try {
  452. println(" trying " + di);
  453. Connection result = di.driver.connect(url, info);
  454. if (result != null) {
  455. // Success!
  456. println("getConnection returning " + di);
  457. return (result);
  458. }
  459. } catch (SQLException ex) {
  460. if (reason == null) {
  461. reason = ex;
  462. }
  463. }
  464. }
  465. // if we got here nobody could connect.
  466. if (reason != null) {
  467. println("getConnection failed: " + reason);
  468. throw reason;
  469. }
  470. println("getConnection: no suitable driver");
  471. throw new SQLException("No suitable driver", "08001");
  472. }
  473. // Class initialization.
  474. static void initialize() {
  475. if (initialized) {
  476. return;
  477. }
  478. initialized = true;
  479. loadInitialDrivers();
  480. println("JDBC DriverManager initialized");
  481. }
  482. // Prevent the DriverManager class from being instantiated.
  483. private DriverManager(){}
  484. private static java.util.Vector drivers = new java.util.Vector();
  485. private static int loginTimeout = 0;
  486. private static java.io.PrintWriter logWriter = null;
  487. private static java.io.PrintStream logStream = null;
  488. private static boolean initialized = false;
  489. private static Object logSync = new Object();
  490. // Returns the caller's class loader, or null if none
  491. private static native ClassLoader getCallerClassLoader();
  492. }
  493. // DriverInfo is a package-private support class.
  494. class DriverInfo {
  495. Driver driver;
  496. Class driverClass;
  497. String driverClassName;
  498. public String toString() {
  499. return ("driver[className=" + driverClassName + "," + driver + "]");
  500. }
  501. }