List of usage examples for org.apache.commons.dbcp BasicDataSource setMaxActive
public synchronized void setMaxActive(int maxActive)
From source file:fi.ni.IFC_ClassModel.java
public void listRDF(OutputStream outputStream, String path, VirtConfig virt) throws IOException, SQLException { BufferedWriter out = null;/*from w ww .j a v a 2 s.c o m*/ Connection c = null; String prefix_query = "PREFIX : <" + path + "> " + "PREFIX instances: <http://drum.cs.hut.fi/instances#> " + "PREFIX owl: <" + Namespace.OWL + "> " + "PREFIX ifc: <" + Namespace.IFC + "> " + "PREFIX xsd: <" + Namespace.XSD + "> " + "INSERT IN GRAPH <" + path + "> { "; try { //Setup file output out = new BufferedWriter(new OutputStreamWriter(outputStream)); out.write("@prefix : <" + path + ">.\n"); out.write("@prefix instances: <http://drum.cs.hut.fi/instances#>. \n"); out.write("@prefix owl: <" + Namespace.OWL + "> .\n"); out.write("@prefix ifc: <" + Namespace.IFC + "> .\n"); out.write("@prefix xsd: <" + Namespace.XSD + "> .\n"); out.write("\n"); //If necessary, setup virtuoso connection if (virt != null) { BasicDataSource dataSource = new BasicDataSource(); dataSource.setUsername(virt.user); dataSource.setPassword(virt.password); dataSource.setUrl(virt.jdbc_uri); dataSource.setMaxActive(100); dataSource.setDriverClassName("virtuoso.jdbc4.Driver"); c = dataSource.getConnection(); } for (Map.Entry<Long, Thing> entry : object_buffer.entrySet()) { Thing gobject = entry.getValue(); String triples = generateTriples(gobject); out.write(triples); if (virt != null) { Statement stmt = c.createStatement(); StringBuilder queryString = new StringBuilder(); queryString.append(prefix_query); queryString.append(triples); queryString.append("}"); boolean more = stmt.execute("sparql " + queryString.toString()); if (!more) { System.err.println("INSERT failed."); } if (stmt != null) stmt.close(); } } } finally { if (out != null) out.close(); if (c != null) c.close(); } }
From source file:com.headstrong.fusion.services.dbpool.impl.DbPool.java
/** * package level constructor to create new dbpool instance. * /*from w ww . j av a2 s .c o m*/ * @param props * properties that needs to be set for creating the pool. * @throws FusionException * Error initializing dbpool */ /* package */ DbPool(Map<String, String> props, String dbcp) throws FusionException { BasicDataSource basicDataSource = new BasicDataSource(); if (dbProps == null) { dbProps = new HashMap<String, String>(props); } if (checkMandatoryProperties(props)) { basicDataSource.setDriverClassName(props.get(FusionConstants.DATABASE_CLASSNAME)); basicDataSource.setUsername(props.get(FusionConstants.DATABASE_USERNAME)); basicDataSource.setPassword(props.get(FusionConstants.DATABASE_PASSWORD)); basicDataSource.setUrl(props.get(FusionConstants.DATABASE_URL)); basicDataSource.setMinEvictableIdleTimeMillis(this.MINEVICTABLEIDLETIMEMILLIS); basicDataSource.setTimeBetweenEvictionRunsMillis(this.TIMEBETWEENEVICTIONRUNSMILLIS); String JDBCINITIALSIZE = props.get(FusionConstants.JDBCINITIALSIZE) != null ? props.get(FusionConstants.JDBCINITIALSIZE) : dbProps.get(FusionConstants.JDBCINITIALSIZE); basicDataSource.setInitialSize(Integer.parseInt(JDBCINITIALSIZE)); String JDBCMAXACTIVE = props.get(FusionConstants.JDBCMAXACTIVE) != null ? props.get(FusionConstants.JDBCMAXACTIVE) : dbProps.get(FusionConstants.JDBCMAXACTIVE); basicDataSource.setMaxActive(Integer.parseInt(JDBCMAXACTIVE)); String JDBCMAXOPENACTIVEPREP = props.get(FusionConstants.JDBCMAXOPENACTIVEPREP) != null ? props.get(FusionConstants.JDBCMAXOPENACTIVEPREP) : dbProps.get(FusionConstants.JDBCMAXOPENACTIVEPREP); basicDataSource.setMaxOpenPreparedStatements(Integer.parseInt(JDBCMAXOPENACTIVEPREP)); String MINEVICTABLEIDLETIMEMILLIS = props.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS) != null ? props.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS) : dbProps.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS); basicDataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(MINEVICTABLEIDLETIMEMILLIS)); String TIMEBETWEENEVICTIONRUNSMILLIS = props.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS) != null ? props.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS) : dbProps.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS); basicDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(TIMEBETWEENEVICTIONRUNSMILLIS)); /* * if (props.get(FusionConstants.JDBCINITIALSIZE) == null) { * basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.JDBCINITIALSIZE))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.JDBCINITIALSIZE))); } if * (props.get(FusionConstants.JDBCMAXACTIVE) == null) { * basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.JDBCMAXACTIVE))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.JDBCMAXACTIVE))); } if * (props.get(FusionConstants.JDBCMAXOPENACTIVEPREP) == null) { * basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.JDBCMAXOPENACTIVEPREP))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.JDBCMAXOPENACTIVEPREP))); } * * if (props.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS) == * null) { basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS))); } if * (props.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS) == * null) { basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS))); } */ dataSource = basicDataSource; } else { throw new FusionException("Error initializing dbpool"); } }
From source file:edu.tamu.tcat.db.core.AbstractDataSourceFactory.java
/** * Create a new {@link BasicDataSource} from the specified {@link DSProperties} *//*from w w w. ja v a 2 s. c o m*/ protected synchronized BasicDataSource createDataSource(final Properties parameters) throws DataSourceException { BasicDataSource dataSource; final Driver driver = getDriver(); final String connectionUrl = getConnectionUrl(parameters); final Properties connectionProps = getConnectionProperties(parameters); dataSource = new BasicDataSource() { @Override protected ConnectionFactory createConnectionFactory() throws SQLException { //The loading of the driver via class-loader does not work properly in OSGI. if (driver.acceptsURL(getUrl())) { if (getValidationQuery() == null) { setTestOnBorrow(false); setTestOnReturn(false); setTestWhileIdle(false); } ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectionUrl, connectionProps); return driverConnectionFactory; } return super.createConnectionFactory(); } }; // dataSource.setDriverClassLoader(Driver.class.getClassLoader()); // should be included in the connection properties and not needed // dataSource.setUsername(key.getUsername()); // dataSource.setPassword(key.getPassword()); dataSource.setDriverClassName(driver.getClass().getName()); dataSource.setUrl(connectionUrl); dataSource.setMaxActive(getMaxActiveConnections(parameters)); dataSource.setMaxIdle(getMaxIdleConnections(parameters)); dataSource.setMinIdle(0); dataSource.setMinEvictableIdleTimeMillis(10000); dataSource.setTimeBetweenEvictionRunsMillis(1000); dataSource.setLogAbandoned(true); dataSource.setRemoveAbandoned(true);//seconds dataSource.setRemoveAbandonedTimeout(60); return dataSource; }
From source file:jetsennet.orm.datasource.DbcpDataSourceCreator.java
@Override public DataSource createDatasource(ConnectionInfo conn, DbPoolInfo props) throws SQLException { org.apache.commons.dbcp.BasicDataSource dataSource = new org.apache.commons.dbcp.BasicDataSource(); dataSource.setDriverClassName(conn.driver); dataSource.setUrl(conn.url);//from w w w. j a v a 2 s .c om dataSource.setUsername(conn.user); dataSource.setPassword(conn.pwd); String connectionProperties = props.get("connectionProperties"); if (connectionProperties != null && connectionProperties.trim().length() > 0) { dataSource.setConnectionProperties(connectionProperties); } Boolean defaultAutoCommit = Utils.str2Boolean(props.get("defaultAutoCommit")); if (defaultAutoCommit != null) { dataSource.setDefaultAutoCommit(defaultAutoCommit); } Boolean defaultReadOnly = Utils.str2Boolean(props.get("defaultReadOnly")); if (defaultReadOnly != null) { dataSource.setDefaultReadOnly(defaultReadOnly); } Integer defaultTransactionIsolation = Utils.strToInteger(props.get("defaultTransactionIsolation")); if (defaultTransactionIsolation != null) { dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation); } String defaultCatalog = props.get("defaultCatalog"); if (defaultCatalog != null && defaultCatalog.trim().length() > 0) { dataSource.setDefaultCatalog(defaultCatalog); } int initialSize = Utils.strToInt(props.get("initialSize")); if (initialSize > 0) { dataSource.setInitialSize(initialSize); } int maxActive = Utils.strToInt(props.get("maxActive")); if (maxActive > 0) { dataSource.setMaxActive(maxActive); } int maxIdle = Utils.strToInt(props.get("maxIdle")); if (maxIdle > 0) { dataSource.setMaxIdle(maxIdle); } int minIdle = Utils.strToInt(props.get("minIdle")); if (minIdle > 0) { dataSource.setMinIdle(minIdle); } int maxWait = Utils.strToInt(props.get("maxWait")); if (maxWait > 0) { dataSource.setMaxWait(maxWait); } String validationQuery = props.get("validationQuery"); if (validationQuery != null && validationQuery.trim().length() > 0) { dataSource.setValidationQuery(validationQuery); } Integer validationQueryTimeout = Utils.strToInteger(props.get("validationQueryTimeout")); if (validationQueryTimeout != null) { dataSource.setValidationQueryTimeout(validationQueryTimeout); } Boolean testOnBorrow = Utils.str2Boolean(props.get("testOnBorrow")); if (testOnBorrow != null) { dataSource.setTestOnBorrow(testOnBorrow); } Boolean testOnReturn = Utils.str2Boolean(props.get("testOnReturn")); if (testOnReturn != null) { dataSource.setTestOnReturn(testOnReturn); } Boolean testWhileIdle = Utils.str2Boolean(props.get("testWhileIdle")); if (testWhileIdle != null) { dataSource.setTestWhileIdle(testWhileIdle); } Integer timeBetweenEvictionRunsMillis = Utils.strToInteger(props.get("timeBetweenEvictionRunsMillis")); if (timeBetweenEvictionRunsMillis != null) { dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); } Integer numTestsPerEvictionRun = Utils.strToInteger(props.get("numTestsPerEvictionRun")); if (numTestsPerEvictionRun != null) { dataSource.setNumTestsPerEvictionRun(numTestsPerEvictionRun); } int minEvictableIdleTimeMillis = Utils.strToInt(props.get("minEvictableIdleTimeMillis")); if (minEvictableIdleTimeMillis > 0) { dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); } Boolean removeAbandoned = Utils.str2Boolean(props.get("removeAbandoned")); if (removeAbandoned != null) { dataSource.setRemoveAbandoned(removeAbandoned); } int removeAbandonedTimeout = Utils.strToInt(props.get("removeAbandonedTimeout")); if (removeAbandonedTimeout > 0) { dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); } Boolean logAbandoned = Utils.str2Boolean(props.get("logAbandoned")); if (logAbandoned != null) { dataSource.setLogAbandoned(logAbandoned); } return dataSource; }
From source file:org.apache.jackrabbit.core.util.db.ConnectionFactory.java
/** * Registers a number of data sources.//from www.ja va2s . c o m * * @param dsc the {@link DataSourceConfig} which contains the configuration */ public void registerDataSources(DataSourceConfig dsc) throws RepositoryException { synchronized (lock) { sanityCheck(); for (DataSourceDefinition def : dsc.getDefinitions()) { Class<?> driverClass = getDriverClass(def.getDriver()); if (driverClass != null && Context.class.isAssignableFrom(driverClass)) { DataSource ds = getJndiDataSource((Class<Context>) driverClass, def.getUrl()); nameToDataSource.put(def.getLogicalName(), ds); nameToDataSourceDef.put(def.getLogicalName(), def); } else { BasicDataSource bds = getDriverDataSource(driverClass, def.getUrl(), def.getUser(), def.getPassword()); if (def.getMaxPoolSize() > 0) { bds.setMaxActive(def.getMaxPoolSize()); } if (def.getValidationQuery() != null && !"".equals(def.getValidationQuery().trim())) { bds.setValidationQuery(def.getValidationQuery()); } nameToDataSource.put(def.getLogicalName(), bds); nameToDataSourceDef.put(def.getLogicalName(), def); } } } }
From source file:org.apache.jackrabbit.core.util.db.ConnectionFactory.java
/** * Creates and returns a pooling JDBC {@link DataSource} for accessing * the database identified by the given driver class and JDBC * connection URL. The driver class can be <code>null</code> if * a specific driver has not been configured. * * @param driverClass the JDBC driver class, or <code>null</code> * @param url the JDBC connection URL/* w ww.j a v a 2s . c om*/ * @return pooling DataSource for accessing the specified database */ private BasicDataSource getDriverDataSource(Class<?> driverClass, String url, String user, String password) { BasicDataSource ds = new BasicDataSource(); created.add(ds); if (driverClass != null) { Driver instance = null; try { // Workaround for Apache Derby: // The JDBC specification recommends the Class.forName // method without the .newInstance() method call, // but it is required after a Derby 'shutdown' instance = (Driver) driverClass.newInstance(); } catch (Throwable e) { // Ignore exceptions as there's no requirement for // a JDBC driver class to have a public default constructor } if (instance != null) { if (instance.jdbcCompliant()) { // JCR-3445 At the moment the PostgreSQL isn't compliant because it doesn't implement this method... ds.setValidationQueryTimeout(3); } } ds.setDriverClassName(driverClass.getName()); } ds.setUrl(url); ds.setUsername(user); ds.setPassword(password); ds.setDefaultAutoCommit(true); ds.setTestOnBorrow(false); ds.setTestWhileIdle(true); ds.setTimeBetweenEvictionRunsMillis(600000); // 10 Minutes ds.setMinEvictableIdleTimeMillis(60000); // 1 Minute ds.setMaxActive(-1); // unlimited ds.setMaxIdle(GenericObjectPool.DEFAULT_MAX_IDLE + 10); ds.setValidationQuery(guessValidationQuery(url)); ds.setAccessToUnderlyingConnectionAllowed(true); ds.setPoolPreparedStatements(true); ds.setMaxOpenPreparedStatements(-1); // unlimited return ds; }
From source file:org.apache.kylin.query.QueryDataSource.java
private static WrappedDataSource getWrapped(String project, KylinConfig config, Properties props) { File olapTmp = OLAPSchemaFactory.createTempOLAPJson(project, config); if (logger.isDebugEnabled()) { try {//from w ww .ja v a2s .c o m String text = FileUtils.readFileToString(olapTmp, Charset.defaultCharset()); logger.debug("The new temp olap json is :" + text); } catch (IOException e) { // logging failure is not critical } } BasicDataSource ds = null; if (StringUtils.isEmpty(props.getProperty("maxActive"))) { props.setProperty("maxActive", "-1"); } try { ds = (BasicDataSource) BasicDataSourceFactory.createDataSource(props); } catch (Exception e) { // Basic mode ds = new BasicDataSource(); ds.setMaxActive(-1); } ds.setUrl("jdbc:calcite:model=" + olapTmp.getAbsolutePath()); ds.setDriverClassName(Driver.class.getName()); WrappedDataSource wrappedDS = new WrappedDataSource(ds, olapTmp); return wrappedDS; }
From source file:org.apache.metamodel.jdbc.JdbcDataContextTest.java
public void testReleaseConnectionsInCompiledQuery() throws Exception { final int connectionPoolSize = 2; final int threadCount = 4; final int noOfCallsPerThreads = 30; final BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:res:metamodel"); ds.setInitialSize(connectionPoolSize); ds.setMaxActive(connectionPoolSize); ds.setMaxWait(10000);//from www. j a va 2 s .c om ds.setMinEvictableIdleTimeMillis(1800000); ds.setMinIdle(0); ds.setMaxIdle(connectionPoolSize); ds.setNumTestsPerEvictionRun(3); ds.setTimeBetweenEvictionRunsMillis(-1); ds.setDefaultTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED); final JdbcDataContext dataContext = new JdbcDataContext(ds, new TableType[] { TableType.TABLE, TableType.VIEW }, null); final JdbcCompiledQuery compiledQuery = (JdbcCompiledQuery) dataContext.query().from("CUSTOMERS") .select("CUSTOMERNAME").where("CUSTOMERNUMBER").eq(new QueryParameter()).compile(); assertEquals(0, compiledQuery.getActiveLeases()); assertEquals(0, compiledQuery.getIdleLeases()); final String compliedQueryString = compiledQuery.toSql(); assertEquals( "SELECT _CUSTOMERS_._CUSTOMERNAME_ FROM PUBLIC._CUSTOMERS_ WHERE _CUSTOMERS_._CUSTOMERNUMBER_ = ?", compliedQueryString.replace('\"', '_')); assertEquals(0, compiledQuery.getActiveLeases()); assertEquals(0, compiledQuery.getIdleLeases()); ExecutorService executorService = Executors.newFixedThreadPool(threadCount); final CountDownLatch latch = new CountDownLatch(threadCount); final List<Throwable> errors = new ArrayList<Throwable>(); final Runnable runnable = new Runnable() { @Override public void run() { try { for (int i = 0; i < noOfCallsPerThreads; i++) { final DataSet dataSet = dataContext.executeQuery(compiledQuery, new Object[] { 103 }); try { assertTrue(dataSet.next()); Row row = dataSet.getRow(); assertNotNull(row); assertEquals("Atelier graphique", row.getValue(0).toString()); assertFalse(dataSet.next()); } finally { dataSet.close(); } } } catch (Throwable e) { errors.add(e); } finally { latch.countDown(); } } }; for (int i = 0; i < threadCount; i++) { executorService.execute(runnable); } try { latch.await(60000, TimeUnit.MILLISECONDS); if (errors.size() > 0) { throw new IllegalStateException(errors.get(0)); } assertTrue(true); } finally { executorService.shutdownNow(); } assertEquals(0, compiledQuery.getActiveLeases()); compiledQuery.close(); assertEquals(0, compiledQuery.getActiveLeases()); assertEquals(0, compiledQuery.getIdleLeases()); }
From source file:org.apache.metamodel.jdbc.JdbcUpdateCallbackTest.java
@Test public void testTransactionalUpdateScripts() throws Exception { DerbyTest.initDerbySettings();/* w w w.ja v a2 s . com*/ final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver"); dataSource.setUrl("jdbc:derby:target/temp_derby;create=true"); dataSource.setInitialSize(10); dataSource.setMaxActive(10); dataSource.setMaxWait(10000); dataSource.setMinEvictableIdleTimeMillis(1800000); dataSource.setMinIdle(0); dataSource.setMaxIdle(10); dataSource.setNumTestsPerEvictionRun(3); dataSource.setTimeBetweenEvictionRunsMillis(-1); dataSource.setDefaultTransactionIsolation(ISOLATION_LEVEL); final String tableName = "counter_table"; final String columnName = "n"; final JdbcDataContext dataContext = new JdbcDataContext(dataSource); dataContext.executeUpdate(new UpdateScript() { @Override public void run(UpdateCallback callback) { if (dataContext.getTableByQualifiedLabel(tableName) != null) { callback.dropTable(tableName).execute(); } callback.createTable(dataContext.getDefaultSchema(), tableName).withColumn(columnName) .ofType(ColumnType.INTEGER).execute(); } }); final Table table = dataContext.getTableByQualifiedLabel(tableName); final Column col = table.getColumnByName(columnName); assertNotNull(col); // insert one record - this one record will be updated transactionally below dataContext.executeUpdate(new InsertInto(table).value(columnName, 0)); final UpdateScript updateScript = new UpdateScript() { @Override public void run(UpdateCallback callback) { final int n = getCounterValue(callback.getDataContext(), table, col); callback.update(table).value(col, n + 1).execute(); } }; final int threadCount = 2; final int iterationsPerThread = 5; final Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { for (int j = 0; j < iterationsPerThread; j++) { int retries = 10; while (retries > 0) { try { dataContext.executeUpdate(updateScript); retries = 0; } catch (RolledBackUpdateException e) { retries--; if (retries == 0) { throw e; } } } } } }; } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } assertEquals(threadCount * iterationsPerThread, getCounterValue(dataContext, table, col)); }
From source file:org.apache.stratos.tenant.mgt.util.TenantMgtUtil.java
public static void deleteTenantUMData(int tenantId) throws Exception { RealmConfiguration realmConfig = TenantMgtServiceComponent.getRealmService() .getBootstrapRealmConfiguration(); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(realmConfig.getRealmProperty(JDBCRealmConstants.DRIVER_NAME)); dataSource.setUrl(realmConfig.getRealmProperty(JDBCRealmConstants.URL)); dataSource.setUsername(realmConfig.getRealmProperty(JDBCRealmConstants.USER_NAME)); dataSource.setPassword(realmConfig.getRealmProperty(JDBCRealmConstants.PASSWORD)); dataSource.setMaxActive(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_ACTIVE))); dataSource.setMinIdle(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MIN_IDLE))); dataSource.setMaxWait(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_WAIT))); TenantUMDataDeletionUtil.deleteTenantUMData(tenantId, dataSource.getConnection()); }