List of usage examples for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool
public GenericObjectPool()
From source file:TestObjectPool.java
public static void main(String args[]) throws Exception { GenericObjectPool pool = new GenericObjectPool(); pool.setFactory(new EmployeeFactory()); /*First way of initializing pool pool.setMinIdle(5);//from w w w . j a v a2 s . c o m pool.setTimeBetweenEvictionRunsMillis(500); Thread.currentThread().sleep(600);*/ /* second, and preferred way */ for(int i = 0; i < 5; ++i) { pool.addObject(); } // pool.setTestOnReturn(true); pool.setMinEvictableIdleTimeMillis(1000); pool.setTimeBetweenEvictionRunsMillis(600); System.err.println("Number of employees in pool: " + pool.getNumIdle()); Thread.currentThread().sleep(1500); Employee employee = (Employee)pool.borrowObject(); employee.setName("Fred Flintstone"); employee.doWork(); System.err.println("Employee: " + employee); pool.returnObject(employee); System.err.println("Number of employees in pool: " + pool.getNumIdle()); }
From source file:ConnectionPoolBasics.java
public static void main(String args[]) throws Exception { GenericObjectPool gPool = new GenericObjectPool(); /*Class.forName("com.mysql.jdbc.Driver"); // w w w . j a v a 2 s . co m DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory( "jdbc:mysql://localhost/commons", "root", "");*/ Properties props = new Properties(); props.setProperty("Username", "root"); props.setProperty("Password", ""); ConnectionFactory cf = new DriverConnectionFactory(new com.mysql.jdbc.Driver(), "jdbc:mysql://localhost/commons", props); KeyedObjectPoolFactory kopf = new GenericKeyedObjectPoolFactory(null, 8); PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, gPool, kopf, null, false, true); for (int i = 0; i < 5; i++) { gPool.addObject(); } // PoolingDataSource pds = new PoolingDataSource(gPool); PoolingDriver pd = new PoolingDriver(); pd.registerPool("example", gPool); for (int i = 0; i < 5; i++) { gPool.addObject(); } Connection conn = java.sql.DriverManager.getConnection("jdbc:apache:commons:dbcp:example"); System.err.println("Connection: " + conn); //": Delegate: " + ((org.apache.commons.dbcp.PoolingConnection)conn).getDelegate()); // do some work with the connection PreparedStatement ps = conn.prepareStatement("Select * from customer where id = ?"); System.err.println("Active: " + gPool.getNumActive() + ", Idle: " + gPool.getNumIdle()); conn.close(); System.err.println("Active: " + gPool.getNumActive() + ", Idle: " + gPool.getNumIdle()); }
From source file:com.hangum.tadpole.tajo.core.connections.manager.ConnectionPoolManager.java
private static DataSource makePool(UserDBDAO userDB) { GenericObjectPool connectionPool = new GenericObjectPool(); connectionPool.setMaxActive(5);/* ww w . j a v a 2s .c o m*/ // connectionPool.setWhenExhaustedAction((byte)1); // connectionPool.setMaxWait(1000 * 60); // 1. // connectionPool.setTimeBetweenEvictionRunsMillis(3 * 1000); connectionPool.setTestWhileIdle(true); String passwdDecrypt = ""; try { passwdDecrypt = CipherManager.getInstance().decryption(userDB.getPasswd()); } catch (Exception e) { passwdDecrypt = userDB.getPasswd(); } ConnectionFactory cf = new DriverManagerConnectionFactory(userDB.getUrl(), userDB.getUsers(), passwdDecrypt); PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, connectionPool, null, null, false, true); DataSource ds = new PoolingDataSource(connectionPool); mapDataSource.put(getKey(userDB), ds); return ds; }
From source file:com.peanuts.database.DatabaseFactory.java
public static void init(String filename) { if (dataSource != null) { return;//from w w w . ja v a 2 s .c om } JDBCConfig.init(filename); try { java.lang.Class.forName(JDBCConfig.JDBC_DRIVER).newInstance(); } catch (Exception e) { log.fatal("Error obtaining DB driver", e); throw new Error("DB Driver doesnt exist!"); } connectionPool = new GenericObjectPool(); connectionPool.setMaxIdle(JDBCConfig.JDBC_CONNECTION_MIN); connectionPool.setMaxActive(JDBCConfig.JDBC_CONNECTION_MAX); try { dataSource = setupDataSource(); Connection c = dataSource.getConnection(); /** On verifie que la connection fonctionne bien **/ c.close(); } catch (Exception e) { log.fatal("Error with mysql connection to : " + JDBCConfig.JDBC_URL + " | user : " + JDBCConfig.JDBC_USER + " | password :" + JDBCConfig.JDBC_PASSWORD); throw new Error("Database mysql not initialized!"); } log.info("Successfully connected to database and pool initialization"); }
From source file:com.panet.imeta.core.database.ConnectionPoolUtil.java
private static void createPool(DatabaseMeta databaseMeta, String partitionId, int initialSize, int maximumSize) throws KettleDatabaseException { LogWriter.getInstance().logBasic(databaseMeta.toString(), Messages.getString("Database.CreatingConnectionPool", databaseMeta.getName())); GenericObjectPool gpool = new GenericObjectPool(); gpool.setMaxIdle(-1);//from w w w .j a v a 2 s. co m gpool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW); gpool.setMaxActive(maximumSize); String clazz = databaseMeta.getDriverClass(); try { Class.forName(clazz).newInstance(); } catch (Exception e) { throw new KettleDatabaseException(Messages.getString( "Database.UnableToLoadConnectionPoolDriver.Exception", databaseMeta.getName(), clazz), e); } String url; String userName; String password; try { url = databaseMeta.environmentSubstitute(databaseMeta.getURL(partitionId)); userName = databaseMeta.environmentSubstitute(databaseMeta.getUsername()); password = databaseMeta.environmentSubstitute(databaseMeta.getPassword()); } catch (RuntimeException e) { url = databaseMeta.getURL(partitionId); userName = databaseMeta.getUsername(); password = databaseMeta.getPassword(); } // Get the list of pool properties Properties originalProperties = databaseMeta.getConnectionPoolingProperties(); //Add user/pass originalProperties.setProperty("user", Const.NVL(userName, "")); originalProperties.setProperty("password", Const.NVL(password, "")); // Now, replace the environment variables in there... Properties properties = new Properties(); Iterator<Object> iterator = originalProperties.keySet().iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = originalProperties.getProperty(key); properties.put(key, databaseMeta.environmentSubstitute(value)); } // Create factory using these properties. // ConnectionFactory cf = new DriverManagerConnectionFactory(url, properties); new PoolableConnectionFactory(cf, gpool, null, null, false, false); for (int i = 0; i < initialSize; i++) { try { gpool.addObject(); } catch (Exception e) { throw new KettleDatabaseException( Messages.getString("Database.UnableToPreLoadConnectionToConnectionPool.Exception"), e); } } pd.registerPool(databaseMeta.getName(), gpool); LogWriter.getInstance().logBasic(databaseMeta.toString(), Messages.getString("Database.CreatedConnectionPool", databaseMeta.getName())); }
From source file:com.hangum.tadpole.engine.manager.transaction.DBCPConnectionManager.java
private DataSource makePool(final String userId, UserDBDAO userDB) { GenericObjectPool connectionPool = new GenericObjectPool(); connectionPool.setMaxActive(2);//from w w w . j ava 2 s . co m // connectionPool.setWhenExhaustedAction((byte)1); // connectionPool.setMaxWait(1000 * 60); // 1. // connectionPool.setTimeBetweenEvictionRunsMillis(3 * 1000); connectionPool.setTestWhileIdle(true); String passwdDecrypt = ""; try { passwdDecrypt = CipherManager.getInstance().decryption(userDB.getPasswd()); } catch (Exception e) { passwdDecrypt = userDB.getPasswd(); } ConnectionFactory cf = new DriverManagerConnectionFactory(userDB.getUrl(), userDB.getUsers(), passwdDecrypt); PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, connectionPool, null, null, false, true); DataSource ds = new PoolingDataSource(connectionPool); mapDataSource.put(TadpoleSQLTransactionManager.getKey(userId, userDB), ds); return ds; }
From source file:com.mapd.parser.server.CalciteServerHandler.java
CalciteServerHandler(int mapDPort, String dataDir, String extensionFunctionsAstFile) { this.parserPool = new GenericObjectPool(); this.mapDPort = mapDPort; Map<String, ExtensionFunction> extSigs = null; try {/*from w ww . j a v a 2 s . c o m*/ extSigs = ExtensionFunctionSignatureParser.parse(extensionFunctionsAstFile); } catch (IOException ex) { MAPDLOGGER.error("Could not load extension function signatures: " + ex.getMessage()); } this.extSigsJson = ExtensionFunctionSignatureParser.signaturesToJson(extSigs); PoolableObjectFactory parserFactory = new CalciteParserFactory(dataDir, extSigs); parserPool.setFactory(parserFactory); }
From source file:com.mapd.parser.server.CalciteDirect.java
public CalciteDirect(int port, String dataDir, String extensionFunctionsAstFile) { Properties p = new Properties(); try {//from w w w .j a v a 2s . co m p.load(getClass().getResourceAsStream("/log4j.properties")); } catch (IOException ex) { MAPDLOGGER.error("Could not load log4j property file from resources " + ex.getMessage()); } p.put("log.dir", dataDir); // overwrite "log.dir" PropertyConfigurator.configure(p); MAPDLOGGER.debug("CalciteDirect Constructor port is '" + port + "' data dir is '" + dataDir + "'"); MAPDLOGGER.debug("Extension signatures file is " + extensionFunctionsAstFile); this.parserPool = new GenericObjectPool(); this.mapDPort = port; Map<String, ExtensionFunction> extSigs = null; try { extSigs = ExtensionFunctionSignatureParser.parse(extensionFunctionsAstFile); } catch (IOException ex) { MAPDLOGGER.error("Could not load extension function signatures: " + ex.getMessage()); } this.extSigsJson = ExtensionFunctionSignatureParser.signaturesToJson(extSigs); PoolableObjectFactory parserFactory = new CalciteParserFactory(dataDir, extSigs); parserPool.setFactory(parserFactory); parserPool.setTestOnReturn(true); }
From source file:com.springsource.insight.plugin.jdbc.PoolingConnectionTest.java
@Test public void testOperationCollection() throws SQLException { DataSourceConnectionFactory connFactory = new DataSourceConnectionFactory(dataSource); ObjectPool connPool = new GenericObjectPool(); PoolableConnectionFactory poolFactory = new PoolableConnectionFactory(connFactory, connPool, null, null, false, true);// w w w .java 2 s .c om PoolingDataSource poolDs = new PoolingDataSource(poolFactory.getPool()); String sql = "select * from appointment where owner = 'Agim'"; Connection c = poolDs.getConnection(); try { PreparedStatement ps = c.prepareStatement(sql); try { System.out.println("Prepared statement=" + ps.getClass()); ResultSet rs = ps.executeQuery(); rs.close(); } finally { ps.close(); } } finally { c.close(); } ArgumentCaptor<Operation> opCaptor = ArgumentCaptor.forClass(Operation.class); verify(spiedOperationCollector, times(3)).enter(opCaptor.capture()); List<Operation> ops = opCaptor.getAllValues(); assertEquals("Mismatched number of operations", 3, ops.size()); assertSourceCodeLocation("top-op", ops.get(0), "org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper", "prepareStatement"); assertSourceCodeLocation("mid-op", ops.get(1), "org.apache.commons.dbcp.DelegatingConnection", "prepareStatement"); assertSourceCodeLocation("bottom-op", ops.get(2), "org.hsqldb.jdbc.jdbcConnection", "prepareStatement"); }
From source file:com.qualogy.qafe.business.resource.rdb.DriverManagerDataSource.java
public void init(ApplicationContext context) { DriverManagerResource driverManagerResource = (DriverManagerResource) getBindResource(); String userName = driverManagerResource.getUsername(); String password = driverManagerResource.getPassword(); String url = driverManagerResource.getUrl(); String driverClassName = driverManagerResource.getDriverClassName(); DataSource springDS = new org.springframework.jdbc.datasource.DriverManagerDataSource(url, userName, password);// w w w . j a va2s. c om ((org.springframework.jdbc.datasource.DriverManagerDataSource) springDS) .setDriverClassName(driverClassName); GenericObjectPool pool = new GenericObjectPool(); pool.setMinEvictableIdleTimeMillis(300000); pool.setTimeBetweenEvictionRunsMillis(60000); PoolableConnectionFactory connectionFactory = new PoolableConnectionFactory( new DataSourceConnectionFactory(springDS), pool, null, null, false, true); PoolingDataSource poolingDataSource = new PoolingDataSource(pool); poolingDataSource.setAccessToUnderlyingConnectionAllowed(true); setDataSource(poolingDataSource); postInit(context); }