1. /*
  2. * @(#)DriverManager.java 1.42 04/05/18
  3. *
  4. * Copyright 2004 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<Driver> 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. @Deprecated
  346. public static synchronized void setLogStream(java.io.PrintStream out) {
  347. SecurityManager sec = System.getSecurityManager();
  348. if (sec != null) {
  349. sec.checkPermission(SET_LOG_PERMISSION);
  350. }
  351. logStream = out;
  352. if ( out != null )
  353. logWriter = new java.io.PrintWriter(out);
  354. else
  355. logWriter = null;
  356. }
  357. /**
  358. * Retrieves the logging/tracing PrintStream that is used by the <code>DriverManager</code>
  359. * and all drivers.
  360. *
  361. * @return the logging/tracing PrintStream; if disabled, is <code>null</code>
  362. * @deprecated
  363. * @see #setLogStream
  364. */
  365. @Deprecated
  366. public static java.io.PrintStream getLogStream() {
  367. return logStream;
  368. }
  369. /**
  370. * Prints a message to the current JDBC log stream.
  371. *
  372. * @param message a log or tracing message
  373. */
  374. public static void println(String message) {
  375. synchronized (logSync) {
  376. if (logWriter != null) {
  377. logWriter.println(message);
  378. // automatic flushing is never enabled, so we must do it ourselves
  379. logWriter.flush();
  380. }
  381. }
  382. }
  383. //------------------------------------------------------------------------
  384. // Returns the class object that would be created if the code calling the
  385. // driver manager had loaded the driver class, or null if the class
  386. // is inaccessible.
  387. private static Class getCallerClass(ClassLoader callerClassLoader,
  388. String driverClassName) {
  389. Class callerC = null;
  390. try {
  391. callerC = Class.forName(driverClassName, true, callerClassLoader);
  392. }
  393. catch (Exception ex) {
  394. callerC = null; // being very careful
  395. }
  396. return callerC;
  397. }
  398. private static void loadInitialDrivers() {
  399. String drivers;
  400. try {
  401. drivers = (String) java.security.AccessController.doPrivileged(
  402. new sun.security.action.GetPropertyAction("jdbc.drivers"));
  403. } catch (Exception ex) {
  404. drivers = null;
  405. }
  406. println("DriverManager.initialize: jdbc.drivers = " + drivers);
  407. if (drivers == null) {
  408. return;
  409. }
  410. while (drivers.length() != 0) {
  411. int x = drivers.indexOf(':');
  412. String driver;
  413. if (x < 0) {
  414. driver = drivers;
  415. drivers = "";
  416. } else {
  417. driver = drivers.substring(0, x);
  418. drivers = drivers.substring(x+1);
  419. }
  420. if (driver.length() == 0) {
  421. continue;
  422. }
  423. try {
  424. println("DriverManager.Initialize: loading " + driver);
  425. Class.forName(driver, true,
  426. ClassLoader.getSystemClassLoader());
  427. } catch (Exception ex) {
  428. println("DriverManager.Initialize: load failed: " + ex);
  429. }
  430. }
  431. }
  432. // Worker method called by the public getConnection() methods.
  433. private static synchronized Connection getConnection(
  434. String url, java.util.Properties info, ClassLoader callerCL) throws SQLException {
  435. /*
  436. * When callerCl is null, we should check the application's
  437. * (which is invoking this class indirectly)
  438. * classloader, so that the JDBC driver class outside rt.jar
  439. * can be loaded from here.
  440. */
  441. if(callerCL == null) {
  442. callerCL = Thread.currentThread().getContextClassLoader();
  443. }
  444. if(url == null) {
  445. throw new SQLException("The url cannot be null", "08001");
  446. }
  447. println("DriverManager.getConnection(\"" + url + "\")");
  448. if (!initialized) {
  449. initialize();
  450. }
  451. // Walk through the loaded drivers attempting to make a connection.
  452. // Remember the first exception that gets raised so we can reraise it.
  453. SQLException reason = null;
  454. for (int i = 0; i < drivers.size(); i++) {
  455. DriverInfo di = (DriverInfo)drivers.elementAt(i);
  456. // If the caller does not have permission to load the driver then
  457. // skip it.
  458. if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) {
  459. println(" skipping: " + di);
  460. continue;
  461. }
  462. try {
  463. println(" trying " + di);
  464. Connection result = di.driver.connect(url, info);
  465. if (result != null) {
  466. // Success!
  467. println("getConnection returning " + di);
  468. return (result);
  469. }
  470. } catch (SQLException ex) {
  471. if (reason == null) {
  472. reason = ex;
  473. }
  474. }
  475. }
  476. // if we got here nobody could connect.
  477. if (reason != null) {
  478. println("getConnection failed: " + reason);
  479. throw reason;
  480. }
  481. println("getConnection: no suitable driver");
  482. throw new SQLException("No suitable driver", "08001");
  483. }
  484. // Class initialization.
  485. static void initialize() {
  486. if (initialized) {
  487. return;
  488. }
  489. initialized = true;
  490. loadInitialDrivers();
  491. println("JDBC DriverManager initialized");
  492. }
  493. // Prevent the DriverManager class from being instantiated.
  494. private DriverManager(){}
  495. private static java.util.Vector drivers = new java.util.Vector();
  496. private static int loginTimeout = 0;
  497. private static java.io.PrintWriter logWriter = null;
  498. private static java.io.PrintStream logStream = null;
  499. private static boolean initialized = false;
  500. private static Object logSync = new Object();
  501. // Returns the caller's class loader, or null if none
  502. private static native ClassLoader getCallerClassLoader();
  503. }
  504. // DriverInfo is a package-private support class.
  505. class DriverInfo {
  506. Driver driver;
  507. Class driverClass;
  508. String driverClassName;
  509. public String toString() {
  510. return ("driver[className=" + driverClassName + "," + driver + "]");
  511. }
  512. }