DriverManager.java 27.3 KB
Newer Older
D
duke 已提交
1
/*
L
lancea 已提交
2
 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31
 */

package java.sql;

import java.util.Iterator;
import java.util.ServiceLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
32
import java.util.concurrent.CopyOnWriteArrayList;
33
import sun.reflect.CallerSensitive;
34
import sun.reflect.Reflection;
D
duke 已提交
35 36 37 38


/**
 * <P>The basic service for managing a set of JDBC drivers.<br>
A
alanb 已提交
39
 * <B>NOTE:</B> The {@link javax.sql.DataSource} interface, new in the
D
duke 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
 * JDBC 2.0 API, provides another way to connect to a data source.
 * The use of a <code>DataSource</code> object is the preferred means of
 * connecting to a data source.
 *
 * <P>As part of its initialization, the <code>DriverManager</code> class will
 * attempt to load the driver classes referenced in the "jdbc.drivers"
 * system property. This allows a user to customize the JDBC Drivers
 * used by their applications. For example in your
 * ~/.hotjava/properties file you might specify:
 * <pre>
 * <CODE>jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver</CODE>
 * </pre>
 *<P> The <code>DriverManager</code> methods <code>getConnection</code> and
 * <code>getDrivers</code> have been enhanced to support the Java Standard Edition
 * <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">Service Provider</a> mechanism. JDBC 4.0 Drivers must
 * include the file <code>META-INF/services/java.sql.Driver</code>. This file contains the name of the JDBC drivers
 * implementation of <code>java.sql.Driver</code>.  For example, to load the <code>my.sql.Driver</code> class,
 * the <code>META-INF/services/java.sql.Driver</code> file would contain the entry:
 * <pre>
 * <code>my.sql.Driver</code>
 * </pre>
 *
 * <P>Applications no longer need to explictly load JDBC drivers using <code>Class.forName()</code>. Existing programs
 * which currently load JDBC drivers using <code>Class.forName()</code> will continue to work without
 * modification.
 *
 * <P>When the method <code>getConnection</code> is called,
 * the <code>DriverManager</code> will attempt to
 * locate a suitable driver from amongst those loaded at
 * initialization and those loaded explicitly using the same classloader
 * as the current applet or application.
 *
 * <P>
 * Starting with the Java 2 SDK, Standard Edition, version 1.3, a
 * logging stream can be set only if the proper
 * permission has been granted.  Normally this will be done with
 * the tool PolicyTool, which can be used to grant <code>permission
 * java.sql.SQLPermission "setLog"</code>.
 * @see Driver
 * @see Connection
 */
public class DriverManager {


84
    // List of registered JDBC drivers
85
    private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<>();
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    private static volatile int loginTimeout = 0;
    private static volatile java.io.PrintWriter logWriter = null;
    private static volatile java.io.PrintStream logStream = null;
    // Used in println() to synchronize logWriter
    private final static  Object logSync = new Object();

    /* Prevent the DriverManager class from being instantiated. */
    private DriverManager(){}


    /**
     * Load the initial JDBC drivers by checking the System property
     * jdbc.properties and then use the {@code ServiceLoader} mechanism
     */
    static {
        loadInitialDrivers();
        println("JDBC DriverManager initialized");
    }

D
duke 已提交
105 106 107 108 109 110 111 112
    /**
     * The <code>SQLPermission</code> constant that allows the
     * setting of the logging stream.
     * @since 1.3
     */
    final static SQLPermission SET_LOG_PERMISSION =
        new SQLPermission("setLog");

113 114 115 116 117 118 119 120
    /**
     * The {@code SQLPermission} constant that allows the
     * un-register a registered JDBC driver.
     * @since 1.8
     */
    final static SQLPermission DEREGISTER_DRIVER_PERMISSION =
        new SQLPermission("deregisterDriver");

D
duke 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    //--------------------------JDBC 2.0-----------------------------

    /**
     * Retrieves the log writer.
     *
     * The <code>getLogWriter</code> and <code>setLogWriter</code>
     * methods should be used instead
     * of the <code>get/setlogStream</code> methods, which are deprecated.
     * @return a <code>java.io.PrintWriter</code> object
     * @see #setLogWriter
     * @since 1.2
     */
    public static java.io.PrintWriter getLogWriter() {
            return logWriter;
    }

    /**
     * Sets the logging/tracing <code>PrintWriter</code> object
     * that is used by the <code>DriverManager</code> and all drivers.
     * <P>
     * There is a minor versioning problem created by the introduction
     * of the method <code>setLogWriter</code>.  The
     * method <code>setLogWriter</code> cannot create a <code>PrintStream</code> object
     * that will be returned by <code>getLogStream</code>---the Java platform does
     * not provide a backward conversion.  As a result, a new application
     * that uses <code>setLogWriter</code> and also uses a JDBC 1.0 driver that uses
     * <code>getLogStream</code> will likely not see debugging information written
     * by that driver.
     *<P>
     * Starting with the Java 2 SDK, Standard Edition, version 1.3 release, this method checks
     * to see that there is an <code>SQLPermission</code> object before setting
     * the logging stream.  If a <code>SecurityManager</code> exists and its
     * <code>checkPermission</code> method denies setting the log writer, this
     * method throws a <code>java.lang.SecurityException</code>.
     *
     * @param out the new logging/tracing <code>PrintStream</code> object;
     *      <code>null</code> to disable logging and tracing
     * @throws SecurityException
     *    if a security manager exists and its
     *    <code>checkPermission</code> method denies
     *    setting the log writer
     *
     * @see SecurityManager#checkPermission
     * @see #getLogWriter
     * @since 1.2
     */
    public static void setLogWriter(java.io.PrintWriter out) {

        SecurityManager sec = System.getSecurityManager();
        if (sec != null) {
            sec.checkPermission(SET_LOG_PERMISSION);
        }
            logStream = null;
            logWriter = out;
    }


    //---------------------------------------------------------------

    /**
     * Attempts to establish a connection to the given database URL.
     * The <code>DriverManager</code> attempts to select an appropriate driver from
     * the set of registered JDBC drivers.
L
lancea 已提交
184 185 186 187 188 189
     *<p>
     * <B>Note:</B> If a property is specified as part of the {@code url} and
     * is also specified in the {@code Properties} object, it is
     * implementation-defined as to which value will take precedence.
     * For maximum portability, an application should only specify a
     * property once.
D
duke 已提交
190 191 192 193 194 195 196
     *
     * @param url a database url of the form
     * <code> jdbc:<em>subprotocol</em>:<em>subname</em></code>
     * @param info a list of arbitrary string tag/value pairs as
     * connection arguments; normally at least a "user" and
     * "password" property should be included
     * @return a Connection to the URL
L
lancea 已提交
197 198 199 200 201 202
     * @exception SQLException if a database access error occurs or the url is
     * {@code null}
     * @throws SQLTimeoutException  when the driver has determined that the
     * timeout value specified by the {@code setLoginTimeout} method
     * has been exceeded and has at least tried to cancel the
     * current database connection attempt
D
duke 已提交
203
     */
204
    @CallerSensitive
D
duke 已提交
205 206 207
    public static Connection getConnection(String url,
        java.util.Properties info) throws SQLException {

208
        return (getConnection(url, info, Reflection.getCallerClass()));
D
duke 已提交
209 210 211 212 213 214
    }

    /**
     * Attempts to establish a connection to the given database URL.
     * The <code>DriverManager</code> attempts to select an appropriate driver from
     * the set of registered JDBC drivers.
L
lancea 已提交
215 216 217 218 219 220
     *<p>
     * <B>Note:</B> If a property is specified as part of the {@code url} and
     * is also specified in the {@code Properties} object, it is
     * implementation-defined as to which value will take precedence.
     * For maximum portability, an application should only specify a
     * property once.
D
duke 已提交
221 222 223 224 225 226 227
     *
     * @param url a database url of the form
     * <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
     * @param user the database user on whose behalf the connection is being
     *   made
     * @param password the user's password
     * @return a connection to the URL
L
lancea 已提交
228 229 230 231 232 233
     * @exception SQLException if a database access error occurs or the url is
     * {@code null}
     * @throws SQLTimeoutException  when the driver has determined that the
     * timeout value specified by the {@code setLoginTimeout} method
     * has been exceeded and has at least tried to cancel the
     * current database connection attempt
D
duke 已提交
234
     */
235
    @CallerSensitive
D
duke 已提交
236 237 238 239 240 241 242 243 244 245 246
    public static Connection getConnection(String url,
        String user, String password) throws SQLException {
        java.util.Properties info = new java.util.Properties();

        if (user != null) {
            info.put("user", user);
        }
        if (password != null) {
            info.put("password", password);
        }

247
        return (getConnection(url, info, Reflection.getCallerClass()));
D
duke 已提交
248 249 250 251 252 253 254 255 256 257
    }

    /**
     * Attempts to establish a connection to the given database URL.
     * The <code>DriverManager</code> attempts to select an appropriate driver from
     * the set of registered JDBC drivers.
     *
     * @param url a database url of the form
     *  <code> jdbc:<em>subprotocol</em>:<em>subname</em></code>
     * @return a connection to the URL
L
lancea 已提交
258 259 260 261 262 263
     * @exception SQLException if a database access error occurs or the url is
     * {@code null}
     * @throws SQLTimeoutException  when the driver has determined that the
     * timeout value specified by the {@code setLoginTimeout} method
     * has been exceeded and has at least tried to cancel the
     * current database connection attempt
D
duke 已提交
264
     */
265
    @CallerSensitive
D
duke 已提交
266 267 268 269
    public static Connection getConnection(String url)
        throws SQLException {

        java.util.Properties info = new java.util.Properties();
270
        return (getConnection(url, info, Reflection.getCallerClass()));
D
duke 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283
    }

    /**
     * Attempts to locate a driver that understands the given URL.
     * The <code>DriverManager</code> attempts to select an appropriate driver from
     * the set of registered JDBC drivers.
     *
     * @param url a database URL of the form
     *     <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
     * @return a <code>Driver</code> object representing a driver
     * that can connect to the given URL
     * @exception SQLException if a database access error occurs
     */
284
    @CallerSensitive
D
duke 已提交
285 286 287 288 289
    public static Driver getDriver(String url)
        throws SQLException {

        println("DriverManager.getDriver(\"" + url + "\")");

290
        Class<?> callerClass = Reflection.getCallerClass();
D
duke 已提交
291

292
        // Walk through the loaded registeredDrivers attempting to locate someone
D
duke 已提交
293
        // who understands the given URL.
294
        for (DriverInfo aDriver : registeredDrivers) {
D
duke 已提交
295 296
            // If the caller does not have permission to load the driver then
            // skip it.
297
            if(isDriverAllowed(aDriver.driver, callerClass)) {
298
                try {
299
                    if(aDriver.driver.acceptsURL(url)) {
300
                        // Success!
301 302
                        println("getDriver returning " + aDriver.driver.getClass().getName());
                    return (aDriver.driver);
303 304 305 306
                    }

                } catch(SQLException sqe) {
                    // Drop through and try the next driver.
D
duke 已提交
307
                }
308
            } else {
309
                println("    skipping: " + aDriver.driver.getClass().getName());
D
duke 已提交
310
            }
311

D
duke 已提交
312 313 314 315 316 317 318 319
        }

        println("getDriver: no suitable driver");
        throw new SQLException("No suitable driver", "08001");
    }


    /**
320
     * Registers the given driver with the {@code DriverManager}.
D
duke 已提交
321
     * A newly-loaded driver class should call
322 323 324
     * the method {@code registerDriver} to make itself
     * known to the {@code DriverManager}. If the driver had previously been
     * registered, no action is taken.
D
duke 已提交
325 326
     *
     * @param driver the new JDBC Driver that is to be registered with the
327
     *               {@code DriverManager}
D
duke 已提交
328
     * @exception SQLException if a database access error occurs
329
     * @exception NullPointerException if {@code driver} is null
D
duke 已提交
330 331 332 333
     */
    public static synchronized void registerDriver(java.sql.Driver driver)
        throws SQLException {

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        registerDriver(driver, null);
    }

    /**
     * Registers the given driver with the {@code DriverManager}.
     * A newly-loaded driver class should call
     * the method {@code registerDriver} to make itself
     * known to the {@code DriverManager}. If the driver had previously been
     * registered, no action is taken.
     *
     * @param driver the new JDBC Driver that is to be registered with the
     *               {@code DriverManager}
     * @param da     the {@code DriverAction} implementation to be used when
     *               {@code DriverManager#deregisterDriver} is called
     * @exception SQLException if a database access error occurs
349
     * @exception NullPointerException if {@code driver} is null
350 351 352 353 354
     */
    public static synchronized void registerDriver(java.sql.Driver driver,
            DriverAction da)
        throws SQLException {

355 356
        /* Register the driver if it has not already been added to our list */
        if(driver != null) {
357
            registeredDrivers.addIfAbsent(new DriverInfo(driver, da));
358 359 360 361
        } else {
            // This is for compatibility with the original DriverManager
            throw new NullPointerException();
        }
D
duke 已提交
362

363
        println("registerDriver: " + driver);
D
duke 已提交
364 365 366 367

    }

    /**
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
     * Removes the specified driver from the {@code DriverManager}'s list of
     * registered drivers.
     * <p>
     * If a {@code null} value is specified for the driver to be removed, then no
     * action is taken.
     * <p>
     * If a security manager exists and its {@code checkPermission} denies
     * permission, then a {@code SecurityException} will be thrown.
     * <p>
     * If the specified driver is not found in the list of registered drivers,
     * then no action is taken.  If the driver was found, it will be removed
     * from the list of registered drivers.
     * <p>
     * If a {@code DriverAction} instance was specified when the JDBC driver was
     * registered, its deregister method will be called
     * prior to the driver being removed from the list of registered drivers.
D
duke 已提交
384
     *
385
     * @param driver the JDBC Driver to remove
D
duke 已提交
386
     * @exception SQLException if a database access error occurs
387 388 389 390
     * @throws SecurityException if a security manager exists and its
     * {@code checkPermission} method denies permission to deregister a driver.
     *
     * @see SecurityManager#checkPermission
D
duke 已提交
391
     */
392
    @CallerSensitive
D
duke 已提交
393 394
    public static synchronized void deregisterDriver(Driver driver)
        throws SQLException {
395 396 397 398
        if (driver == null) {
            return;
        }

399 400 401 402 403
        SecurityManager sec = System.getSecurityManager();
        if (sec != null) {
            sec.checkPermission(DEREGISTER_DRIVER_PERMISSION);
        }

D
duke 已提交
404 405
        println("DriverManager.deregisterDriver: " + driver);

406
        DriverInfo aDriver = new DriverInfo(driver, null);
407
        if(registeredDrivers.contains(aDriver)) {
408
            if (isDriverAllowed(driver, Reflection.getCallerClass())) {
409 410 411 412 413 414
                DriverInfo di = registeredDrivers.get(registeredDrivers.indexOf(aDriver));
                 // If a DriverAction was specified, Call it to notify the
                 // driver that it has been deregistered
                 if(di.action() != null) {
                     di.action().deregister();
                 }
415
                 registeredDrivers.remove(aDriver);
416 417 418 419
            } else {
                // If the caller does not have permission to load the driver then
                // throw a SecurityException.
                throw new SecurityException();
D
duke 已提交
420
            }
421
        } else {
D
duke 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434
            println("    couldn't find driver to unload");
        }
    }

    /**
     * Retrieves an Enumeration with all of the currently loaded JDBC drivers
     * to which the current caller has access.
     *
     * <P><B>Note:</B> The classname of a driver can be found using
     * <CODE>d.getClass().getName()</CODE>
     *
     * @return the list of JDBC Drivers loaded by the caller's class loader
     */
435
    @CallerSensitive
D
duke 已提交
436
    public static java.util.Enumeration<Driver> getDrivers() {
437
        java.util.Vector<Driver> result = new java.util.Vector<>();
D
duke 已提交
438

439
        Class<?> callerClass = Reflection.getCallerClass();
D
duke 已提交
440

441
        // Walk through the loaded registeredDrivers.
442
        for(DriverInfo aDriver : registeredDrivers) {
D
duke 已提交
443 444
            // If the caller does not have permission to load the driver then
            // skip it.
445
            if(isDriverAllowed(aDriver.driver, callerClass)) {
446
                result.addElement(aDriver.driver);
447 448
            } else {
                println("    skipping: " + aDriver.getClass().getName());
D
duke 已提交
449 450 451 452 453 454 455 456
            }
        }
        return (result.elements());
    }


    /**
     * Sets the maximum time in seconds that a driver will wait
L
lancea 已提交
457 458
     * while attempting to connect to a database once the driver has
     * been identified.
D
duke 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
     *
     * @param seconds the login time limit in seconds; zero means there is no limit
     * @see #getLoginTimeout
     */
    public static void setLoginTimeout(int seconds) {
        loginTimeout = seconds;
    }

    /**
     * Gets the maximum time in seconds that a driver can wait
     * when attempting to log in to a database.
     *
     * @return the driver login time limit in seconds
     * @see #setLoginTimeout
     */
    public static int getLoginTimeout() {
        return (loginTimeout);
    }

    /**
     * Sets the logging/tracing PrintStream that is used
     * by the <code>DriverManager</code>
     * and all drivers.
     *<P>
     * In the Java 2 SDK, Standard Edition, version 1.3 release, this method checks
     * to see that there is an <code>SQLPermission</code> object before setting
     * the logging stream.  If a <code>SecurityManager</code> exists and its
     * <code>checkPermission</code> method denies setting the log writer, this
     * method throws a <code>java.lang.SecurityException</code>.
     *
     * @param out the new logging/tracing PrintStream; to disable, set to <code>null</code>
490
     * @deprecated Use {@code setLogWriter}
D
duke 已提交
491 492 493 494 495 496
     * @throws SecurityException if a security manager exists and its
     *    <code>checkPermission</code> method denies setting the log stream
     *
     * @see SecurityManager#checkPermission
     * @see #getLogStream
     */
497
    @Deprecated
D
duke 已提交
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    public static void setLogStream(java.io.PrintStream out) {

        SecurityManager sec = System.getSecurityManager();
        if (sec != null) {
            sec.checkPermission(SET_LOG_PERMISSION);
        }

        logStream = out;
        if ( out != null )
            logWriter = new java.io.PrintWriter(out);
        else
            logWriter = null;
    }

    /**
     * Retrieves the logging/tracing PrintStream that is used by the <code>DriverManager</code>
     * and all drivers.
     *
     * @return the logging/tracing PrintStream; if disabled, is <code>null</code>
517
     * @deprecated  Use {@code getLogWriter}
D
duke 已提交
518 519
     * @see #setLogStream
     */
520
    @Deprecated
D
duke 已提交
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    public static java.io.PrintStream getLogStream() {
        return logStream;
    }

    /**
     * Prints a message to the current JDBC log stream.
     *
     * @param message a log or tracing message
     */
    public static void println(String message) {
        synchronized (logSync) {
            if (logWriter != null) {
                logWriter.println(message);

                // automatic flushing is never enabled, so we must do it ourselves
                logWriter.flush();
            }
        }
    }

    //------------------------------------------------------------------------

543 544
    // Indicates whether the class object that would be created if the code calling
    // DriverManager is accessible.
545 546 547 548 549
    private static boolean isDriverAllowed(Driver driver, Class<?> caller) {
        ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
        return isDriverAllowed(driver, callerCL);
    }

550 551 552 553 554 555 556 557 558
    private static boolean isDriverAllowed(Driver driver, ClassLoader classLoader) {
        boolean result = false;
        if(driver != null) {
            Class<?> aClass = null;
            try {
                aClass =  Class.forName(driver.getClass().getName(), true, classLoader);
            } catch (Exception ex) {
                result = false;
            }
D
duke 已提交
559

560
             result = ( aClass == driver.getClass() ) ? true : false;
D
duke 已提交
561 562
        }

563
        return result;
D
duke 已提交
564 565 566 567 568
    }

    private static void loadInitialDrivers() {
        String drivers;
        try {
569 570
            drivers = AccessController.doPrivileged(new PrivilegedAction<String>() {
                public String run() {
D
duke 已提交
571 572 573 574 575 576 577 578 579 580 581
                    return System.getProperty("jdbc.drivers");
                }
            });
        } catch (Exception ex) {
            drivers = null;
        }
        // If the driver is packaged as a Service Provider, load it.
        // Get all the drivers through the classloader
        // exposed as a java.sql.Driver.class service.
        // ServiceLoader.load() replaces the sun.misc.Providers()

582 583
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
D
duke 已提交
584 585

                ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
586
                Iterator<Driver> driversIterator = loadedDrivers.iterator();
D
duke 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

                /* Load these drivers, so that they can be instantiated.
                 * It may be the case that the driver class may not be there
                 * i.e. there may be a packaged driver with the service class
                 * as implementation of java.sql.Driver but the actual class
                 * may be missing. In that case a java.util.ServiceConfigurationError
                 * will be thrown at runtime by the VM trying to locate
                 * and load the service.
                 *
                 * Adding a try catch block to catch those runtime errors
                 * if driver not available in classpath but it's
                 * packaged as service and that service is there in classpath.
                 */
                try{
                    while(driversIterator.hasNext()) {
L
lancea 已提交
602
                        driversIterator.next();
D
duke 已提交
603 604 605 606 607 608 609 610 611
                    }
                } catch(Throwable t) {
                // Do nothing
                }
                return null;
            }
        });

        println("DriverManager.initialize: jdbc.drivers = " + drivers);
612 613

        if (drivers == null || drivers.equals("")) {
D
duke 已提交
614 615
            return;
        }
616 617 618
        String[] driversList = drivers.split(":");
        println("number of Drivers:" + driversList.length);
        for (String aDriver : driversList) {
D
duke 已提交
619
            try {
620 621 622
                println("DriverManager.Initialize: loading " + aDriver);
                Class.forName(aDriver, true,
                        ClassLoader.getSystemClassLoader());
D
duke 已提交
623 624 625 626 627 628 629 630 631
            } catch (Exception ex) {
                println("DriverManager.Initialize: load failed: " + ex);
            }
        }
    }


    //  Worker method called by the public getConnection() methods.
    private static Connection getConnection(
632
        String url, java.util.Properties info, Class<?> caller) throws SQLException {
D
duke 已提交
633 634 635 636 637 638
        /*
         * When callerCl is null, we should check the application's
         * (which is invoking this class indirectly)
         * classloader, so that the JDBC driver class outside rt.jar
         * can be loaded from here.
         */
639
        ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
D
duke 已提交
640
        synchronized(DriverManager.class) {
641 642 643 644
            // synchronize loading of the correct classloader.
            if (callerCL == null) {
                callerCL = Thread.currentThread().getContextClassLoader();
            }
D
duke 已提交
645 646 647 648 649 650 651 652
        }

        if(url == null) {
            throw new SQLException("The url cannot be null", "08001");
        }

        println("DriverManager.getConnection(\"" + url + "\")");

653
        // Walk through the loaded registeredDrivers attempting to make a connection.
D
duke 已提交
654 655 656
        // Remember the first exception that gets raised so we can reraise it.
        SQLException reason = null;

657
        for(DriverInfo aDriver : registeredDrivers) {
D
duke 已提交
658 659
            // If the caller does not have permission to load the driver then
            // skip it.
660
            if(isDriverAllowed(aDriver.driver, callerCL)) {
661
                try {
662 663
                    println("    trying " + aDriver.driver.getClass().getName());
                    Connection con = aDriver.driver.connect(url, info);
664 665
                    if (con != null) {
                        // Success!
666
                        println("getConnection returning " + aDriver.driver.getClass().getName());
667 668 669 670 671 672
                        return (con);
                    }
                } catch (SQLException ex) {
                    if (reason == null) {
                        reason = ex;
                    }
D
duke 已提交
673
                }
674 675 676

            } else {
                println("    skipping: " + aDriver.getClass().getName());
D
duke 已提交
677
            }
678

D
duke 已提交
679 680 681 682 683 684 685 686 687 688 689 690 691 692
        }

        // if we got here nobody could connect.
        if (reason != null)    {
            println("getConnection failed: " + reason);
            throw reason;
        }

        println("getConnection: no suitable driver found for "+ url);
        throw new SQLException("No suitable driver found for "+ url, "08001");
    }


}
693 694 695 696 697 698 699 700 701

/*
 * Wrapper class for registered Drivers in order to not expose Driver.equals()
 * to avoid the capture of the Driver it being compared to as it might not
 * normally have access.
 */
class DriverInfo {

    final Driver driver;
702 703
    DriverAction da;
    DriverInfo(Driver driver, DriverAction action) {
704
        this.driver = driver;
705
        da = action;
706 707
    }

708
    @Override
709 710 711 712 713
    public boolean equals(Object other) {
        return (other instanceof DriverInfo)
                && this.driver == ((DriverInfo) other).driver;
    }

714
    @Override
715 716 717 718
    public int hashCode() {
        return driver.hashCode();
    }

719
    @Override
720 721 722
    public String toString() {
        return ("driver[className="  + driver + "]");
    }
723 724 725 726

    DriverAction action() {
        return da;
    }
727
}