List of usage examples for org.apache.commons.dbcp BasicDataSource setUrl
public synchronized void setUrl(String url)
Sets the #url .
Note: this method currently has no effect once the pool has been initialized.
From source file:com.jolbox.benchmark.BenchmarkTests.java
/** * Benchmarks PreparedStatement functionality (single thread) * @return result// w w w . j a v a 2s.c o m * * @throws PropertyVetoException * @throws SQLException */ private long testPreparedStatementSingleThreadDBCP() throws PropertyVetoException, SQLException { BasicDataSource cpds = new BasicDataSource(); cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver"); cpds.setUrl(url); cpds.setUsername(username); cpds.setPassword(password); cpds.setMaxIdle(-1); cpds.setMinIdle(-1); cpds.setPoolPreparedStatements(true); cpds.setMaxOpenPreparedStatements(30); cpds.setInitialSize(pool_size); cpds.setMaxActive(pool_size); Connection conn = cpds.getConnection(); long start = System.currentTimeMillis(); for (int i = 0; i < MAX_CONNECTIONS; i++) { Statement st = conn.prepareStatement(TEST_QUERY); st.close(); } conn.close(); long end = (System.currentTimeMillis() - start); System.out.println("DBCP PreparedStatement Single thread benchmark: " + end); results.add("DBCP, " + end); // dispose of pool cpds.close(); return end; }
From source file:net.firejack.platform.model.config.hibernate.HibernateFactoryBean.java
private void buildHibernateTransactionManager() { for (Map.Entry<String, Database> entry : databases.entrySet()) { String name = entry.getKey(); Database database = entry.getValue(); BasicDataSource dataSource = null; try {//from ww w.j ava 2 s . com dataSource = context.getBean(name + HIBERNATE_DATA_SOURCE_SUFFIX, BasicDataSource.class); } catch (BeansException e) { logger.info("Manual Hibernate DataSource: " + name + HIBERNATE_DATA_SOURCE_SUFFIX + " not found use default"); } if (dataSource == null) { dataSource = defaultHibernate.getBean(HIBERNATE_DEFAULT_PREFIX + HIBERNATE_DATA_SOURCE_SUFFIX, BasicDataSource.class); dataSource.setDriverClassName(database.type.getDriver()); dataSource.setUrl(database.getUrl()); dataSource.setUsername(database.getUsername()); dataSource.setPassword(database.getPassword()); dataSource.setValidationQuery(database.getType().getValidate()); context.getBeanFactory().registerSingleton(name + HIBERNATE_DATA_SOURCE_SUFFIX, dataSource); } Properties properties = null; try { properties = context.getBean(name + HIBERNATE_PROPERTIES_SUFFIX, Properties.class); } catch (BeansException e) { logger.info("Manual Hibernate properties: " + name + HIBERNATE_PROPERTIES_SUFFIX + " not found use default"); } if (properties == null) { properties = defaultHibernate.getBean(HIBERNATE_DEFAULT_PREFIX + HIBERNATE_PROPERTIES_SUFFIX, Properties.class); properties.put(Environment.DIALECT, database.getType().getDialect()); context.getBeanFactory().registerSingleton(name + HIBERNATE_PROPERTIES_SUFFIX, properties); } SessionFactory sessionFactory = null; try { sessionFactory = context.getBean(name + HIBERNATE_SESSION_FACTORY_SUFFIX, SessionFactory.class); } catch (BeansException e) { logger.info("Manual Hibernate Session Factory: " + name + HIBERNATE_SESSION_FACTORY_SUFFIX + " not found use default"); } if (sessionFactory == null) { try { AnnotationSessionFactoryBean annotationSessionFactoryBean = new AnnotationSessionFactoryBean(); annotationSessionFactoryBean.setAnnotatedClasses(new Class[] { BaseEntityModel.class }); annotationSessionFactoryBean.setDataSource(dataSource); annotationSessionFactoryBean.setHibernateProperties(properties); annotationSessionFactoryBean.setPackagesToScan(database.getScanPackages()); annotationSessionFactoryBean.setNamingStrategy(new OpenFlameNamingStrategy(database.getType())); if (database.getType() == DatabaseName.MySQL || database.getType() == DatabaseName.MSSQL) { annotationSessionFactoryBean.setLobHandler(new DefaultLobHandler()); } else if (database.getType() == DatabaseName.Oracle) { annotationSessionFactoryBean.setLobHandler(new OracleLobHandler()); } disposableBeans.add(annotationSessionFactoryBean); annotationSessionFactoryBean.afterPropertiesSet(); sessionFactory = annotationSessionFactoryBean.getObject(); } catch (Exception e) { logger.error(e, e); } } HibernateTemplate template = new HibernateTemplate(); template.setSessionFactory(sessionFactory); context.getBeanFactory().registerSingleton(name + HIBERNATE_TEMPLATE_PREFIX, template); database.setHibernateSupport(template); logger.info("Initialize Hibernate support for stories: " + database); String beanName = name + HIBERNATE_TRANSACTION_MANAGER_SUFFIX; ConstructorArgumentValues values = new ConstructorArgumentValues(); values.addGenericArgumentValue(sessionFactory); RootBeanDefinition definition = new RootBeanDefinition(HibernateTransactionManager.class); definition.setConstructorArgumentValues(values); registers.put(beanName, definition); Collection<HibernateSupport> stores = database.getStores(); for (HibernateSupport store : stores) { targets.put(((Advised) store).getTargetClass(), beanName); } } }
From source file:com.openddal.test.BaseTestCase.java
private BasicDataSource newDataSource() { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(driverClassName); ds.setUrl(url); ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); return ds;/* w w w . j a v a 2 s. c o m*/ }
From source file:fi.ni.IFC_ClassModel.java
public void listRDF(OutputStream outputStream, String path, VirtConfig virt) throws IOException, SQLException { BufferedWriter out = null;/*w ww. ja va 2 s. c om*/ 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.googlecode.wmbutil.jdbc.DataSourceLocator.java
/** * Looks up a named data source/*from ww w. j av a 2s. com*/ * * @param dataSourceName * The name of the data source to look for * @return The data source * @throws RuntimeException * If the configuration can not be loaded or the data source * definition is missing */ public synchronized DataSource lookup(String dataSourceName) { BasicDataSource ds; if (dataSources.containsKey(dataSourceName)) { ds = (BasicDataSource) dataSources.get(dataSourceName); if (ds == null) { // we failed to create it earlier throw new RuntimeException("Failed to create data source"); } } else { ds = new BasicDataSource(); try { String driver = config.getProperty("jdbc." + dataSourceName + ".class"); if (driver == null || driver.trim().length() == 0) { throw new RuntimeException("Lookup connections configuration file must contain a jdbc." + dataSourceName + ".class value"); } else { ds.setDriverClassName(driver); } String url = config.getProperty("jdbc." + dataSourceName + ".url"); if (url == null || url.trim().length() == 0) { throw new RuntimeException("Lookup connections configuration file must contain a jdbc." + dataSourceName + ".url value"); } else { ds.setUrl(url); } String username = config.getProperty("jdbc." + dataSourceName + ".username"); if (username == null || username.trim().length() == 0) { throw new RuntimeException("Lookup connections configuration file must contain a jdbc." + dataSourceName + ".username value"); } else { ds.setUsername(username); } ds.setPassword(config.getProperty("jdbc." + dataSourceName + ".password")); ds.setDefaultReadOnly(true); dataSources.put(dataSourceName, ds); } catch (RuntimeException e) { // mark failed to create dataSources.put(dataSourceName, null); throw e; } } return ds; }
From source file:edu.tamu.tcat.db.core.AbstractDataSourceFactory.java
/** * Create a new {@link BasicDataSource} from the specified {@link DSProperties} *//* w w w . j a v a 2 s . c om*/ 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:cz.muni.fi.pv168.MainForm.java
private DataSource prepareDataSource() { /*/*w w w. jav a 2 s . co m*/ * BasicDataSource ds = new BasicDataSource(); Properties properties = * new Properties(); FileInputStream in = null; try { in = new * FileInputStream("database.properties"); } catch * (FileNotFoundException ex) { * Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, "File * Not Found", ex); } try { properties.load(in); } catch (IOException * ex) { Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, * "Can Not Read Properties File", ex); } String drivers = * properties.getProperty("jdbc.drivers"); if (null == drivers) { * System.setProperty("jdbs.drivers", drivers); } String url = * properties.getProperty("jdbc.url"); String username = * properties.getProperty("jdbc.username"); String password = * properties.getProperty("jdbc.password"); ds.setUrl(url); * ds.setUsername(username); ds.setPassword(password); return ds; */ ResourceBundle databaseProperties = ResourceBundle.getBundle("cz.muni.fi.pv168.database"); String url = databaseProperties.getString("jdbc.url"); String username = databaseProperties.getString("jdbc.username"); String password = databaseProperties.getString("jdbc.password"); BasicDataSource ds = new BasicDataSource(); ds.setUrl(url); ds.setUsername(username); ds.setPassword(password); try { DBUtils.tryCreateTables(ds); } catch (SQLException ex) { JOptionPane.showMessageDialog(jMenu1, localization.getString("db_connection_failure"), localization.getString("error"), JOptionPane.ERROR_MESSAGE); } carManager.setDataSource(ds); customerManager.setDataSource(ds); rentManager.setDataSource(ds); return ds; }
From source file:com.alibaba.otter.manager.biz.common.DataSourceCreator.java
private DataSource createDataSource(String url, String userName, String password, String driverClassName, DataMediaType dataMediaType, String encoding) { BasicDataSource dbcpDs = new BasicDataSource(); dbcpDs.setInitialSize(initialSize);// ? dbcpDs.setMaxActive(maxActive);// ????? dbcpDs.setMaxIdle(maxIdle);// ?? dbcpDs.setMinIdle(minIdle);// ?0? dbcpDs.setMaxWait(maxWait);// ??-1? dbcpDs.setRemoveAbandoned(true);// ??removeAbandonedTimeout dbcpDs.setLogAbandoned(true);// ?? dbcpDs.setRemoveAbandonedTimeout(removeAbandonedTimeout); // ? dbcpDs.setNumTestsPerEvictionRun(numTestsPerEvictionRun);// ?? dbcpDs.setTestOnBorrow(false);// ?? dbcpDs.setTestOnReturn(false);// ?? dbcpDs.setTestWhileIdle(true);// ???? dbcpDs.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); // ???????? dbcpDs.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); // ??????? // ??//from w ww. j a v a 2 s .c o m dbcpDs.setDriverClassName(driverClassName); dbcpDs.setUrl(url); dbcpDs.setUsername(userName); dbcpDs.setPassword(password); if (dataMediaType.isOracle()) { dbcpDs.addConnectionProperty("restrictGetTables", "true"); // dbcpDs.setValidationQuery("select 1 from dual"); } else if (dataMediaType.isMysql()) { // open the batch mode for mysql since 5.1.8 dbcpDs.addConnectionProperty("useServerPrepStmts", "false"); dbcpDs.addConnectionProperty("rewriteBatchedStatements", "true"); dbcpDs.addConnectionProperty("zeroDateTimeBehavior", "convertToNull");// 0000-00-00null dbcpDs.addConnectionProperty("yearIsDateType", "false");// ??year?date? dbcpDs.addConnectionProperty("noDatetimeStringSync", "true");// ,??? if (StringUtils.isNotEmpty(encoding)) { if (StringUtils.equalsIgnoreCase(encoding, "utf8mb4")) { dbcpDs.addConnectionProperty("characterEncoding", "utf8"); dbcpDs.setConnectionInitSqls(Arrays.asList("set names utf8mb4")); } else { dbcpDs.addConnectionProperty("characterEncoding", encoding); } } // dbcpDs.setValidationQuery("select 1"); } else { logger.error("ERROR ## Unknow database type"); } return dbcpDs; }
From source file:com.alibaba.otter.node.etl.common.datasource.impl.DBDataSourceService.java
private DataSource createDataSource(String url, String userName, String password, String driverClassName, DataMediaType dataMediaType, String encoding) { BasicDataSource dbcpDs = new BasicDataSource(); dbcpDs.setInitialSize(initialSize);// ? dbcpDs.setMaxActive(maxActive);// ????? dbcpDs.setMaxIdle(maxIdle);// ?? dbcpDs.setMinIdle(minIdle);// ?0? dbcpDs.setMaxWait(maxWait);// ??-1? dbcpDs.setRemoveAbandoned(true);// ??removeAbandonedTimeout dbcpDs.setLogAbandoned(true);// ?? dbcpDs.setRemoveAbandonedTimeout(removeAbandonedTimeout); // ? dbcpDs.setNumTestsPerEvictionRun(numTestsPerEvictionRun);// ?? dbcpDs.setTestOnBorrow(false);// ?? dbcpDs.setTestOnReturn(false);// ?? dbcpDs.setTestWhileIdle(true);// ???? dbcpDs.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); // ???????? dbcpDs.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); // ??????? // ??/* www . jav a2s . c o m*/ dbcpDs.setDriverClassName(driverClassName); dbcpDs.setUrl(url); dbcpDs.setUsername(userName); dbcpDs.setPassword(password); if (dataMediaType.isOracle()) { dbcpDs.addConnectionProperty("restrictGetTables", "true"); dbcpDs.setValidationQuery("select 1 from dual"); } else if (dataMediaType.isMysql()) { // open the batch mode for mysql since 5.1.8 dbcpDs.addConnectionProperty("useServerPrepStmts", "false"); dbcpDs.addConnectionProperty("rewriteBatchedStatements", "true"); dbcpDs.addConnectionProperty("zeroDateTimeBehavior", "convertToNull");// 0000-00-00null dbcpDs.addConnectionProperty("yearIsDateType", "false");// ??year?date? dbcpDs.addConnectionProperty("noDatetimeStringSync", "true");// ,??? if (StringUtils.isNotEmpty(encoding)) { if (StringUtils.equalsIgnoreCase(encoding, "utf8mb4")) { dbcpDs.addConnectionProperty("characterEncoding", "utf8"); dbcpDs.setConnectionInitSqls(Arrays.asList("set names utf8mb4")); } else { dbcpDs.addConnectionProperty("characterEncoding", encoding); } } dbcpDs.setValidationQuery("select 1"); } else { logger.error("ERROR ## Unknow database type"); } return dbcpDs; }
From source file:com.alibaba.otter.common.push.datasource.media.MediaPushDataSource.java
protected DataSource doCreateDataSource(String url) { BasicDataSource dbcpDs = new BasicDataSource(); dbcpDs.setInitialSize(initialSize);// ? dbcpDs.setMaxActive(maxActive);// ????? dbcpDs.setMaxIdle(maxIdle);// ?? dbcpDs.setMinIdle(minIdle);// ?0? dbcpDs.setMaxWait(maxWait);// ??-1? dbcpDs.setRemoveAbandoned(true);// ??removeAbandonedTimeout dbcpDs.setLogAbandoned(true);// ?? dbcpDs.setRemoveAbandonedTimeout(removeAbandonedTimeout); // ? dbcpDs.setNumTestsPerEvictionRun(numTestsPerEvictionRun);// ?? dbcpDs.setTestOnBorrow(false);// ?? dbcpDs.setTestOnReturn(false);// ?? dbcpDs.setTestWhileIdle(true);// ???? dbcpDs.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); // ???????? dbcpDs.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); // ??????? // ??/*w ww. j a v a 2 s . c o m*/ dbcpDs.setDriverClassName(driverClassName); dbcpDs.setUrl(url); dbcpDs.setUsername(userName); dbcpDs.setPassword(password); if (dataMediaType.isOracle()) { dbcpDs.addConnectionProperty("restrictGetTables", "true"); dbcpDs.setValidationQuery("select 1 from dual"); } else if (dataMediaType.isMysql()) { // open the batch mode for mysql since 5.1.8 dbcpDs.addConnectionProperty("useServerPrepStmts", "false"); dbcpDs.addConnectionProperty("rewriteBatchedStatements", "true"); dbcpDs.addConnectionProperty("zeroDateTimeBehavior", "convertToNull");// 0000-00-00null dbcpDs.addConnectionProperty("yearIsDateType", "false");// ??year?date? if (StringUtils.isNotEmpty(encoding)) { dbcpDs.addConnectionProperty("characterEncoding", encoding); } dbcpDs.setValidationQuery("select 1"); } else { logger.error("ERROR ## Unknow database type"); } return dbcpDs; }