List of usage examples for java.sql DriverManager getDriver
@CallerSensitive public static Driver getDriver(String url) throws SQLException
From source file:org.apache.jcs.auxiliary.disk.jdbc.JDBCDiskCachePoolAccess.java
/** * @param connectURI// w w w. jav a 2 s . c om * @param userName * @param password * @param maxActive max connetions * @throws Exception */ public void setupDriver(String connectURI, String userName, String password, int maxActive) throws Exception { // First, we'll need a ObjectPool that serves as the // actual pool of connections. // We'll use a GenericObjectPool instance, although // any ObjectPool implementation will suffice. ObjectPool connectionPool = new GenericObjectPool(null, maxActive); // TODO make configurable // By dfault the size is 8!!!!!!! ((GenericObjectPool) connectionPool).setMaxIdle(-1); // Next, we'll create a ConnectionFactory that the // pool will use to create Connections. // We'll use the DriverManagerConnectionFactory, // using the connect string passed in the command line // arguments. // Properties props = new Properties(); // props.setProperty( "user", userName ); // props.setProperty( "password", password ); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, userName, password); // Now we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. // PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); // Finally, we create the PoolingDriver itself... Class.forName("org.apache.commons.dbcp.PoolingDriver"); PoolingDriver driver = (PoolingDriver) DriverManager.getDriver(DRIVER_NAME); // ...and register our pool with it. driver.registerPool(this.getPoolName(), connectionPool); // Now we can just use the connect string // "jdbc:apache:commons:dbcp:jcs" // to access our pool of Connections. }
From source file:org.apache.jcs.auxiliary.disk.jdbc.JDBCDiskCachePoolAccess.java
/** * @throws Exception//w ww .j a va2s . c o m */ public void logDriverStats() throws Exception { PoolingDriver driver = (PoolingDriver) DriverManager.getDriver(DRIVER_NAME); ObjectPool connectionPool = driver.getConnectionPool(this.getPoolName()); if (connectionPool != null) { if (log.isDebugEnabled()) { log.debug(connectionPool); } if (log.isInfoEnabled()) { log.info("NumActive: " + getNumActiveInPool()); log.info("NumIdle: " + getNumIdleInPool()); } } else { log.warn("Could not find pool."); } }
From source file:org.apache.phoenix.query.BaseTest.java
/** * Create a {@link PhoenixTestDriver} and register it. * @return an initialized and registered {@link PhoenixTestDriver} *//*from w ww . j a va 2 s .c o m*/ public static PhoenixTestDriver initAndRegisterTestDriver(String url, ReadOnlyProps props) throws Exception { PhoenixTestDriver newDriver = new PhoenixTestDriver(props); DriverManager.registerDriver(newDriver); Driver oldDriver = DriverManager.getDriver(url); if (oldDriver != newDriver) { destroyDriver(oldDriver); } Properties driverProps = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = newDriver.connect(url, driverProps); conn.close(); return newDriver; }
From source file:org.castor.cpa.persistence.sql.connection.DriverConnectionFactory.java
/** * {@inheritDoc}/*from ww w.j av a 2s .c o m*/ */ public void initializeFactory(final PersistenceFactory factory) throws MappingException { _factory = factory; String driverName = _driver.getClassName(); if (driverName != null) { try { Class.forName(driverName).newInstance(); } catch (InstantiationException e) { String msg = Messages.format("jdo.engine.classNotInstantiable", driverName); LOG.error(msg, e); throw new MappingException(msg, e); } catch (IllegalAccessException e) { String msg = Messages.format("jdo.engine.classNotAccessable", driverName, "constructor"); LOG.error(msg, e); throw new MappingException(msg, e); } catch (ClassNotFoundException e) { String msg = "Can not load class " + driverName; LOG.error(msg, e); throw new MappingException(msg, e); } } _url = _driver.getUrl(); try { if (DriverManager.getDriver(_url) == null) { String msg = Messages.format("jdo.missingDriver", _url); LOG.error(msg); throw new MappingException(msg); } } catch (SQLException ex) { throw new MappingException(ex); } _props = new Properties(); Enumeration<? extends Param> params = _driver.enumerateParam(); while (params.hasMoreElements()) { Param param = params.nextElement(); _props.put(param.getName(), param.getValue()); } if (LOG.isDebugEnabled()) { LOG.debug("Using driver: " + driverName); } }
From source file:org.dspace.storage.rdbms.MockDatabaseManager.java
/** * Provide a means for a (web) application to cleanly terminate the connection pool. * @throws SQLException// w w w. j a va 2 s . c om */ @Mock public static synchronized void shutdown() throws SQLException { if (initialized) { initialized = false; // Get the registered DBCP pooling driver PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); // Close the named pool if (driver != null) driver.closePool(poolName); } }
From source file:org.dspace.storage.rdbms.MockDatabaseManager.java
/** * Initialize the DatabaseManager./* www .jav a 2 s .c o m*/ */ @Mock private static synchronized void initialize() throws SQLException { if (initialized) { return; } try { // Register basic JDBC driver Class.forName(ConfigurationManager.getProperty("db.driver")); // Register the DBCP driver Class.forName("org.apache.commons.dbcp.PoolingDriver"); // Read pool configuration parameter or use defaults // Note we check to see if property is null; getIntProperty returns // '0' if the property is not set OR if it is actually set to zero. // But 0 is a valid option... int maxConnections = ConfigurationManager.getIntProperty("db.maxconnections"); if (ConfigurationManager.getProperty("db.maxconnections") == null) { maxConnections = 30; } int maxWait = ConfigurationManager.getIntProperty("db.maxwait"); if (ConfigurationManager.getProperty("db.maxwait") == null) { maxWait = 5000; } int maxIdle = ConfigurationManager.getIntProperty("db.maxidle"); if (ConfigurationManager.getProperty("db.maxidle") == null) { maxIdle = -1; } boolean useStatementPool = ConfigurationManager.getBooleanProperty("db.statementpool", true); // Create object pool connectionPool = new GenericObjectPool(null, // PoolableObjectFactory // - set below maxConnections, // max connections GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, // don't // block // more than 5 // seconds maxIdle, // max idle connections (unlimited) true, // validate when we borrow connections from pool false // don't bother validation returned connections ); // ConnectionFactory the pool will use to create connections. ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( ConfigurationManager.getProperty("db.url"), ConfigurationManager.getProperty("db.username"), ConfigurationManager.getProperty("db.password")); // // Now we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. // String validationQuery = "SELECT 1"; // Oracle has a slightly different validation query if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { validationQuery = "SELECT 1 FROM DUAL"; } GenericKeyedObjectPoolFactory statementFactory = null; if (useStatementPool) { // The statement Pool is used to pool prepared statements. GenericKeyedObjectPool.Config statementFactoryConfig = new GenericKeyedObjectPool.Config(); // Just grow the pool size when needed. // // This means we will never block when attempting to // create a query. The problem is unclosed statements, // they can never be reused. So if we place a maximum // cap on them, then we might reach a condition where // a page can only be viewed X number of times. The // downside of GROW_WHEN_EXHAUSTED is that this may // allow a memory leak to exist. Both options are bad, // but I'd prefer a memory leak over a failure. // // Perhaps this decision should be derived from config parameters? statementFactoryConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW; statementFactory = new GenericKeyedObjectPoolFactory(null, statementFactoryConfig); } PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementFactory, validationQuery, // validation query false, // read only is not default for now false); // Autocommit defaults to none // Obtain a poolName from the config, default is "dspacepool" if (ConfigurationManager.getProperty("db.poolname") != null) { poolName = ConfigurationManager.getProperty("db.poolname"); } // // Finally, we get the PoolingDriver itself... // PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); // // ...and register our pool with it. // if (driver != null) driver.registerPool(poolName, connectionPool); //preload the contents of the database String s = new String(); StringBuilder sb = new StringBuilder(); String schemaPath = System.getProperty("db.schema.path"); if (null == schemaPath) throw new IllegalArgumentException("System property db.schema.path must be defined"); FileReader fr = new FileReader(new File(schemaPath)); BufferedReader br = new BufferedReader(fr); while ((s = br.readLine()) != null) { //we skip white lines and comments if (!"".equals(s.trim()) && !s.trim().startsWith("--")) { sb.append(s); } } br.close(); //we use ";" as a delimiter for each request. This assumes no triggers //nor other calls besides CREATE TABLE, CREATE SEQUENCE and INSERT //exist in the file String[] stmts = sb.toString().split(";"); //stablish the connection using the pool Connection con = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + poolName); Statement st = con.createStatement(); for (int i = 0; i < stmts.length; i++) { // we ensure that there is no spaces before or after the request string // in order to not execute empty statements if (!stmts[i].trim().equals("")) { st.executeUpdate(stmts[i]); log.debug("Loading into database: " + stmts[i]); } } //commit changes con.commit(); con.close(); // Old SimplePool init //DriverManager.registerDriver(new SimplePool()); initialized = true; } catch (SQLException se) { // Simply throw up SQLExceptions throw se; } catch (Exception e) { // Need to be able to catch other exceptions. Pretend they are // SQLExceptions, but do log log.warn("Exception initializing DB pool", e); throw new SQLException(e.toString()); } }
From source file:org.infoglue.cms.util.workflow.InfoGlueJDBCPropertySet.java
public void setupDriver(String connectURI, String userName, String password) throws Exception { String validationQuery = "select 1 from cmInfoGlueProperties"; logger.info("Setting up driver."); Class.forName(this.driverClassName).newInstance(); logger.info("dbcpWhenExhaustedAction:" + dbcpWhenExhaustedAction); logger.info("dbcpMaxActive:" + dbcpMaxActive); logger.info("dbcpMaxWait:" + dbcpMaxWait); logger.info("dbcpMaxIdle:" + dbcpMaxIdle); logger.info("dbcpValidationQuery:" + dbcpValidationQuery); int dbcpMaxActiveInt = 200; if (dbcpMaxActive != null && !dbcpMaxActive.equals("")) dbcpMaxActiveInt = Integer.parseInt(dbcpMaxActive); logger.info("dbcpMaxActiveInt:" + dbcpMaxActiveInt); connectionPool = new GenericObjectPool(null, dbcpMaxActiveInt); connectionPool.setTestOnBorrow(true); connectionFactory = new DriverManagerConnectionFactory(connectURI, userName, password); poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, validationQuery, false, true); Class.forName("org.apache.commons.dbcp.PoolingDriver"); driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); driver.registerPool("infoGlueJDBCPropertySet", connectionPool); }
From source file:org.infoglue.cms.util.workflow.InfoGlueJDBCPropertySet.java
public void printDriverStats() throws Exception { PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); ObjectPool connectionPool = driver.getConnectionPool("infoGlueJDBCPropertySet"); if (logger.isInfoEnabled()) { logger.info("NumActive: " + connectionPool.getNumActive()); logger.info("NumIdle: " + connectionPool.getNumIdle()); }//from w w w .j a v a 2 s.c o m }
From source file:org.infoglue.cms.util.workflow.InfoGlueJDBCPropertySet.java
public void shutdownDriver() throws Exception { PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); driver.closePool("infoGlueJDBCPropertySet"); }
From source file:org.onecmdb.core.utils.transform.jdbc.ClassLoaderBasicDataSource.java
/** * <p>Create (if necessary) and return the internal data source we are * using to manage our connections.</p> * * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the * "double checked locking" idiom in an attempt to avoid synchronizing * on every single call to this method. However, this idiom fails to * work correctly in the face of some optimizations that are legal for * a JVM to perform.</p>/*from ww w . jav a 2 s . co m*/ * * @throws SQLException if the object pool cannot be created. */ protected synchronized DataSource createDataSource() throws SQLException { // Return the pool if we have already created it if (dataSource != null) { return (dataSource); } // Load the JDBC driver class Driver driver = null; if (driverClassName != null) { try { Class driverClass = Class.forName(driverClassName, true, driverLoader); driver = (Driver) driverClass.newInstance(); //Class.forName(driverClassName); } catch (Throwable t) { String message = "Cannot load JDBC driver class '" + driverClassName + "'"; logWriter.println(message); t.printStackTrace(logWriter); throw new SQLNestedException(message, t); } } // Create a JDBC driver instance if (driver == null) { try { driver = DriverManager.getDriver(url); } catch (Throwable t) { String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'"; logWriter.println(message); t.printStackTrace(logWriter); throw new SQLNestedException(message, t); } } // Can't test without a validationQuery if (validationQuery == null) { setTestOnBorrow(false); setTestOnReturn(false); setTestWhileIdle(false); } // Create an object pool to contain our active connections if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned())) { connectionPool = new AbandonedObjectPool(null, abandonedConfig); } else { connectionPool = new GenericObjectPool(); } connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(maxIdle); connectionPool.setMinIdle(minIdle); connectionPool.setMaxWait(maxWait); connectionPool.setTestOnBorrow(testOnBorrow); connectionPool.setTestOnReturn(testOnReturn); connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun); connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); connectionPool.setTestWhileIdle(testWhileIdle); // Set up statement pool, if desired GenericKeyedObjectPoolFactory statementPoolFactory = null; if (isPoolPreparedStatements()) { statementPoolFactory = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key) GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait 1, // maxIdle (per key) maxOpenPreparedStatements); } // Set up the driver connection factory we will use if (username != null) { connectionProperties.put("user", username); } else { log("DBCP DataSource configured without a 'username'"); } if (password != null) { connectionProperties.put("password", password); } else { log("DBCP DataSource configured without a 'password'"); } DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties); // Set up the poolable connection factory we will use PoolableConnectionFactory connectionFactory = null; try { connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, abandonedConfig); if (connectionFactory == null) { throw new SQLException("Cannot create PoolableConnectionFactory"); } validateConnectionFactory(connectionFactory); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e); } // Create and return the pooling data source to manage the connections dataSource = new PoolingDataSource(connectionPool); ((PoolingDataSource) dataSource) .setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed()); dataSource.setLogWriter(logWriter); try { for (int i = 0; i < initialSize; i++) { connectionPool.addObject(); } } catch (Exception e) { throw new SQLNestedException("Error preloading the connection pool", e); } return dataSource; }