Java Code Examples for java.sql.DriverManager#getDriver()

The following examples show how to use java.sql.DriverManager#getDriver() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DriverTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Do java.sql.Driver.connect(String url, Properties info call)
 *
 * @param expectUrlEqualsGetUrl boolean indicating embedded would
 *                  expect the url passed in to equal metadata.getURL()
 * @param url       url to pass to Driver.connect()
 * @param info      properties to pass to Driver.Connect()
 *
 * @throws SQLException on error.
 */
private static void assertConnect(
        boolean expectUrlEqualsGetUrl, String url, Properties info)
        throws SQLException
{
    Driver driver = DriverManager.getDriver(url);

    Connection conn = driver.connect(url, info);
    assertNotNull(conn);

    if (expectUrlEqualsGetUrl)
        assertEquals(url, conn.getMetaData().getURL());
    else
        assertNotSame(url, conn.getMetaData().getURL());
    ResultSet rs =
            conn.createStatement().executeQuery("VALUES(CURRENT SCHEMA)");
    rs.next();
    assertEquals(
            rs.getString(1), conn.getMetaData().getUserName().toUpperCase());
    rs.close();
    conn.close();
    return;
}
 
Example 2
Source File: Driver40UnbootedTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <p>
 * This entry point is used to run a separate java process in order to verify
 * that the correct exception is being raised by getParentLogger() when the
 * engine hasn't been booted yet.
 * </p>
 */
public  static  void    main( String[] args )  throws Exception
{
    Driver  embeddedDriver = DriverManager.getDriver( "jdbc:splice:" );
    Wrapper41Driver embeddedWrapper = new Wrapper41Driver( embeddedDriver );

    String  statusMessage = SUCCESS;
    
    try {
        embeddedWrapper.getParentLogger();
        statusMessage = "getParentLogger() unexpectedly succeeded";
    }
    catch (Exception se)
    {
        if ( !( se instanceof SQLFeatureNotSupportedException ) )
        {
            statusMessage = "Exception was not a SQLFeatureNotSupportedException. It was a " + se.getClass().getName();
        }
    }

    System.out.print( statusMessage );
}
 
Example 3
Source File: PoolingDriverExample.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
public static void printDriverStats() throws Exception {
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
    ObjectPool<? extends Connection> connectionPool = driver.getConnectionPool("example");

    System.out.println("NumActive: " + connectionPool.getNumActive());
    System.out.println("NumIdle: " + connectionPool.getNumIdle());
}
 
Example 4
Source File: Driver.java    From javasimon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Tries to determine driver class, instantiate it and register if already not registered.
 * For more detail look at {@link Driver} class javadoc.
 *
 * @param configuration instance of url object that represents url
 * @param info parameters from {@link #connect(String, java.util.Properties)} method
 * @return instance of real driver
 * @throws java.sql.SQLException if real driver can't be determined or is not registerd
 */
private java.sql.Driver getRealDriver(SimonConnectionConfiguration configuration, Properties info) throws SQLException {
	java.sql.Driver drv = null;
	try {
		drv = DriverManager.getDriver(configuration.getRealUrl());
	} catch (SQLException e) {
		// nothing, not an error
	}

	if (drv == null && info != null && info.keySet().contains(SimonConnectionConfiguration.REAL_DRIVER)) {
		drv = registerDriver(info.getProperty(SimonConnectionConfiguration.REAL_DRIVER));
	}

	if (drv == null && configuration.getRealDriver() != null) {
		drv = registerDriver(configuration.getRealDriver());
	}

	if (drv == null) {
		if (configuration.getRealDriver() != null) {
			drv = registerDriver(configuration.getRealDriver());
		}
	}

	if (drv == null) {
		throw new SQLException("Real driver is not registered and can't determine real driver class name for registration.");
	}
	return drv;
}
 
Example 5
Source File: DriverTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load the driver and check java.sql.Driver.jdbcCompliant() and
 * driver.get*Version
 * @throws Exception
 */
public void testDriverCompliantVersion() throws Exception
{
    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String url = TestConfiguration.getCurrent().getJDBCUrl(dbName);

    loadDriver();
    String defaultdburl = url + ";create=true";

    // Test that we loaded the right driver by making a connection
    Driver driver = DriverManager.getDriver(defaultdburl);
    Properties props = new Properties();
    props.put("user", "testuser");
    props.put("password", "testpass");
    Connection conn = DriverManager.getConnection(defaultdburl, props);
    // Driver should be jdbc compliant.
    assertTrue(driver.jdbcCompliant());

    // compare driver.get*Version() with DatabaseMetadata.getDriver*Version.
    DatabaseMetaData dbmd = conn.getMetaData();

    assertEquals(dbmd.getDriverMajorVersion(), driver.getMajorVersion());
    assertEquals(dbmd.getDriverMinorVersion(), driver.getMinorVersion());

    // test that the driver is one of the special 40 versions if we are running
    // on Java 6 or higher
    println( "Driver is a " + driver.getClass().getName() );
    assertEquals( JDBC.vmSupportsJDBC4(), driver.getClass().getName().endsWith( "40" ) );

    conn.close();
}
 
Example 6
Source File: DriverManagerTests.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate that DriverAction.release is called when a driver is registered
 * via registerDriver(Driver, DriverAction)
 *
 * @throws Exception
 */
@Test
public void test16() throws Exception {
    File file = new File(util.StubDriverDA.DriverActionCalled);
    file.delete();
    assertFalse(file.exists());
    Driver d = null;
    Class.forName("util.StubDriverDA");
    d = DriverManager.getDriver(StubDriverDAURL);
    DriverManager.deregisterDriver(d);
    assertFalse(isDriverRegistered(d), "Driver is registered");
    assertTrue(file.exists());
}
 
Example 7
Source File: BaseTest.java    From phoenix with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link PhoenixTestDriver} and register it.
 * @return an initialized and registered {@link PhoenixTestDriver} 
 */
protected static PhoenixTestDriver initAndRegisterDriver(String url, ReadOnlyProps props) throws Exception {
    PhoenixTestDriver newDriver = new PhoenixTestDriver(props);
    DriverManager.registerDriver(newDriver);
    Driver oldDriver = DriverManager.getDriver(url); 
    if (oldDriver != newDriver) {
        destroyDriver(oldDriver);
    }
    Connection conn = newDriver.connect(url, PropertiesUtil.deepCopy(TEST_PROPERTIES));
    conn.close();
    return newDriver;
}
 
Example 8
Source File: DriverManagerTests.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Register a driver and make sure you find it via its URL. Deregister the
 * driver and validate it is not longer registered
 *
 * @throws Exception
 */
@Test()
public void test15() throws Exception {
    DriverManager.registerDriver(new StubDriver());
    Driver d = DriverManager.getDriver(StubDriverURL);
    assertTrue(d != null);
    assertTrue(isDriverRegistered(d));
    DriverManager.deregisterDriver(d);
    assertFalse(isDriverRegistered(d));
}
 
Example 9
Source File: DriverManagerTests.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate that DriverAction.release is called when a driver is registered
 * via registerDriver(Driver, DriverAction)
 *
 * @throws Exception
 */
@Test
public void test16() throws Exception {
    File file = new File(util.StubDriverDA.DriverActionCalled);
    file.delete();
    assertFalse(file.exists());
    Driver d = null;
    Class.forName("util.StubDriverDA");
    d = DriverManager.getDriver(StubDriverDAURL);
    DriverManager.deregisterDriver(d);
    assertFalse(isDriverRegistered(d), "Driver is registered");
    assertTrue(file.exists());
}
 
Example 10
Source File: SlaveDatabase.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
     * Used to shutdown this database. 
     *
     * If an error occurs as part of the database boot process, we
     * hand the exception that caused boot to fail to the client
     * thread. The client thread will in turn shut down this database.
     *
     * If an error occurs at a later stage than during boot, we shut
     * down the database by setting up a connection with the shutdown
     * attribute. The internal connection is required because database
     * shutdown requires EmbedConnection to do cleanup.
     *
     * @param shutdownCause the reason why the database needs to be
     * shutdown
     */
    private void handleShutdown(StandardException shutdownCause) {
        if (inBoot) {
            bootException = shutdownCause;
            return;
        } 
        try {
            shutdownInitiated = true;
            String driverName = 
                "com.pivotal.gemfirexd.jdbc.EmbeddedDriver";

            Class.forName(driverName).newInstance();

            Driver embedDriver = 
                DriverManager.getDriver(com.pivotal.gemfirexd.Attribute.PROTOCOL);

// GemStone changes BEGIN
            String conStr = com.pivotal.gemfirexd.Attribute.PROTOCOL + ";" +
            /* String conStr = "jdbc:derby:"+dbname+";"+ */
// GemStone changes END
                Attribute.REPLICATION_INTERNAL_SHUTDOWN_SLAVE+
                "=true";

            embedDriver.connect(conStr, (Properties) null);
        } catch (Exception e) {
            // Todo: report error to gemfirexd.log if exception is not
            // SQLState.SHUTDOWN_DATABASE
        }
    }
 
Example 11
Source File: DriverManagerTests.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Register a driver and make sure you find it via its URL. Deregister the
 * driver and validate it is not longer registered
 *
 * @throws Exception
 */
@Test()
public void test15() throws Exception {
    DriverManager.registerDriver(new StubDriver());
    Driver d = DriverManager.getDriver(StubDriverURL);
    assertTrue(d != null);
    assertTrue(isDriverRegistered(d));
    DriverManager.deregisterDriver(d);
    assertFalse(isDriverRegistered(d));
}
 
Example 12
Source File: DriverTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Tests client URLs to see connection is successful or the correct exception is thrown.
 */
public void testClientURL() throws SQLException {
    if (!usingDerbyNetClient())
        return;

    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String protocol =
        TestConfiguration.getCurrent().getJDBCClient().getUrlBase();
    if (usingDerbyNetClient())
        protocol = protocol + TestConfiguration.getCurrent().getHostName()
        + ":" + TestConfiguration.getCurrent().getPort() + "/";

    Properties info = null;     //test with null Properties object

    String CLIENT_CREATE_URL_WITH_COLON1 =
        protocol + dbName + ":create=true";
    //String CLIENT_CREATE_URL_WITH_COLON2 = protocol + DERBY_SYSTEM_HOME +
    //   File.separator + dbName + ":create=true";
    // String CLIENT_CREATE_URL_WITH_DOUBLE_QUOTES1 =
    //     protocol + "\"" + dbName + "\";create=true";
    // String CLIENT_CREATE_URL_WITH_DOUBLE_QUOTES2 = protocol + "\"" +
    //     DERBY_SYSTEM_HOME + File.separator + dbName + "\";create=true";
    // String CLIENT_CREATE_URL_WITH_SINGLE_QUOTES1 = protocol + "'" +
    //     DERBY_SYSTEM_HOME + File.separator + dbName + "';create=true";
    String CLIENT_CREATE_URL_WITH_SINGLE_QUOTES2 =
        protocol + "'" + dbName + "';create=true";

    String CLIENT_SHUT_URL_WITH_SINGLE_QUOTES2 =
        protocol + "'" + dbName + "';shutdown=true";

    //Client URLS
    String[] clientCreateUrls = new String[]
    {
        CLIENT_CREATE_URL_WITH_COLON1,
        //CLIENT_URL_WITH_COLON2,
        //CLIENT_URL_WITH_DOUBLE_QUOTES1,
        //CLIENT_URL_WITH_DOUBLE_QUOTES2,
        //CLIENT_URL_WITH_SINGLE_QUOTES1,
        CLIENT_CREATE_URL_WITH_SINGLE_QUOTES2
    };

    for (int i = 0; i < clientCreateUrls.length;i++)
    {
        String url = clientCreateUrls[i];
        try{
            if (url.equals(CLIENT_CREATE_URL_WITH_COLON1))
            {
                Driver driver = DriverManager.getDriver(url);
                assertNull(driver.connect(url,info));
            }
            else
                assertConnect(true, url, info);
        }
        catch(SQLException se){
            fail ("did not expect an exception");
        }
    }
    // shutdown the databases, which should get rid of all open connections
    // currently, there's only the one; otherwise, this could be done in
    // a loop.
    shutdownDB(
        CLIENT_SHUT_URL_WITH_SINGLE_QUOTES2 + ";shutdown=true", null);
}
 
Example 13
Source File: SybaseInterServiceProviderTest.java    From dekaf with Apache License 2.0 4 votes vote down vote up
@Test
public void driverIsLoaded() throws SQLException {
  final Driver driver = DriverManager.getDriver(SYBASE_JTDS_CONNECTION_STRING_EXAMPLE);
  assertThat(driver).isNotNull();
}
 
Example 14
Source File: BxDriverManager.java    From beakerx with Apache License 2.0 4 votes vote down vote up
public static Driver getDriver(String url) throws SQLException {
  return DriverManager.getDriver(url);
}
 
Example 15
Source File: DriverManagerTests.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Validate that SQLException is thrown when the URL is not valid for any of
 * the registered drivers
 */
@Test(expectedExceptions = SQLException.class)
public void test13() throws Exception {
    DriverManager.registerDriver(new StubDriver());
    DriverManager.getDriver(InvalidURL);
}
 
Example 16
Source File: NetworkServerControlImpl.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/** 
	 * Load Derby and save driver for future use.
	 * We can't call Driver Manager when the client connects, 
	 * because they might be holding the DriverManager lock.
	 *
	 * 
	 */

	


// GemStone changes BEGIN
        @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="DM_GC")
// GemStone changes END
	protected void startNetworkServer() throws Exception
	{

		// we start the Derby server here.
		boolean restartCheck = this.restartFlag;
		synchronized (serverStartSync) {

			if (restartCheck == this.restartFlag) {
			// then we can go ahead and restart the server (odds
			// that some else has just done so are very slim (but not
			// impossible--however, even if it does happen, things
			// should still work correctly, just not as efficiently...))

				try {
	
					if (cleanupOnStart) {
					// we're restarting the server (probably after a shutdown
					// exception), so we need to clean up first.

						// Close and remove sessions on runQueue.
						synchronized (runQueue) {
							for (int i = 0; i < runQueue.size(); i++) {
								Session s = (Session) runQueue.get(i);
								s.close();
								removeFromSessionTable(s.getConnNum());
							}
							runQueue.clear();
						}

						// DERBY-1326: There could be active threads that
						// contain old/invalid sessions. These sessions won't
						// be cleaned up until there is some activity on
						// them. We could optimize this by going through
						// sessionTable and closing the sessions' socket
						// streams.

						// Unload driver, then restart the server.
						cloudscapeDriver = null;	// so it gets collected.
						System.gc();
					}

					// start the server.
					Class.forName(CLOUDSCAPE_DRIVER).newInstance();
					cloudscapeDriver = DriverManager.getDriver(com.pivotal.gemfirexd.Attribute.PROTOCOL);

				}
				catch (Exception e) {
                    this.consoleExceptionPrintTrace(e);
					consolePropertyMessage("DRDA_LoadException.S", e.getMessage());
				}
				cleanupOnStart = true;
				this.restartFlag = !this.restartFlag;
			}
			// else, multiple threads hit this synchronize block at the same
			// time, but one of them already executed it--so all others just
			// return and do nothing (no need to restart the server multiple
			// times in a row).
		}
	}
 
Example 17
Source File: DriverTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Check that drivers accept the correct urls and reject those for other supported drivers.
 *
 * @throws SQLException, Exception
 */
public void testAcceptsURL() throws SQLException, Exception {
    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String orgurl = TestConfiguration.getCurrent().getJDBCUrl(dbName);

    loadDriver();
    String defaultdburl = orgurl + ";create=true";

    // Test that we loaded the right driver by making a connection
    Driver driver = DriverManager.getDriver(defaultdburl);

    int  frameworkOffset;
    int EMBEDDED_OFFSET = 0;
    int DERBYNETCLIENT_OFFSET = 1;
    if (usingDerbyNetClient())
        frameworkOffset = DERBYNETCLIENT_OFFSET;
    else // assume (usingEmbedded())
        frameworkOffset = EMBEDDED_OFFSET;

    // URLS to check.  New urls need to also be added to the acceptsUrl table
    //GemStone changes BEGIN
    //String EMBEDDED_URL = "jdbc:derby:";
    String EMBEDDED_URL = "jdbc:gemfirexd:";
    // GemStone changes END
    String INVALID_URL = "jdbc:db2j:";
    String hostName = TestConfiguration.getCurrent().getHostName();
    int port = TestConfiguration.getCurrent().getPort();
    String CLIENT_URL =
        "jdbc:derby://"+hostName+":"+port+"/"+dbName+";create=true";

    String[] urls = new String[]
    {
        EMBEDDED_URL,
        CLIENT_URL,
        INVALID_URL,
    };

    // Table that shows whether tested urls should return true for
    // acceptsURL under the given framework
    // The acceptsURLTable uses  the frameworkOffset column int he table
    // to check for valid results for each framework
    boolean[][] acceptsURLTable = new boolean[][]
    {
    // Framework/url      EMBEDDED     DERBYNETCLIENT
    /* EMBEDDED_URL*/  {   true      ,  false        },
    /* CLIENT_URL  */  {   false     ,  true         },
    /* INVALID_URL */  {   false     ,  false        }
    };

    for (int u = 0; u < urls.length;u++)
    {
        String url = urls[u];
        boolean expectedAcceptance = acceptsURLTable[u][frameworkOffset];
        boolean actualAcceptance = driver.acceptsURL(url);
        assertEquals(expectedAcceptance, actualAcceptance);
    }
}
 
Example 18
Source File: DriverManagerTests.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Validate that SQLException is thrown when there is no Driver to service
 * the URL
 */
@Test(expectedExceptions = SQLException.class)
public void test10() throws Exception {
    DriverManager.getDriver(InvalidURL);
}
 
Example 19
Source File: CloudSpannerDriverTest.java    From spanner-jdbc with MIT License 4 votes vote down vote up
private static Driver getDriver() throws SQLException {
  return DriverManager.getDriver("jdbc:cloudspanner://localhost");
}
 
Example 20
Source File: SnowflakeDriverIT.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetPropertyInfo() throws SQLException
{
  // Test with blank URL and no properties. ServerURL is needed.
  String url = "";
  Properties props = new Properties();
  Driver driver = DriverManager.getDriver("jdbc:snowflake://snowflake.reg.local:8082");
  DriverPropertyInfo[] info = driver.getPropertyInfo(url, props);
  assertEquals(1, info.length);
  assertEquals("serverURL", info[0].name);
  assertEquals("server URL in form of <protocol>://<host or domain>:<port number>/<path of resource>",
               info[0].description);

  // Test with URL that requires username and password.
  url = "jdbc:snowflake://snowflake.reg.local:8082";
  info = driver.getPropertyInfo(url, props);
  assertEquals(2, info.length);
  assertEquals("user", info[0].name);
  assertEquals("username for account",
               info[0].description);
  assertEquals("password", info[1].name);
  assertEquals("password for account", info[1].description);

  // Add username and try again; get password requirement back
  props.put("user", "snowman");
  props.put("password", "test");
  info = driver.getPropertyInfo(url, props);
  assertEquals(0, info.length);

  props.put("useProxy", "true");
  info = driver.getPropertyInfo(url, props);
  assertEquals(2, info.length);
  assertEquals("proxyHost", info[0].name);
  assertEquals("proxy host name", info[0].description);
  assertEquals("proxyPort", info[1].name);
  assertEquals("proxy port; should be an integer", info[1].description);

  props.put("proxyHost", "dummyHost");
  props.put("proxyPort", "dummyPort");
  info = driver.getPropertyInfo(url, props);
  assertEquals(0, info.length);

  // invalid URL still throws SQLException
  try
  {
    url = "snowflake.reg.local:8082";
    driver.getPropertyInfo(url, props);
  }
  catch (SQLException e)
  {
    assertEquals((int) ErrorCode.INVALID_CONNECT_STRING.getMessageCode(), e.getErrorCode());
  }
}