Java Examples for org.apache.commons.dbcp2.BasicDataSource

The following java examples will help you to understand the usage of org.apache.commons.dbcp2.BasicDataSource. These source code samples are taken from different open source projects.

Example 1
Project: spring-cloud-connectors-master  File: BasicDbcpPooledDataSourceCreator.java View source code
@Override
public DataSource create(RelationalServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig, String driverClassName, String validationQuery) {
    if (hasClass(DBCP2_BASIC_DATASOURCE)) {
        logger.info("Found DBCP2 on the classpath. Using it for DataSource connection pooling.");
        org.apache.commons.dbcp2.BasicDataSource ds = new org.apache.commons.dbcp2.BasicDataSource();
        setBasicDataSourceProperties(ds, serviceInfo, serviceConnectorConfig, driverClassName, validationQuery);
        return ds;
    } else if (hasClass(DBCP_BASIC_DATASOURCE)) {
        logger.info("Found DBCP on the classpath. Using it for DataSource connection pooling.");
        org.apache.commons.dbcp.BasicDataSource ds = new org.apache.commons.dbcp.BasicDataSource();
        setBasicDataSourceProperties(ds, serviceInfo, serviceConnectorConfig, driverClassName, validationQuery);
        return ds;
    } else {
        return null;
    }
}
Example 2
Project: jcommons.import-master  File: DataSourceFactory.java View source code
/** @return a reference to the default in-memory database */
public static DataSource createMemoryDataSource() {
    if (dataSource == null) {
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName("org.hsqldb.jdbcDriver");
        basicDataSource.setUrl("jdbc:hsqldb:mem:junit");
        basicDataSource.setUsername("sa");
        basicDataSource.setPassword("");
        dataSource = basicDataSource;
    }
    return dataSource;
}
Example 3
Project: OpenNotification-master  File: GenericSQLDatabaseBroker.java View source code
public void reset() {
    ds = new BasicDataSource();
    ds.setMaxActive(500);
    ds.setDriverClassName(getDriverClassname());
    BrokerFactory.getLoggingBroker().logDebug("Logging into database as " + getDatabaseUserName());
    ds.setUsername(getDatabaseUserName());
    ds.setPassword(getDatabasePassword());
    ds.setUrl(getDatabaseURL());
    ds.setLogAbandoned(true);
    ds.setRemoveAbandoned(true);
    ds.setRemoveAbandonedTimeout(60);
    String validationQuery = getValidationQuery();
    if (validationQuery != null) {
        ds.setValidationQuery(validationQuery);
    }
}
Example 4
Project: vcap-java-master  File: MysqlServiceCreator.java View source code
/**
	 * Create a datasource based on service info.
	 * 
	 * <p>
	 * Tries to create a pooled connection based on either 
	 */
public DataSource createService(MysqlServiceInfo serviceInfo) {
    try {
        Class.forName(DRIVER_CLASS_NAME);
        // Give first preference to user's DBCP datasource
        if (hasClass("org.apache.commons.dbcp.BasicDataSource")) {
            org.apache.commons.dbcp.BasicDataSource ds = new org.apache.commons.dbcp.BasicDataSource();
            ds.setDriverClassName(DRIVER_CLASS_NAME);
            ds.setUrl(serviceInfo.getUrl());
            ds.setUsername(serviceInfo.getUserName());
            ds.setPassword(serviceInfo.getPassword());
            return ds;
        // else, we have one from Tomcat
        } else if (hasClass("org.apache.tomcat.dbcp.dbcp.BasicDataSource")) {
            org.apache.tomcat.dbcp.dbcp.BasicDataSource ds = new org.apache.tomcat.dbcp.dbcp.BasicDataSource();
            ds.setDriverClassName(DRIVER_CLASS_NAME);
            ds.setUrl(serviceInfo.getUrl());
            ds.setUsername(serviceInfo.getUserName());
            ds.setPassword(serviceInfo.getPassword());
            return ds;
        } else {
            // Only for testing outside Tomcat/CloudFoundry
            return new SimpleDriverDataSource(DriverManager.getDriver(serviceInfo.getUrl()), serviceInfo.getUrl(), serviceInfo.getUserName(), serviceInfo.getPassword());
        }
    } catch (Exception e) {
        throw new CloudServiceException("Failed to created cloud datasource for " + serviceInfo.getServiceName() + " service", e);
    }
}
Example 5
Project: kylo-master  File: PoolingDataSourceService.java View source code
private static DataSource createDatasource(DataSourceProperties props) {
    DataSourceBuilder builder = DataSourceBuilder.create().url(props.getUrl()).username(props.getUser()).password(props.getPassword());
    if (StringUtils.isNotBlank(props.getDriverClassName())) {
        builder.driverClassName(props.getDriverClassName());
    }
    DataSource ds = builder.build();
    if (props.isTestOnBorrow() && StringUtils.isNotBlank(props.getValidationQuery())) {
        if (ds instanceof org.apache.tomcat.jdbc.pool.DataSource) {
            ((org.apache.tomcat.jdbc.pool.DataSource) ds).setTestOnBorrow(true);
            ((org.apache.tomcat.jdbc.pool.DataSource) ds).setValidationQuery(props.getValidationQuery());
        } else if (ds instanceof org.apache.commons.dbcp2.BasicDataSource) {
            ((org.apache.commons.dbcp2.BasicDataSource) ds).setValidationQuery(props.getValidationQuery());
            ((org.apache.commons.dbcp2.BasicDataSource) ds).setTestOnBorrow(true);
        } else if (ds instanceof org.apache.commons.dbcp.BasicDataSource) {
            ((org.apache.commons.dbcp.BasicDataSource) ds).setValidationQuery(props.getValidationQuery());
            ((org.apache.commons.dbcp.BasicDataSource) ds).setTestOnBorrow(true);
        }
    }
    return ds;
}
Example 6
Project: JDBC-Performance-Logger-master  File: DbcpDataSourcePostProcessor.java View source code
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
    if (bean instanceof BasicDataSource) {
        final BasicDataSource ds = (BasicDataSource) bean;
        // avoid to wrap an already wrapped datasource
        if (!ds.getUrl().startsWith(AbstractDataSourcePostProcessor.JDBC_URL_PREFIX)) {
            checkVisibleFromDataSource(BasicDataSource.class);
            checkUnderlyingDriverIsVisible(ds.getDriverClassName());
            ds.setUrl("jdbcperflogger:" + ds.getUrl());
            ds.setDriverClassName(WrappingDriver.class.getName());
        }
    }
    return bean;
}
Example 7
Project: minuteProject-master  File: ConnectionUtils.java View source code
public static Connection getConnection(DataModel dataModel) {
    BasicDataSource basicDataSource = dataModel.getBasicDataSource();
    String driver = basicDataSource.getDriverClassName();
    String url = basicDataSource.getUrl();
    String username = basicDataSource.getUsername();
    String password = basicDataSource.getPassword();
    try {
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }// load Oracle driver
     catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}
Example 8
Project: OnlineFrontlines-master  File: ServerInfoAction.java View source code
/**
	 * Query data source status
	 * 
	 * @param dataSourceName Name of the data source
	 */
private String getDataSourceStatus(String dataSourceName) {
    DataSource dataSource = (DataSource) DbConnectionPool.getInstance().getDataSources().get(dataSourceName);
    if (dataSource.getClass().getName().equals("org.apache.commons.dbcp.BasicDataSource") && dataSource instanceof org.apache.commons.dbcp.BasicDataSource) {
        org.apache.commons.dbcp.BasicDataSource s = (org.apache.commons.dbcp.BasicDataSource) dataSource;
        return "Busy: " + s.getNumActive() + " (" + (int) (s.getNumActive() * 100 / s.getMaxActive()) + "%), Connections: " + (s.getNumIdle() + s.getNumActive()) + ", Max: " + s.getMaxActive();
    } else if (dataSource.getClass().getName().equals("org.apache.tomcat.dbcp.dbcp.BasicDataSource") && dataSource instanceof org.apache.tomcat.dbcp.dbcp.BasicDataSource) {
        org.apache.tomcat.dbcp.dbcp.BasicDataSource s = (org.apache.tomcat.dbcp.dbcp.BasicDataSource) dataSource;
        return "Busy: " + s.getNumActive() + " (" + (int) (s.getNumActive() * 100 / s.getMaxActive()) + "%), Connections: " + (s.getNumIdle() + s.getNumActive()) + ", Max: " + s.getMaxActive();
    } else {
        return "Unknown datasource: " + dataSource.getClass().getName();
    }
}
Example 9
Project: tomee-master  File: IgnoreDefaultTest.java View source code
private void check(final String id, final String user, final String password) throws NamingException {
    final DataSource ds = (DataSource) assembler.getContainerSystem().getJNDIContext().lookup("openejb/Resource/" + id);
    assertThat(ds, instanceOf(org.apache.commons.dbcp2.BasicDataSource.class));
    assertEquals(user, ((org.apache.commons.dbcp2.BasicDataSource) ds).getUsername());
    assertEquals(password, ((org.apache.commons.dbcp2.BasicDataSource) ds).getPassword());
}
Example 10
Project: bc-commons-master  File: SqlUtils.java View source code
public static BasicDataSource createDatasource(DataSourceConfig dataSourceConfig) {
    final BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(dataSourceConfig.getDriver());
    result.setUrl(dataSourceConfig.getUrl());
    result.setUsername(dataSourceConfig.getUsername());
    result.setPassword(dataSourceConfig.getPassword());
    return result;
}
Example 11
Project: cattle-master  File: DefaultDataSourceFactoryImpl.java View source code
@Override
public DataSource createDataSource(String name) {
    String server = PoolConfig.getProperty("db." + name + ".database");
    String alias = PoolConfig.getProperty("db." + name + ".alias");
    if (server == null && alias != null) {
        server = PoolConfig.getProperty("db." + alias + ".database");
    }
    BasicDataSource ds = newBasicDataSource(name);
    if (alias == null) {
        PoolConfig.setConfig(ds, name, String.format("db.%s.%s.", name, server), String.format("db.%s.", name), "db.", "global.pool.");
    } else {
        PoolConfig.setConfig(ds, name, String.format("db.%s.%s.", name, server), String.format("db.%s.", name), String.format("db.%s.%s.", alias, server), String.format("db.%s.", alias), "db.", "global.pool.");
    }
    return ds;
}
Example 12
Project: dbpool-master  File: DBSource.java View source code
public DataSource getDataSource(DBServer server) {
    BasicDataSource ds = datasources.get(server.checksum());
    if (ds != null) {
        return ds;
    }
    ds = new BasicDataSource();
    ds.setDriverClassName(server.driver);
    ds.setUrl("jdbc:mysql://" + server.host + ":" + server.port + "/" + server.db + "?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true");
    ds.setUsername(server.user);
    ds.setPassword(server.pass);
    ds.setInitialSize(server.coreSize);
    ds.setMinIdle(server.coreSize);
    ds.setMaxActive(server.maxSize);
    ds.setMinEvictableIdleTimeMillis(server.idleTimeSeconds * 1000L / 2);
    datasources.put(server.checksum(), ds);
    return ds;
}
Example 13
Project: javaconfig-ftw-master  File: LocalDataSourceConfiguration.java View source code
@Bean
public DataSource dataSource(Environment environment) throws Exception {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setPassword(environment.getProperty("dataSource.password"));
    dataSource.setUrl(environment.getProperty("dataSource.url"));
    dataSource.setUsername(environment.getProperty("dataSource.user"));
    dataSource.setDriverClassName(environment.getPropertyAsClass("dataSource.driverClass", Driver.class).getName());
    return dataSource;
}
Example 14
Project: micro-server-master  File: DBCPDataSourceBuilder.java View source code
private void retrySetup(BasicDataSource ds) {
    if (!"org.hibernate.dialect.HSQLDialect".equals(mainEnv.getDialect())) {
        ds.setTestOnBorrow(dbcpEnv.isTestOnBorrow());
        ds.setValidationQuery(dbcpEnv.getValidationQuery());
        ds.setMaxTotal(dbcpEnv.getMaxTotal());
        ds.setMinEvictableIdleTimeMillis(dbcpEnv.getMinEvictableIdleTime());
        ds.setTimeBetweenEvictionRunsMillis(dbcpEnv.getTimeBetweenEvictionRuns());
        ds.setNumTestsPerEvictionRun(dbcpEnv.getNumTestsPerEvictionRun());
        ds.setTestWhileIdle(dbcpEnv.isTestWhileIdle());
        ds.setTestOnReturn(dbcpEnv.isTestOnReturn());
    }
}
Example 15
Project: osmosis-master  File: DataSourceFactory.java View source code
/**
	 * Creates a new data source based on the specified credentials.
	 * 
	 * @param credentials
	 *            The database credentials.
	 * 
	 * @return The data source.
	 */
public static BasicDataSource createDataSource(DatabaseLoginCredentials credentials) {
    BasicDataSource dataSource;
    dataSource = new BasicDataSource();
    switch(credentials.getDbType()) {
        case POSTGRESQL:
            dataSource.setDriverClassName("org.postgresql.Driver");
            dataSource.setUrl("jdbc:postgresql://" + credentials.getHost() + "/" + credentials.getDatabase());
            break;
        case MYSQL:
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://" + credentials.getHost() + "/" + credentials.getDatabase());
            break;
        default:
            throw new OsmosisRuntimeException("Unknown database type " + credentials.getDbType() + ".");
    }
    dataSource.setUsername(credentials.getUser());
    dataSource.setPassword(credentials.getPassword());
    return dataSource;
}
Example 16
Project: QMAClone-master  File: DatabaseModule.java View source code
@Provides
@Singleton
private DataSource provideDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(DRIVER_CLASS_NAME);
    dataSource.setUsername(USERNAME);
    dataSource.setPassword(PASSWORD);
    dataSource.setUrl(URL);
    dataSource.setValidationQuery(VALIDATION_QUERY);
    return dataSource;
}
Example 17
Project: springsource-cloudfoundry-samples-master  File: ReferenceDataRepository.java View source code
public String getDbInfo() {
    DataSource dataSource = jdbcTemplate.getDataSource();
    if (dataSource instanceof BasicDataSource) {
        return ((BasicDataSource) dataSource).getUrl();
    } else if (dataSource instanceof SimpleDriverDataSource) {
        return ((SimpleDriverDataSource) dataSource).getUrl();
    }
    return dataSource.toString();
}
Example 18
Project: ZenQuery-master  File: BasicDataSourceFactory.java View source code
public BasicDataSource getBasicDataSource(String url, String username, String password) {
    Pattern pattern = Pattern.compile("jdbc:(\\w+?):");
    Matcher matcher = pattern.matcher(url);
    String driverClassName = "";
    String validationQuery = "";
    if (matcher.find()) {
        driverClassName = databaseDriverProperties.getProperty("drivers." + matcher.group(1));
        validationQuery = databaseDriverProperties.getProperty("validationQueries." + matcher.group(1));
    }
    BasicDataSource dataSource = dataSources.get(url);
    if (dataSource == null) {
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setUrl(url);
        dataSource.setMaxIdle(5);
        dataSource.setValidationQuery(validationQuery);
        dataSources.put(url, dataSource);
    }
    return dataSource;
}
Example 19
Project: java-test-applications-master  File: DataSourceUtils.java View source code
//
public String getUrl(DataSource dataSource) {
    if (isClass(dataSource, "com.jolbox.bonecp.BoneCPDataSource")) {
        return invokeMethod(dataSource, "getJdbcUrl");
    } else if (isClass(dataSource, "org.apache.commons.dbcp.BasicDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.apache.commons.dbcp2.BasicDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.apache.tomcat.dbcp.dbcp.BasicDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.apache.tomcat.dbcp.dbcp2.BasicDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.apache.tomcat.jdbc.pool.DataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.springframework.jdbc.datasource.embedded" + ".EmbeddedDatabaseFactory$EmbeddedDataSourceProxy")) {
        return getUrl(getDataSource(dataSource, "dataSource"));
    } else if (isClass(dataSource, "org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy")) {
        return getUrl(getTargetDataSource(dataSource));
    } else if (isClass(dataSource, "org.springframework.jdbc.datasource.SimpleDriverDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy")) {
        return getUrl(getTargetDataSource(dataSource));
    } else if (isClass(dataSource, "com.zaxxer.hikari.HikariDataSource")) {
        return invokeMethod(dataSource, "getJdbcUrl");
    } else if (isClass(dataSource, "org.apache.openejb.resource.jdbc.managed.local.ManagedDataSource")) {
        return getUrl(getDataSource(dataSource, "delegate"));
    } else if (isClass(dataSource, "org.apache.tomee.jdbc.TomEEDataSourceCreator$TomEEDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    }
    return String.format("Unable to determine URL for DataSource of type %s", dataSource.getClass().getName());
}
Example 20
Project: javamelody-master  File: TestJdbcWrapper.java View source code
/** Test.
	 * @throws Exception e */
@Test
public void testCreateDataSourceProxy() throws Exception {
    // on fait le ménage au cas où TestMonitoringSpringInterceptor ait été exécuté juste avant
    cleanUp();
    assertTrue("getBasicDataSourceProperties0", JdbcWrapper.getBasicDataSourceProperties().isEmpty());
    assertEquals("getMaxConnectionCount0", -1, JdbcWrapper.getMaxConnectionCount());
    final org.apache.tomcat.jdbc.pool.DataSource tomcatJdbcDataSource = new org.apache.tomcat.jdbc.pool.DataSource();
    tomcatJdbcDataSource.setUrl(H2_DATABASE_URL);
    tomcatJdbcDataSource.setDriverClassName("org.h2.Driver");
    tomcatJdbcDataSource.setMaxActive(123);
    final DataSource tomcatJdbcProxy = jdbcWrapper.createDataSourceProxy("test2", tomcatJdbcDataSource);
    assertNotNull("createDataSourceProxy1", tomcatJdbcProxy);
    tomcatJdbcProxy.getConnection().close();
    assertFalse("getBasicDataSourceProperties1", JdbcWrapper.getBasicDataSourceProperties().isEmpty());
    assertEquals("getMaxConnectionCount1", 123, JdbcWrapper.getMaxConnectionCount());
    final org.apache.commons.dbcp.BasicDataSource dbcpDataSource = new org.apache.commons.dbcp.BasicDataSource();
    dbcpDataSource.setUrl(H2_DATABASE_URL);
    dbcpDataSource.setMaxActive(456);
    final DataSource dbcpProxy = jdbcWrapper.createDataSourceProxy(dbcpDataSource);
    assertNotNull("createDataSourceProxy2", dbcpProxy);
    assertFalse("getBasicDataSourceProperties2", JdbcWrapper.getBasicDataSourceProperties().isEmpty());
    assertEquals("getMaxConnectionCount2", 456, JdbcWrapper.getMaxConnectionCount());
    final BasicDataSource tomcatDataSource = new BasicDataSource();
    tomcatDataSource.setUrl(H2_DATABASE_URL);
    tomcatDataSource.setMaxActive(789);
    final DataSource tomcatProxy = jdbcWrapper.createDataSourceProxy("test", tomcatDataSource);
    assertNotNull("createDataSourceProxy3", tomcatProxy);
    assertNotNull("getLogWriter2", tomcatProxy.getLogWriter());
    tomcatProxy.getConnection().close();
    assertFalse("getBasicDataSourceProperties3", JdbcWrapper.getBasicDataSourceProperties().isEmpty());
    assertEquals("getMaxConnectionCount3", 789, JdbcWrapper.getMaxConnectionCount());
    final org.apache.commons.dbcp2.BasicDataSource dbcp2DataSource = new org.apache.commons.dbcp2.BasicDataSource();
    dbcp2DataSource.setUrl(H2_DATABASE_URL);
    dbcp2DataSource.setMaxTotal(456);
    final DataSource dbcp2Proxy = jdbcWrapper.createDataSourceProxy(dbcp2DataSource);
    assertNotNull("createDataSourceProxy2b", dbcp2Proxy);
    final org.apache.tomcat.dbcp.dbcp2.BasicDataSource tomcat2DataSource = new org.apache.tomcat.dbcp.dbcp2.BasicDataSource();
    tomcat2DataSource.setUrl(H2_DATABASE_URL);
    tomcat2DataSource.setMaxTotal(789);
    final DataSource tomcat2Proxy = jdbcWrapper.createDataSourceProxy("test", tomcat2DataSource);
    assertNotNull("createDataSourceProxy3b", tomcat2Proxy);
    final DataSource dataSource2 = new MyDataSource(tomcatDataSource);
    jdbcWrapper.createDataSourceProxy(dataSource2);
}
Example 21
Project: AnalyzerBeans-master  File: TestHelper.java View source code
public static DataSource createSampleDatabaseDataSource() {
    BasicDataSource _dataSource = new BasicDataSource();
    _dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
    _dataSource.setUrl("jdbc:hsqldb:res:testwareorderdb;readonly=true");
    _dataSource.setMaxActive(-1);
    _dataSource.setDefaultAutoCommit(false);
    return _dataSource;
}
Example 22
Project: beanfuse-master  File: DataSourceUtil.java View source code
public static DataSource getDataSource(String datasourceName) {
    final Properties props = new Properties();
    try {
        InputStream is = DataSourceUtil.class.getResourceAsStream("/database.properties");
        if (null == is) {
            throw new RuntimeException("cannot find database.properties");
        }
        props.load(is);
    } catch (IOException e) {
        throw new RuntimeException("cannot find database.properties");
    }
    BasicDataSource datasource = new BasicDataSource();
    Enumeration names = props.propertyNames();
    boolean find = false;
    while (names.hasMoreElements()) {
        String propertyName = (String) names.nextElement();
        if (propertyName.startsWith(datasourceName + ".")) {
            find = true;
            try {
                PropertyUtils.setProperty(datasource, StringUtils.substringAfter(propertyName, datasourceName + "."), props.getProperty(propertyName));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    if (find) {
        return datasource;
    } else {
        return null;
    }
}
Example 23
Project: cobar-master  File: CobarFactory.java View source code
public static CobarAdapter getCobarAdapter(String cobarNodeName) throws IOException {
    CobarAdapter cAdapter = new CobarAdapter();
    Properties prop = new Properties();
    prop.load(CobarFactory.class.getClassLoader().getResourceAsStream("cobarNode.properties"));
    BasicDataSource ds = new BasicDataSource();
    String user = prop.getProperty(cobarNodeName + ".user").trim();
    String password = prop.getProperty(cobarNodeName + ".password").trim();
    String ip = prop.getProperty(cobarNodeName + ".ip").trim();
    int managerPort = Integer.parseInt(prop.getProperty(cobarNodeName + ".manager.port").trim());
    int maxActive = -1;
    int minIdle = 0;
    long timeBetweenEvictionRunsMillis = 10 * 60 * 1000;
    int numTestsPerEvictionRun = Integer.MAX_VALUE;
    long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setUrl(new StringBuilder().append("jdbc:mysql://").append(ip).append(":").append(managerPort).append("/").toString());
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    ds.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    cAdapter.setDataSource(ds);
    return cAdapter;
}
Example 24
Project: Consent2Share-master  File: DataAccessConfig.java View source code
@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    logger.debug("database.driverClassName " + databaseDriverClassName);
    logger.debug("database.url " + databaseUrl);
    logger.debug("database.username " + databaseUsername);
    dataSource.setDriverClassName(databaseDriverClassName);
    dataSource.setUrl(databaseUrl);
    dataSource.setUsername(databaseUsername);
    dataSource.setPassword(databasePassword);
    dataSource.setTestOnBorrow(true);
    dataSource.setTestOnReturn(true);
    dataSource.setTestWhileIdle(true);
    dataSource.setTimeBetweenEvictionRunsMillis(1800000);
    dataSource.setNumTestsPerEvictionRun(3);
    dataSource.setMinEvictableIdleTimeMillis(1800000);
    dataSource.setValidationQuery("SELECT 1");
    return dataSource;
}
Example 25
Project: druid-master  File: Case_Concurrent_50.java View source code
public void test_1() throws Exception {
    final BasicDataSource dataSource = new BasicDataSource();
    dataSource.setInitialSize(initialSize);
    dataSource.setMaxActive(maxActive);
    dataSource.setMinIdle(minIdle);
    dataSource.setMaxIdle(maxIdle);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(jdbcUrl);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    dataSource.setValidationQuery(validationQuery);
    dataSource.setTestOnBorrow(testOnBorrow);
    dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    for (int i = 0; i < LOOP_COUNT; ++i) {
        p0(dataSource, "dbcp");
    }
    System.out.println();
}
Example 26
Project: elastic-job-master  File: JobEventRdbListenerTest.java View source code
@Before
public void setUp() throws JobEventListenerConfigurationException, SQLException, NoSuchFieldException {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(org.h2.Driver.class.getName());
    dataSource.setUrl("jdbc:h2:mem:job_event_storage");
    dataSource.setUsername("sa");
    dataSource.setPassword("");
    JobEventRdbListener jobEventRdbListener = new JobEventRdbListener(dataSource);
    ReflectionUtils.setFieldValue(jobEventRdbListener, "repository", repository);
    when(jobEventRdbConfiguration.createJobEventListener()).thenReturn(jobEventRdbListener);
    jobEventBus = new JobEventBus(jobEventRdbConfiguration);
}
Example 27
Project: geowebcache-master  File: OracleQuotaStoreTest.java View source code
protected BasicDataSource getDataSource() throws IOException, SQLException {
    BasicDataSource dataSource = super.getDataSource();
    // cleanup
    Connection cx = null;
    Statement st = null;
    try {
        cx = dataSource.getConnection();
        st = cx.createStatement();
        try {
            st.execute("DROP TABLE TILEPAGE CASCADE CONSTRAINTS");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            st.execute("DROP TABLE TILESET CASCADE CONSTRAINTS");
        } catch (Exception e) {
            e.printStackTrace();
        }
    } finally {
        st.close();
        cx.close();
    }
    return dataSource;
}
Example 28
Project: gobblin-master  File: MysqlDatasetStateStoreFactory.java View source code
@Override
public DatasetStateStore<JobState.DatasetState> createStateStore(Config config) {
    BasicDataSource basicDataSource = MysqlStateStore.newDataSource(config);
    String stateStoreTableName = config.hasPath(ConfigurationKeys.STATE_STORE_DB_TABLE_KEY) ? config.getString(ConfigurationKeys.STATE_STORE_DB_TABLE_KEY) : ConfigurationKeys.DEFAULT_STATE_STORE_DB_TABLE;
    boolean compressedValues = config.hasPath(ConfigurationKeys.STATE_STORE_COMPRESSED_VALUES_KEY) ? config.getBoolean(ConfigurationKeys.STATE_STORE_COMPRESSED_VALUES_KEY) : ConfigurationKeys.DEFAULT_STATE_STORE_COMPRESSED_VALUES;
    try {
        return new MysqlDatasetStateStore(basicDataSource, stateStoreTableName, compressedValues);
    } catch (Exception e) {
        throw new RuntimeException("Failed to create MysqlDatasetStateStore with factory", e);
    }
}
Example 29
Project: jOOQ-master  File: Example_4_1_ConnectionProvider.java View source code
@Test
public void run() {
    Connection connection = connection();
    Tools.title("Using jOOQ with a standalone connection");
    System.out.println(DSL.using(connection).select().from(AUTHOR).fetch());
    Tools.title("Using jOOQ with a DBCP connection pool");
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(Tools.driver());
    ds.setUrl(Tools.url());
    ds.setUsername(Tools.username());
    ds.setPassword(Tools.password());
    System.out.println(DSL.using(ds, SQLDialect.H2).select().from(AUTHOR).fetch());
}
Example 30
Project: kornakapi-master  File: ExtractTest.java View source code
public static void main(String[] args) throws IOException {
    /**
		 * test class
		 */
    String path = args[0];
    System.out.print(path);
    File configFile = new File(path);
    System.out.print(configFile.canRead());
    Configuration conf = null;
    try {
        conf = Configuration.fromXML(Files.toString(configFile, Charsets.UTF_8));
    } catch (IOException e) {
        e.printStackTrace();
    }
    BasicDataSource dataSource = new BasicDataSource();
    MySqlMaxPersistentStorage labelsGet = new MySqlMaxPersistentStorage(conf.getStorageConfiguration(), "", dataSource);
    LinkedList<String> labels = labelsGet.getAllLabels();
    labelsGet.close();
    StreamingKMeansClustererTrainer clusterer = null;
    StreamingKMeansClassifierModel model = new StreamingKMeansClassifierModel(conf.getStorageConfiguration(), labels.getFirst(), dataSource);
    try {
        clusterer = new StreamingKMeansClustererTrainer(conf.getStreamingKMeansClusterer().iterator().next(), model);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        clusterer.doTrain(configFile, null, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 31
Project: lsql-master  File: AbstractLSqlTest.java View source code
@Parameters({ TestParameter.jdbcDriverClassName, TestParameter.jdbcUrl, TestParameter.jdbcUsername, TestParameter.jdbcPassword })
@BeforeMethod()
public final void beforeMethod(@Optional String driverClassName, @Optional String url, @Optional String username, @Optional String password) {
    driverClassName = driverClassName != null ? driverClassName : "org.h2.Driver";
    url = url != null ? url : "jdbc:h2:mem:testdb;mode=postgresql";
    username = username != null ? username : "";
    password = password != null ? password : "";
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    ds.setDefaultAutoCommit(false);
    TestUtils.clear(ds);
    Connection connection;
    try {
        connection = ds.getConnection();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    GenericDialect dialect = null;
    if (driverClassName.equals("org.h2.Driver")) {
        dialect = new H2Dialect();
    } else if (driverClassName.equals("org.postgresql.Driver")) {
        dialect = new PostgresDialect();
    }
    this.lSql = new LSql(dialect, ConnectionProviders.fromInstance(connection));
    this.beforeMethodHook();
}
Example 32
Project: marbles-master  File: MySqlStore.java View source code
@Override
public void initialize() throws SailException {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        throw new RdbmsException(e.toString(), e);
    }
    StringBuilder url = new StringBuilder();
    url.append("jdbc:mysql:");
    if (serverName != null) {
        url.append("//").append(serverName);
        if (portNumber > 0) {
            url.append(":").append(portNumber);
        }
        url.append("/");
    }
    url.append(databaseName);
    url.append("?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true");
    BasicDataSource ds = new BasicDataSource();
    ds.setUrl(url.toString());
    ds.setMaxActive(64);
    ds.setValidationQuery("SELECT 1 FROM DUAL");
    /* Based on http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-j2ee.html */
    ds.setTestOnBorrow(true);
    ds.setTestOnReturn(true);
    ds.setTestWhileIdle(true);
    ds.setTimeBetweenEvictionRunsMillis(10000);
    ds.setMinEvictableIdleTimeMillis(30000);
    if (user != null) {
        ds.setUsername(user);
    } else {
        ds.setUsername(System.getProperty("user.name"));
    }
    if (password != null) {
        ds.setPassword(password);
    }
    MySqlConnectionFactory factory = new MySqlConnectionFactory();
    factory.setSail(this);
    factory.setDataSource(ds);
    setConnectionFactory(factory);
    super.initialize();
}
Example 33
Project: mockjndi-master  File: DataSourceBinding.java View source code
@Override
protected synchronized Object createBoundObject() {
    final BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);
    if (user != null) {
        dataSource.setUsername(user);
        if (password != null) {
            dataSource.setPassword(password);
        }
    }
    return dataSource;
}
Example 34
Project: monitoring-master  File: CommonsDbcp2Plugin.java View source code
private void addBasicDataSourceTransformer() {
    transformTemplate.transform("org.apache.commons.dbcp2.BasicDataSource", new TransformCallback() {

        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            if (isAvailableDataSourceMonitor(target)) {
                target.addField(CommonsDbcp2Constants.ACCESSOR_DATASOURCE_MONITOR);
                target.addInterceptor(CommonsDbcp2Constants.INTERCEPTOR_CONSTRUCTOR);
                target.addInterceptor(CommonsDbcp2Constants.INTERCEPTOR_CLOSE);
            }
            target.addInterceptor(CommonsDbcp2Constants.INTERCEPTOR_GET_CONNECTION);
            return target.toBytecode();
        }
    });
}
Example 35
Project: moskito-demo-master  File: DBUtil.java View source code
private static Connection getConnection() throws SQLException {
    BasicDataSource newDataSource = new BasicDataSource();
    JDBCConfig config = JDBCConfigFactory.getJDBCConfig();
    newDataSource.setDriverClassName(config.getDriver());
    if (config.getPreconfiguredJdbcUrl() != null && config.getPreconfiguredJdbcUrl().length() > 0)
        newDataSource.setUrl(config.getPreconfiguredJdbcUrl());
    else
        newDataSource.setUrl("jdbc:" + config.getVendor() + "://" + config.getHost() + ":" + config.getPort() + "/" + config.getDb());
    newDataSource.setUsername(config.getUsername());
    newDataSource.setPassword(config.getPassword());
    if (config.getMaxConnections() != Integer.MAX_VALUE)
        newDataSource.setMaxActive(config.getMaxConnections());
    return newDataSource.getConnection();
}
Example 36
Project: nutz-master  File: DaoPerformanceTest.java View source code
/**
	 * 务必先把log关闭!! 设置为Error或者NONE
	 */
@Test
public void test_dao() throws Throwable {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.h2.Driver");
    ds.setUsername("sa");
    ds.setPassword("sa");
    ds.setUrl("jdbc:h2:mem:~");
    ds.setDefaultAutoCommit(false);
    Json.toJson(ds);
    NutDao dao = new NutDao(ds);
    List<Pojo> list = new ArrayList<Pojo>();
    for (int i = 0; i < num; i++) {
        Pojo pojo = new Pojo();
        pojo.setName("abc" + i);
        list.add(pojo);
    }
    dao.create(Pojo.class, true);
    dao.fastInsert(list);
    System.out.println("预热完�,开始测试");
    //--------------------------------------------------
    dao.create(Pojo.class, true);
    dao(dao, list);
    dao.create(Pojo.class, true);
    jdbc(ds, list);
    dao.create(Pojo.class, true);
    dao(dao, list);
}
Example 37
Project: opencit-master  File: JdbcUtil.java View source code
public static DataSource getDataSource() {
    try {
        if (ds == null) {
            String driver = My.jdbc().driver();
            String dbUrl = My.jdbc().url();
            BasicDataSource dataSource = new BasicDataSource();
            // or com.mysql.jdbc.Driver  for mysql
            dataSource.setDriverClassName(driver);
            dataSource.setUrl(dbUrl);
            dataSource.setUsername(My.configuration().getDatabaseUsername());
            dataSource.setPassword(My.configuration().getDatabasePassword());
            ds = dataSource;
        }
    } catch (Exception ex) {
        log.error("Error connecting to the database. {}", ex.getMessage());
    }
    return ds;
}
Example 38
Project: openiot-master  File: DataSources.java View source code
public static BasicDataSource getDataSource(DBConnectionInfo dci) {
    BasicDataSource ds = null;
    try {
        ds = (BasicDataSource) GSNContext.getMainContext().lookup(Integer.toString(dci.hashCode()));
        if (ds == null) {
            ds = new BasicDataSource();
            ds.setDriverClassName(dci.getDriverClass());
            ds.setUsername(dci.getUserName());
            ds.setPassword(dci.getPassword());
            ds.setUrl(dci.getUrl());
            //ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            //ds.setAccessToUnderlyingConnectionAllowed(true); 
            GSNContext.getMainContext().bind(Integer.toString(dci.hashCode()), ds);
            logger.warn("Created a DataSource to: " + ds.getUrl());
        }
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }
    return ds;
}
Example 39
Project: pinpoint-master  File: DataSourceConstructorInterceptor.java View source code
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (!InterceptorUtils.isSuccess(throwable)) {
        return;
    }
    if ((target instanceof DataSourceMonitorAccessor) && (target instanceof BasicDataSource)) {
        Dbcp2DataSourceMonitor dbcpDataSourceMonitor = new Dbcp2DataSourceMonitor((BasicDataSource) target);
        dataSourceMonitorRegistry.register(dbcpDataSourceMonitor);
        ((DataSourceMonitorAccessor) target)._$PINPOINT$_setDataSourceMonitor(dbcpDataSourceMonitor);
    }
}
Example 40
Project: pinus4j-master  File: DBCPConnectionPoolImpl.java View source code
@Override
public DataSource buildAppDataSource(AppDBInfo dbInfo) throws LoadConfigException {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(dbInfo.getDbCatalog().getDriverClass());
    ds.setUsername(dbInfo.getUsername());
    ds.setPassword(dbInfo.getPassword());
    ds.setUrl(dbInfo.getUrl());
    // 设置连接池信�
    ds.setValidationQuery("SELECT 1");
    for (Map.Entry<String, String> entry : dbInfo.getConnPoolInfo().entrySet()) {
        try {
            setConnectionParam(ds, entry.getKey(), entry.getValue());
        } catch (Exception e) {
            LOG.warn("无法识别的连接池�数:" + entry);
        }
    }
    return ds;
}
Example 41
Project: qi4j-sdk-master  File: DBCPDataSourceServiceImporter.java View source code
@Override
protected BasicDataSource setupDataSourcePool(DataSourceConfigurationValue config) throws Exception {
    BasicDataSource pool = new BasicDataSource();
    Class.forName(config.driver().get());
    pool.setDriverClassName(config.driver().get());
    pool.setUrl(config.url().get());
    if (!config.username().get().equals("")) {
        pool.setUsername(config.username().get());
        pool.setPassword(config.password().get());
    }
    if (config.minPoolSize().get() != null) {
        pool.setMinIdle(config.minPoolSize().get());
    }
    if (config.maxPoolSize().get() != null) {
        pool.setMaxActive(config.maxPoolSize().get());
    }
    if (config.loginTimeoutSeconds().get() != null) {
        pool.setLoginTimeout(config.loginTimeoutSeconds().get());
    }
    if (config.maxConnectionAgeSeconds().get() != null) {
        pool.setMinEvictableIdleTimeMillis(config.maxConnectionAgeSeconds().get() * 1000);
    }
    if (config.validationQuery().get() != null) {
        pool.setValidationQuery(config.validationQuery().get());
    }
    return pool;
}
Example 42
Project: shard-master  File: AbstractSpringDBUnitTest.java View source code
private DataSource createDataSource(final String dataSetFile) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(org.h2.Driver.class.getName());
    result.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL", getFileName(dataSetFile)));
    result.setUsername("sa");
    result.setPassword("");
    result.setMaxActive(100);
    return result;
}
Example 43
Project: sharding-jdbc-master  File: AbstractSpringDBUnitTest.java View source code
private DataSource createDataSource(final String dataSetFile) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(org.h2.Driver.class.getName());
    result.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL", getFileName(dataSetFile)));
    result.setUsername("sa");
    result.setPassword("");
    result.setMaxActive(100);
    return result;
}
Example 44
Project: siena-master  File: PostgresTestNoAutoInc_4_SPECIALS.java View source code
@Override
public PersistenceManager createPersistenceManager(List<Class<?>> classes) throws Exception {
    if (pm == null) {
        Properties p = new Properties();
        String driver = "org.postgresql.Driver";
        String username = "siena";
        String password = "siena";
        String url = "jdbc:postgresql://localhost/siena";
        p.setProperty("driver", driver);
        p.setProperty("user", username);
        p.setProperty("password", password);
        p.setProperty("url", url);
        Class.forName(driver);
        BasicDataSource dataSource = new BasicDataSource();
        dataSource = new BasicDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        // 2 seconds max for wait a connection.
        dataSource.setMaxWait(2000);
        DdlGenerator generator = new DdlGenerator();
        for (Class<?> clazz : classes) {
            generator.addTable(clazz);
        }
        // get the Database model
        Database database = generator.getDatabase();
        Platform platform = PlatformFactory.createNewPlatformInstance("postgresql");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println(platform.getAlterTablesSql(connection, database));
        // this will perform the database changes
        platform.alterTables(connection, database, true);
        connection.close();
        pm = new PostgresqlPersistenceManager();
        pm.init(p);
    }
    return pm;
}
Example 45
Project: spring-batch-master  File: DataSourceConfiguration.java View source code
@Bean(destroyMethod = "close")
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(environment.getProperty("batch.jdbc.driver"));
    dataSource.setUrl(environment.getProperty("batch.jdbc.url"));
    dataSource.setUsername(environment.getProperty("batch.jdbc.user"));
    dataSource.setPassword(environment.getProperty("batch.jdbc.password"));
    return dataSource;
}
Example 46
Project: spring-batch-quartz-example-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "close")
public DataSource dbcpDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/batch_db");
    dataSource.setUsername("root");
    dataSource.setPassword("wakeup");
    dataSource.setMaxActive(20);
    dataSource.setMaxIdle(20);
    dataSource.setMaxWait(10000);
    dataSource.setInitialSize(5);
    dataSource.setValidationQuery("SELECT 1");
    dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    return dataSource;
}
Example 47
Project: spring-boot-data-jpa-mysql-master  File: DatabaseConfig.java View source code
@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(connectionSettings.getDriver());
    dataSource.setUrl(connectionSettings.getUrl());
    dataSource.setUsername(connectionSettings.getUsername());
    dataSource.setPassword(connectionSettings.getPassword());
    return dataSource;
}
Example 48
Project: spring-boot-master  File: DataSourceAutoConfigurationTests.java View source code
@Test
public void commonsDbcp2ValidatesConnectionByDefault() throws Exception {
    org.apache.commons.dbcp2.BasicDataSource dataSource = autoConfigureDataSource(org.apache.commons.dbcp2.BasicDataSource.class, "com.zaxxer.hikari", "org.apache.tomcat");
    assertThat(dataSource.getTestOnBorrow()).isEqualTo(true);
    // Use Connection#isValid()
    assertThat(dataSource.getValidationQuery()).isNull();
}
Example 49
Project: spring-social-flickr-master  File: MainConfig.java View source code
/*

    @Bean(destroyMethod = "shutdown")
    public DataSource dataSource() {
        EmbeddedDatabaseFactory factory = new EmbeddedDatabaseFactory();
        factory.setDatabaseName("spring-social-flickr");
        factory.setDatabaseType(EmbeddedDatabaseType.H2);
        factory.setDatabasePopulator(databasePopulator());
        return factory.getDatabase();
    }
*/
@Bean(destroyMethod = "close")
@Inject
public DataSource dataSource(Environment environment) throws Exception {
    String user = environment.getProperty("dataSource.user"), pw = environment.getProperty("dataSource.password"), host = environment.getProperty("dataSource.host");
    int port = Integer.parseInt(environment.getProperty("dataSource.port"));
    String db = environment.getProperty("dataSource.db");
    Class<Driver> driverClass = environment.getPropertyAsClass("dataSource.driverClassName", Driver.class);
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(driverClass.getName());
    basicDataSource.setPassword(pw);
    String url = String.format("jdbc:postgresql://%s:%s/%s", host, port, db);
    basicDataSource.setUrl(url);
    basicDataSource.setUsername(user);
    basicDataSource.setInitialSize(5);
    basicDataSource.setMaxActive(10);
    return basicDataSource;
}
Example 50
Project: Stage-master  File: ConnectionMonitoringTransformerTest.java View source code
@Parameterized.Parameters(name = "{index}: {1}")
public static Iterable<Object[]> data() throws Exception {
    final PoolProperties poolProperties = new PoolProperties();
    poolProperties.setDriverClassName(DRIVER_CLASS_NAME);
    poolProperties.setUrl(URL);
    final org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource = new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setDriverClass(DRIVER_CLASS_NAME);
    comboPooledDataSource.setJdbcUrl(URL);
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setDriverClassName(DRIVER_CLASS_NAME);
    hikariDataSource.setJdbcUrl(URL);
    org.apache.commons.dbcp.BasicDataSource dbcp = new org.apache.commons.dbcp.BasicDataSource();
    dbcp.setDriverClassName(DRIVER_CLASS_NAME);
    dbcp.setUrl(URL);
    org.apache.commons.dbcp2.BasicDataSource dbcp2 = new org.apache.commons.dbcp2.BasicDataSource();
    dbcp2.setDriverClassName(DRIVER_CLASS_NAME);
    dbcp2.setUrl(URL);
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setDriverClassName(DRIVER_CLASS_NAME);
    druidDataSource.setUrl(URL);
    druidDataSource.setTestWhileIdle(false);
    return Arrays.asList(new Object[][] { { tomcatDataSource, tomcatDataSource.getClass() }, { comboPooledDataSource, comboPooledDataSource.getClass() }, { hikariDataSource, hikariDataSource.getClass() }, { dbcp, dbcp.getClass() }, { dbcp2, dbcp2.getClass() }, { new P6DataSource(druidDataSource), druidDataSource.getClass() } });
}
Example 51
Project: stagemonitor-master  File: ConnectionMonitoringTransformerTest.java View source code
@Parameterized.Parameters(name = "{index}: {1}")
public static Iterable<Object[]> data() throws Exception {
    final PoolProperties poolProperties = new PoolProperties();
    poolProperties.setDriverClassName(DRIVER_CLASS_NAME);
    poolProperties.setUrl(URL);
    final org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource = new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setDriverClass(DRIVER_CLASS_NAME);
    comboPooledDataSource.setJdbcUrl(URL);
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setDriverClassName(DRIVER_CLASS_NAME);
    hikariDataSource.setJdbcUrl(URL);
    org.apache.commons.dbcp.BasicDataSource dbcp = new org.apache.commons.dbcp.BasicDataSource();
    dbcp.setDriverClassName(DRIVER_CLASS_NAME);
    dbcp.setUrl(URL);
    org.apache.commons.dbcp2.BasicDataSource dbcp2 = new org.apache.commons.dbcp2.BasicDataSource();
    dbcp2.setDriverClassName(DRIVER_CLASS_NAME);
    dbcp2.setUrl(URL);
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setDriverClassName(DRIVER_CLASS_NAME);
    druidDataSource.setUrl(URL);
    druidDataSource.setTestWhileIdle(false);
    return Arrays.asList(new Object[][] { { tomcatDataSource, tomcatDataSource.getClass() }, { comboPooledDataSource, comboPooledDataSource.getClass() }, { hikariDataSource, hikariDataSource.getClass() }, { dbcp, dbcp.getClass() }, { dbcp2, dbcp2.getClass() }, { new P6DataSource(druidDataSource), druidDataSource.getClass() } });
}
Example 52
Project: stockplay-master  File: OracleConnection.java View source code
public static Connection getConnection() throws StockPlayException {
    try {
        if (ds == null) {
            ds = new BasicDataSource();
            ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
            ds.setUrl("jdbc:oracle:thin:@//oersted.iii.hogent.be:1521/xe");
            ds.setUsername("stockplay");
            ds.setPassword("chocolademousse");
            ds.setTestOnBorrow(true);
            ds.setTestOnReturn(true);
            ds.setTestWhileIdle(true);
            ds.setRemoveAbandoned(true);
            // 15 seconden timeout
            ds.setMaxWait(15 * 1000);
            ds.setValidationQuery("select 1 from dual");
        }
        return ds.getConnection();
    } catch (SQLException ex) {
        throw new SubsystemException(SubsystemException.Type.DATABASE_FAILURE, "Error while creating connection-object", ex.getCause());
    }
}
Example 53
Project: streamflow-core-master  File: Dao.java View source code
private static void initializeDataSource() {
    Preferences preference = Preferences.userRoot().node("/streamsource/streamflow/StreamflowServer/streamflowds/properties");
    String dbUrl = preference.get("url", "n/a");
    String dbUser = preference.get("username", "n/a");
    String dbPwd = preference.get("password", "n/a");
    String dbDriver = preference.get("driver", "n/a");
    dbVendor = preference.get("dbVendor", "mysql");
    ds = new BasicDataSource();
    ds.setDriverClassName(dbDriver);
    ds.setUrl(dbUrl);
    ds.setUsername(dbUser);
    ds.setPassword(dbPwd);
    bDataSourceInitialized = true;
}
Example 54
Project: transaction-master  File: AbstractSpringDBUnitTest.java View source code
private DataSource createDataSource(final String dataSetFile) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(org.h2.Driver.class.getName());
    result.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL", getFileName(dataSetFile)));
    result.setUsername("sa");
    result.setPassword("");
    result.setMaxActive(100);
    return result;
}
Example 55
Project: umt-master  File: TokenDatabaseUtil.java View source code
public BasicDataSource getDataScource(Config config) {
    BasicDataSource ds = new BasicDataSource();
    ds.setMaxActive(config.getInt("database.maxconn", 10));
    ds.setMaxIdle(config.getInt("database.maxidle", 3));
    ds.setMaxWait(100);
    ds.setUsername(config.getStringProp("database.token.username", null));
    ds.setPassword(config.getStringProp("database.token.password", null));
    ds.setDriverClassName(config.getStringProp("database.driver", null));
    ds.setUrl(config.getStringProp("database.token.conn-url", null));
    ds.setTimeBetweenEvictionRunsMillis(3600000);
    ds.setMinEvictableIdleTimeMillis(1200000);
    return ds;
}
Example 56
Project: unitils-master  File: PropertiesDataSourceFactory.java View source code
public DataSource createDataSource() {
    logger.info("Creating data source. Driver: " + config.getDriverClassName() + ", url: " + config.getUrl() + ", user: " + config.getUserName() + ", password: <not shown>");
    BasicDataSource dataSource = getNewDataSource();
    dataSource.setDriverClassName(config.getDriverClassName());
    dataSource.setUsername(config.getUserName());
    dataSource.setPassword(config.getPassword());
    dataSource.setUrl(config.getUrl());
    return dataSource;
}
Example 57
Project: zstack-master  File: JpaUnitPostProcessor.java View source code
void init() {
    dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    String jdbcUrl = String.format("jdbc:mysql://%s/%s", getDbHost(), getDbName());
    dataSource.setUrl(jdbcUrl);
    dataSource.setUsername(getDbUser());
    dataSource.setPassword(getDbPassword());
}
Example 58
Project: epcis-master  File: DBConfiguration.java View source code
public static String getDB() {
    String config = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!-- dispatcher-servlet.xml -->\n" + "<beans xmlns=\"http://www.springframework.org/schema/beans\"\n" + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + "xmlns:context=\"http://www.springframework.org/schema/context\"\n" + "xsi:schemaLocation=\"http://www.springframework.org/schema/beans\n" + "http://www.springframework.org/schema/beans/spring-beans.xsd\n" + "http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\n" + "http://www.springframework.org/schema/data/mongo\n" + "http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd\">\n" + "<context:annotation-config/>\n" + "<context:component-scan base-package=\"org.oliot.epcis.serde.mysql\"/>\n" + "<bean id=\"queryOprationBackend\" class=\"org.oliot.epcis.service.query.mysql.QueryOprationBackend\"/>\n" + "<!--<bean id=\"dataSource\" class=\"org.apache.commons.dbcp2.BasicDataSource\">-->\n" + "<bean id=\"dataSource\" class=\"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n" + "<property name=\"driverClassName\" value=\"com.mysql.jdbc.Driver\"/>\n" + "<property name=\"url\" value=\"jdbc:mysql://localhost/epcis\"/>\n" + "<property name=\"username\" value=\"root\"/>\n" + "<property name=\"password\" value=\"root\"/>\n" + "<!--<property name=\"initialSize\" value=\"2\"/>\n" + "<property name=\"maxTotal\" value=\"100\"/>-->\n" + "</bean>" + "<!--org.springframework.orm.hibernate4.LocalSessionFactoryBean  -->\n" + "<bean id=\"sessionFactory\" class=\"org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean\">\n" + "<property name=\"dataSource\" ref=\"dataSource\" />\n" + "<property name=\"packagesToScan\" value=\"org.oliot.model.oliot\"/>\n" + "<property name=\"hibernateProperties\">\n" + "<props>\n" + "<prop key=\"dialect\">org.hibernate.dialect.MySQLDialect</prop>\n" + "<prop key=\"hibernate.hbm2ddl.auto\">update</prop>\n" + "<!--create-drop   update-->\n" + "<prop key=\"hibernate.show_sql\">true</prop>\n" + "<prop key=\"hibernate.format_sql\">true</prop>\n" + "<prop key=\"use_sql_comments\">true</prop>\n" + " </props>\n" + "</property>\n" + "<!--   <property name=\"hibernate.hbm2ddl.auto\" value=\"update\"/>\n" + "<property name=\"hibernate.show_sql\" value=\"true\"/>\n" + "<property name=\"hibernate.format_sql\" value=\"false\"/>-->\n" + "</bean>\n" + "</beans>\n";
    return config;
}
Example 59
Project: oliot-epcis-master  File: DBConfiguration.java View source code
public static String getDB() {
    String config = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!-- dispatcher-servlet.xml -->\n" + "<beans xmlns=\"http://www.springframework.org/schema/beans\"\n" + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + "xmlns:context=\"http://www.springframework.org/schema/context\"\n" + "xsi:schemaLocation=\"http://www.springframework.org/schema/beans\n" + "http://www.springframework.org/schema/beans/spring-beans.xsd\n" + "http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\n" + "http://www.springframework.org/schema/data/mongo\n" + "http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd\">\n" + "<context:annotation-config/>\n" + "<context:component-scan base-package=\"org.oliot.epcis.serde.mysql\"/>\n" + "<bean id=\"queryOprationBackend\" class=\"org.oliot.epcis.service.query.mysql.QueryOprationBackend\"/>\n" + "<!--<bean id=\"dataSource\" class=\"org.apache.commons.dbcp2.BasicDataSource\">-->\n" + "<bean id=\"dataSource\" class=\"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n" + "<property name=\"driverClassName\" value=\"com.mysql.jdbc.Driver\"/>\n" + "<property name=\"url\" value=\"jdbc:mysql://localhost/epcis\"/>\n" + "<property name=\"username\" value=\"root\"/>\n" + "<property name=\"password\" value=\"root\"/>\n" + "<!--<property name=\"initialSize\" value=\"2\"/>\n" + "<property name=\"maxTotal\" value=\"100\"/>-->\n" + "</bean>" + "<!--org.springframework.orm.hibernate4.LocalSessionFactoryBean  -->\n" + "<bean id=\"sessionFactory\" class=\"org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean\">\n" + "<property name=\"dataSource\" ref=\"dataSource\" />\n" + "<property name=\"packagesToScan\" value=\"org.oliot.model.oliot\"/>\n" + "<property name=\"hibernateProperties\">\n" + "<props>\n" + "<prop key=\"dialect\">org.hibernate.dialect.MySQLDialect</prop>\n" + "<prop key=\"hibernate.hbm2ddl.auto\">update</prop>\n" + "<!--create-drop   update-->\n" + "<prop key=\"hibernate.show_sql\">true</prop>\n" + "<prop key=\"hibernate.format_sql\">true</prop>\n" + "<prop key=\"use_sql_comments\">true</prop>\n" + " </props>\n" + "</property>\n" + "<!--   <property name=\"hibernate.hbm2ddl.auto\" value=\"update\"/>\n" + "<property name=\"hibernate.show_sql\" value=\"true\"/>\n" + "<property name=\"hibernate.format_sql\" value=\"false\"/>-->\n" + "</bean>\n" + "</beans>\n";
    return config;
}
Example 60
Project: aokp-gerrit-master  File: ReviewDbDataSourceProvider.java View source code
private void closeDataSource(final DataSource ds) {
    try {
        Class<?> type = Class.forName("org.apache.commons.dbcp.BasicDataSource");
        if (type.isInstance(ds)) {
            type.getMethod("close").invoke(ds);
            return;
        }
    } catch (Throwable bad) {
    }
    try {
        Class<?> type = Class.forName("com.mchange.v2.c3p0.DataSources");
        if (type.isInstance(ds)) {
            type.getMethod("destroy", DataSource.class).invoke(null, ds);
        }
    } catch (Throwable bad) {
    }
}
Example 61
Project: assertj-db-master  File: SqliteConfiguration.java View source code
@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.sqlite.JDBC");
    dataSource.setUrl("jdbc:sqlite:target/testDerby.db");
    dataSource.setUsername("");
    dataSource.setPassword("");
    try {
        try (Connection connection = dataSource.getConnection()) {
            try (Statement statement = connection.createStatement()) {
                statement.executeUpdate("drop table if exists teSt;");
                statement.executeUpdate("create table teSt (" + " Var1 BIGINT PRIMARY KEY,\n" + " vAr2 BLOB,\n" + " vaR3 CHAR,\n" + " var4 CHAR FOR BIT DATA,\n" + " var5 CLOB,\n" + " var6 DATE,\n" + " var7 DECIMAL,\n" + " var8 DOUBLE,\n" + " var9 DOUBLE PRECISION,\n" + " var10 FLOAT,\n" + " var11 INTEGER,\n" + " var12 LONG VARCHAR,\n" + " var13 LONG VARCHAR FOR BIT DATA,\n" + " var14 NUMERIC,\n" + " var15 REAL,\n" + " var16 SMALLINT,\n" + " var17 TIME,\n" + " var18 TIMESTAMP,\n" + " var19 VARCHAR,\n" + " var20 VARCHAR FOR BIT DATA" + " )");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dataSource;
}
Example 62
Project: cayenne-master  File: DBCP2DataSourceFactoryTest.java View source code
@Test
public void testGetDataSource() throws Exception {
    String baseUrl = getClass().getPackage().getName().replace('.', '/');
    URL url = getClass().getClassLoader().getResource(baseUrl + "/");
    assertNotNull(url);
    DataNodeDescriptor nodeDescriptor = new DataNodeDescriptor();
    nodeDescriptor.setConfigurationSource(new URLResource(url));
    nodeDescriptor.setParameters("testDBCP2.properties");
    DBCPDataSourceFactory factory = new DBCPDataSourceFactory();
    DataSource dataSource = factory.getDataSource(nodeDescriptor);
    assertNotNull(dataSource);
    assertTrue(dataSource instanceof BasicDataSource);
    try (BasicDataSource basicDataSource = (BasicDataSource) dataSource) {
        assertEquals("com.example.jdbc.Driver", basicDataSource.getDriverClassName());
        assertEquals("jdbc:somedb://localhost/cayenne", basicDataSource.getUrl());
        assertEquals("john", basicDataSource.getUsername());
        assertEquals("secret", basicDataSource.getPassword());
        assertEquals(20, basicDataSource.getMaxTotal());
        assertEquals(5, basicDataSource.getMinIdle());
        assertEquals(8, basicDataSource.getMaxIdle());
        assertEquals(10000, basicDataSource.getMaxWaitMillis());
        assertEquals("select 1 from xyz;", basicDataSource.getValidationQuery());
    }
}
Example 63
Project: DataCleaner-master  File: TestHelper.java View source code
public static DataSource createSampleDatabaseDataSource() {
    final BasicDataSource _dataSource = new BasicDataSource();
    _dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
    _dataSource.setUrl("jdbc:hsqldb:res:orderdb;readonly=true");
    _dataSource.setMaxActive(-1);
    _dataSource.setDefaultAutoCommit(false);
    return _dataSource;
}
Example 64
Project: dddlib-master  File: CommonsDbcpDataSourceCreatorTest.java View source code
@Test
public void createDataSourceForTenantByMysqlAndDbname() throws Exception {
    instance.setDbType(DbType.ORACLE);
    instance.setMappingStrategy(TenantDbMappingStrategy.INSTANCE);
    String url = "jdbc:oracle:thin:@localhost:3306:DB_ABC?useUnicode=true&characterEncoding=utf-8";
    DataSource result = instance.createDataSourceForTenant(tenant);
    assertThat(result, instanceOf(BasicDataSource.class));
    assertEquals("oracle.jdbc.OracleDriver", BeanUtils.getProperty(result, "driverClassName"));
    assertEquals(url, BeanUtils.getProperty(result, "url"));
    assertEquals("root", BeanUtils.getProperty(result, "username"));
    assertEquals("1234", BeanUtils.getProperty(result, "password"));
    assertEquals("100", BeanUtils.getProperty(result, "initialSize"));
}
Example 65
Project: easyweb-master  File: DataSourceProcessor.java View source code
@Override
public void process(ScanResult result) throws DeployException {
    List<String> list = result.getSuffixFiles(".properties");
    if (list.isEmpty()) {
        return;
    }
    App app = result.getApp();
    for (String file : list) {
        if (!file.endsWith("datasource.properties")) {
            continue;
        }
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(file));
        } catch (Exception e) {
        }
        String type = properties.getProperty("ds.type");
        String name = properties.getProperty("ds.name");
        String driverClassName = properties.getProperty("ds.driverClassName");
        String url = properties.getProperty("ds.url");
        String username = properties.getProperty("ds.username", "");
        String password = properties.getProperty("ds.password", "");
        if ("simple".equals(type)) {
            SimpleDataSource dataSource = new SimpleDataSource();
            try {
                dataSource.setDriverClassName(driverClassName);
            } catch (ClassNotFoundException e) {
            }
            dataSource.setJdbcUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            DatasourceFactory.regist(app, name, dataSource);
        } else if ("tddl".equals(type)) {
            //tddlµÄ²ÉÓÃspring bean×¢Èë
            String appName = properties.getProperty("tddl.appName");
            String dbGroupKey = properties.getProperty("tddl.dbGroupKey");
            if (StringUtils.isBlank(appName) || StringUtils.isBlank(dbGroupKey)) {
                throw new RuntimeException("tddl datasource config error");
            }
            TGroupDataSource dataSource = new TGroupDataSource();
            dataSource.setAppName(appName);
            dataSource.setDbGroupKey(dbGroupKey);
            dataSource.init();
            DatasourceFactory.regist(app, name, dataSource);
        } else if ("dbcp".equals(type)) {
            BasicDataSource basicDataSource = new BasicDataSource();
            basicDataSource.setDriverClassName(driverClassName);
            basicDataSource.setUrl(url);
            basicDataSource.setUsername(username);
            basicDataSource.setPassword(password);
            DatasourceFactory.regist(app, name, basicDataSource);
        }
    }
}
Example 66
Project: edu-master  File: JdbcTemplatePersonDaoIntegrationTest.java View source code
@Test
public void testFindAll() throws Exception {
    JdbcTemplatePersonDao dao = new JdbcTemplatePersonDao();
    dao.setDataSource(new BasicDataSource() {

        @Override
        public Connection getConnection() throws SQLException {
            return getJdbcConnection();
        }
    });
    assertEquals(expectedList, dao.findAll());
}
Example 67
Project: ef-orm-master  File: JDBCTransactionTest.java View source code
/*
	 * mysql> create table t_user (user_name varchar(255),score int,password1 varchar(255));
	 */
@Test
public void testJdbcWithoutTransManager() throws SQLException {
    ApplicationContext ctx = super.initContext();
    UserJdbcWithoutTransManagerService service = (UserJdbcWithoutTransManagerService) ctx.getBean("service1");
    JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
    BasicDataSource basicDataSource = (BasicDataSource) jdbcTemplate.getDataSource();
    checkTable(basicDataSource);
    // ①.检查数��autoCommit的设置
    System.out.println("autoCommit:" + basicDataSource.getDefaultAutoCommit());
    // ②.�入一�记录,�始分数为10
    jdbcTemplate.execute("INSERT INTO t_user (user,password,score) VALUES ('tom','123456',10)");
    // ③.调用工作在无事务环境下的�务类方法,将分数添加20分
    service.addScore("tom", 20);
    // ④.查看此时用户的分数
    int score = jdbcTemplate.queryForObject("SELECT score FROM t_user WHERE user='tom'", Integer.class);
    System.out.println("score:" + score);
    //		jdbcTemplate.execute("DELETE FROM t_user WHERE user='tom'");
    assertEquals(30, score);
}
Example 68
Project: ff-master  File: JdbcTestHelper.java View source code
/**
     * Initialize DataSource with a pool of connections to HQL database.
     *
     * @return
     *      current data source
     */
public static DataSource createInMemoryHQLDataSource() {
    // Init DataSource
    BasicDataSource dbcpDataSource = new BasicDataSource();
    dbcpDataSource.setDriverClassName("org.hsqldb.jdbcDriver");
    dbcpDataSource.setUsername("sa");
    dbcpDataSource.setPassword("");
    dbcpDataSource.setUrl("jdbc:hsqldb:mem:.");
    dbcpDataSource.setMaxActive(3);
    dbcpDataSource.setMaxIdle(2);
    dbcpDataSource.setInitialSize(2);
    dbcpDataSource.setValidationQuery("select 1 from INFORMATION_SCHEMA.SYSTEM_USERS;");
    dbcpDataSource.setPoolPreparedStatements(true);
    return dbcpDataSource;
}
Example 69
Project: ff4j-master  File: JdbcTestHelper.java View source code
/**
     * Initialize DataSource with a pool of connections to HQL database.
     *
     * @return
     *      current data source
     */
public static DataSource createInMemoryHQLDataSource() {
    // Init DataSource
    BasicDataSource dbcpDataSource = new BasicDataSource();
    dbcpDataSource.setDriverClassName("org.hsqldb.jdbcDriver");
    dbcpDataSource.setUsername("sa");
    dbcpDataSource.setPassword("");
    dbcpDataSource.setUrl("jdbc:hsqldb:mem:.");
    dbcpDataSource.setMaxActive(3);
    dbcpDataSource.setMaxIdle(2);
    dbcpDataSource.setInitialSize(2);
    dbcpDataSource.setValidationQuery("select 1 from INFORMATION_SCHEMA.SYSTEM_USERS;");
    dbcpDataSource.setPoolPreparedStatements(true);
    return dbcpDataSource;
}
Example 70
Project: geotools-2.7.x-master  File: OracleDialectEpsgMediatorConnectionLeakOnlineTest.java View source code
protected void connect() throws Exception {
    super.connect();
    hints = new Hints(Hints.CACHE_POLICY, "none");
    hints.put(Hints.AUTHORITY_MAX_ACTIVE, new Integer(MAX_WORKERS));
    if (datasource == null) {
        fail("no datasource available");
    }
    wrappedDataSource = new BasicDataSource() {

        {
            this.dataSource = datasource;
        }
    };
    mediator = new OracleDialectEpsgMediator(80, hints, wrappedDataSource);
    codes = OracleDialectEpsgMediatorOnlineStressTest.getCodes();
}
Example 71
Project: geotools-master  File: SpatiaLiteTestSetup.java View source code
@Override
protected void initializeDataSource(BasicDataSource ds, Properties db) {
    super.initializeDataSource(ds, db);
    try {
        SpatiaLiteDataStoreFactory.addConnectionProperties(ds);
        SpatiaLiteDataStoreFactory.initializeDataSource(ds);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
}
Example 72
Project: geotools-old-master  File: OracleDialectEpsgMediatorConnectionLeakOnlineTest.java View source code
protected void connect() throws Exception {
    super.connect();
    hints = new Hints(Hints.CACHE_POLICY, "none");
    hints.put(Hints.AUTHORITY_MAX_ACTIVE, new Integer(MAX_WORKERS));
    if (datasource == null) {
        fail("no datasource available");
    }
    wrappedDataSource = new BasicDataSource() {

        {
            this.dataSource = datasource;
        }
    };
    mediator = new OracleDialectEpsgMediator(80, hints, wrappedDataSource);
    codes = OracleDialectEpsgMediatorOnlineStressTest.getCodes();
}
Example 73
Project: geotools-tike-master  File: OracleDialectEpsgMediatorConnectionLeakOnlineTest.java View source code
protected void connect() throws Exception {
    super.connect();
    hints = new Hints(Hints.CACHE_POLICY, "none");
    hints.put(Hints.AUTHORITY_MAX_ACTIVE, new Integer(MAX_WORKERS));
    if (datasource == null) {
        fail("no datasource available");
    }
    wrappedDataSource = new BasicDataSource() {

        {
            this.dataSource = datasource;
        }
    };
    mediator = new OracleDialectEpsgMediator(80, hints, wrappedDataSource);
    codes = OracleDialectEpsgMediatorOnlineStressTest.getCodes();
}
Example 74
Project: geotools_trunk-master  File: OracleDialectEpsgMediatorConnectionLeakOnlineTest.java View source code
protected void connect() throws Exception {
    super.connect();
    hints = new Hints(Hints.CACHE_POLICY, "none");
    hints.put(Hints.AUTHORITY_MAX_ACTIVE, new Integer(MAX_WORKERS));
    if (datasource == null) {
        fail("no datasource available");
    }
    wrappedDataSource = new BasicDataSource() {

        {
            this.dataSource = datasource;
        }
    };
    mediator = new OracleDialectEpsgMediator(80, hints, wrappedDataSource);
    codes = OracleDialectEpsgMediatorOnlineStressTest.getCodes();
}
Example 75
Project: gerrit-master  File: ReviewDbDataSourceProvider.java View source code
private void closeDataSource(final DataSource ds) {
    try {
        Class<?> type = Class.forName("org.apache.commons.dbcp.BasicDataSource");
        if (type.isInstance(ds)) {
            type.getMethod("close").invoke(ds);
            return;
        }
    } catch (Throwable bad) {
    }
    try {
        Class<?> type = Class.forName("com.mchange.v2.c3p0.DataSources");
        if (type.isInstance(ds)) {
            type.getMethod("destroy", DataSource.class).invoke(null, ds);
        }
    } catch (Throwable bad) {
    }
}
Example 76
Project: gsn-master  File: DataSources.java View source code
public static BasicDataSource getDataSource(DBConnectionInfo dci) {
    BasicDataSource ds = null;
    try {
        ds = (BasicDataSource) GSNContext.getMainContext().lookup(Integer.toString(dci.hashCode()));
        if (ds == null) {
            ds = new BasicDataSource();
            ds.setDriverClassName(dci.getDriverClass());
            ds.setUsername(dci.getUserName());
            ds.setPassword(dci.getPassword());
            ds.setUrl(dci.getUrl());
            //ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            //ds.setAccessToUnderlyingConnectionAllowed(true); 
            GSNContext.getMainContext().bind(Integer.toString(dci.hashCode()), ds);
            logger.info("Created a DataSource to: " + ds.getUrl());
        }
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }
    return ds;
}
Example 77
Project: javablog-master  File: DbcpPool.java View source code
@Test
public void testDbcp() {
    //Dbcp连接池核心类
    BasicDataSource dataSource = new BasicDataSource();
    //连接池�数�置:�始化连接数�最大连接数 / 连接字符串�驱动�用户�密�
    dataSource.setUrl("jdbc:mysql://localhost:3306/day01?useUnicode=true&characterEncoding=UTF8");
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUsername("root");
    dataSource.setPassword("126165");
    // �始化连接
    dataSource.setInitialSize(3);
    // 最大连接
    dataSource.setMaxActive(6);
    // 最大空闲时间
    dataSource.setMaxIdle(3000);
    try {
        //获�连接
        Connection connection = dataSource.getConnection();
        //关闭
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
Example 78
Project: KeyBox-master  File: DSPool.java View source code
/**
     * register the data source for H2 DB
     *
     * @return pooling database object
     */
private static BasicDataSource registerDataSource() {
    System.setProperty("h2.baseDir", BASE_DIR);
    // create a database connection
    String user = AppConfig.getProperty("dbUser");
    String password = AppConfig.decryptProperty("dbPassword");
    String connectionURL = AppConfig.getProperty("dbConnectionURL");
    if (connectionURL != null && connectionURL.contains("CIPHER=")) {
        password = "filepwd " + password;
    }
    String validationQuery = "select 1";
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(DB_DRIVER);
    dataSource.setMaxTotal(MAX_ACTIVE);
    dataSource.setTestOnBorrow(TEST_ON_BORROW);
    dataSource.setMinIdle(MIN_IDLE);
    dataSource.setMaxWaitMillis(MAX_WAIT);
    dataSource.setValidationQuery(validationQuery);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    dataSource.setUrl(connectionURL);
    return dataSource;
}
Example 79
Project: longneck-core-master  File: JdbcConfiguration.java View source code
public DataSource getDataSource() {
    if (dataSource == null) {
        String driverClass = properties.getProperty("driverClassName", null);
        if (driverClass != null && !"".equals(driverClass)) {
            // Load driver class
            try {
                Class.forName(driverClass);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(String.format("Could not load driver class for database connection %1$s: %2$s.", name, driverClass), ex);
            }
        }
        try {
            dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception ex) {
            throw new RuntimeException(String.format("Could not create JDBC datasource %1$s.", name), ex);
        }
    }
    return dataSource;
}
Example 80
Project: mango-master  File: DataSourceConfig.java View source code
public static DataSource getDataSource(int i, boolean autoCommit, int maxActive) {
    String driverClassName = getDriverClassName(i);
    String url = getUrl(i);
    String username = getUsername(i);
    String password = getPassword(i);
    BasicDataSource ds = new BasicDataSource();
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    ds.setInitialSize(1);
    ds.setMaxActive(maxActive);
    ds.setDriverClassName(driverClassName);
    ds.setDefaultAutoCommit(autoCommit);
    return ds;
}
Example 81
Project: mini-git-server-master  File: ReviewDbDataSourceProvider.java View source code
private void closeDataSource(final DataSource ds) {
    try {
        Class<?> type = Class.forName("org.apache.commons.dbcp.BasicDataSource");
        if (type.isInstance(ds)) {
            type.getMethod("close").invoke(ds);
            return;
        }
    } catch (Throwable bad) {
    }
    try {
        Class<?> type = Class.forName("com.mchange.v2.c3p0.DataSources");
        if (type.isInstance(ds)) {
            type.getMethod("destroy", DataSource.class).invoke(null, ds);
            return;
        }
    } catch (Throwable bad) {
    }
}
Example 82
Project: OpERP-master  File: JpaTestContext.java View source code
@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
    dataSource.setUrl(env.getProperty("jdbc.url"));
    dataSource.setUsername(env.getProperty("jdbc.username"));
    dataSource.setPassword(env.getProperty("jdbc.password"));
    dataSource.setInitialSize(2);
    dataSource.setMaxActive(10);
    return dataSource;
}
Example 83
Project: qi4j-extensions-master  File: ImportedDataSourceServiceTest.java View source code
@SuppressWarnings("unchecked")
public void assemble(ModuleAssembly module) throws AssemblyException {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl(CONNECTION_STRING);
    try {
        new DerbySQLEntityStoreAssembler(new DataSourceAssembler(new ImportableDataSourceService(dataSource))).assemble(module);
    } catch (AssemblyException e) {
        Assume.assumeNoException(e);
    }
}
Example 84
Project: skysail-server-ext-master  File: FlywaySetup.java View source code
public void init() {
    Map<?, ?> properties = (Map<?, ?>) enitityManagerFactory.getProperties().get("PUnitInfo");
    BasicDataSource bds = new BasicDataSource();
    if (properties == null) {
        // test case
        bds.setUrl((String) enitityManagerFactory.getProperties().get("javax.persistence.jdbc.url"));
        bds.setPassword((String) enitityManagerFactory.getProperties().get("javax.persistence.jdbc.password"));
        bds.setUsername((String) enitityManagerFactory.getProperties().get("javax.persistence.jdbc.user"));
        bds.setDriverClassName((String) enitityManagerFactory.getProperties().get("javax.persistence.jdbc.driver"));
    } else {
        bds.setUrl((String) properties.get("driverUrl"));
        bds.setPassword((String) properties.get("driverPassword"));
        bds.setUsername((String) properties.get("driverUser"));
        bds.setDriverClassName((String) properties.get("driverClassName"));
    }
    flyway.setDataSource(bds);
    flyway.setTable("skysail_server_ext_notes_schema_version");
    // flyway.setLocations();
    ClassLoader ccl = Thread.currentThread().getContextClassLoader();
    ClassLoader thisClassLoader = this.getClass().getClassLoader();
    Thread.currentThread().setContextClassLoader(thisClassLoader);
    flyway.setInitOnMigrate(true);
    flyway.migrate();
    Thread.currentThread().setContextClassLoader(ccl);
}
Example 85
Project: spring-cloud-stream-modules-master  File: GreenplumDataSourceFactoryBean.java View source code
@Override
protected BasicDataSource createInstance() throws Exception {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.postgresql.Driver");
    if (StringUtils.hasText(dbUser)) {
        ds.setUsername(dbUser);
    }
    if (StringUtils.hasText(dbPassword)) {
        ds.setPassword(dbPassword);
    }
    ds.setUrl("jdbc:postgresql://" + dbHost + ":" + dbPort + "/" + dbName);
    return ds;
}
Example 86
Project: spring-xd-master  File: GreenplumDataSourceFactoryBean.java View source code
@Override
protected BasicDataSource createInstance() throws Exception {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.postgresql.Driver");
    if (StringUtils.hasText(dbUser)) {
        ds.setUsername(dbUser);
    }
    if (StringUtils.hasText(dbPassword)) {
        ds.setPassword(dbPassword);
    }
    ds.setUrl("jdbc:postgresql://" + dbHost + ":" + dbPort + "/" + dbName);
    return ds;
}
Example 87
Project: symmetric-ds-master  File: DbSqlCommand.java View source code
@Override
protected boolean executeWithOptions(CommandLine line) throws Exception {
    BasicDataSource basicDataSource = getDatabasePlatform(false).getDataSource();
    String url = basicDataSource.getUrl();
    String user = basicDataSource.getUsername();
    String password = basicDataSource.getPassword();
    String driver = basicDataSource.getDriverClassName();
    Shell shell = new Shell();
    if (line.hasOption(OPTION_SQL)) {
        String sql = line.getOptionValue(OPTION_SQL);
        shell.runTool("-url", url, "-user", user, "-password", password, "-driver", driver, "-sql", sql);
    } else {
        shell.runTool("-url", url, "-user", user, "-password", password, "-driver", driver);
    }
    return true;
}
Example 88
Project: TeeFun-master  File: DataBaseConfig.java View source code
/**
	 * @return the default data source
	 */
@Bean
public DataSource defaultDataSource() {
    final BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(this.env.getProperty("jdbc.driverClassName"));
    dataSource.setUrl(this.env.getProperty("jdbc.url"));
    dataSource.setUsername(this.env.getProperty("jdbc.user"));
    dataSource.setPassword(this.env.getProperty("jdbc.pass"));
    return dataSource;
}
Example 89
Project: tools_gerrit-master  File: ReviewDbDataSourceProvider.java View source code
private void closeDataSource(final DataSource ds) {
    try {
        Class<?> type = Class.forName("org.apache.commons.dbcp.BasicDataSource");
        if (type.isInstance(ds)) {
            type.getMethod("close").invoke(ds);
            return;
        }
    } catch (Throwable bad) {
    }
    try {
        Class<?> type = Class.forName("com.mchange.v2.c3p0.DataSources");
        if (type.isInstance(ds)) {
            type.getMethod("destroy", DataSource.class).invoke(null, ds);
            return;
        }
    } catch (Throwable bad) {
    }
}
Example 90
Project: openjpa-master  File: DBCPDriverDataSource.java View source code
public void close() throws SQLException {
    try {
        if (_ds != null) {
            if (isDBCPLoaded(getClassLoader())) {
                ((org.apache.commons.dbcp.BasicDataSource) _dbcpClass.cast(_ds)).close();
            }
        }
    } catch (Exception e) {
    } catch (Throwable t) {
    } finally {
        _ds = null;
    }
}
Example 91
Project: airavata-master  File: JPAUtils.java View source code
public static EntityManager getEntityManager() {
    if (factory == null) {
        //FIXME
        String connectionProperties = "DriverClassName=" + Utils.getJDBCDriver() + "," + "Url=" + Utils.getJDBCURL() + "?autoReconnect=true," + "Username=" + Utils.getJDBCUser() + "," + "Password=" + Utils.getJDBCPassword() + ",validationQuery=" + Utils.getValidationQuery();
        logger.info(connectionProperties);
        Map<String, String> properties = new HashMap<String, String>();
        properties.put("openjpa.ConnectionDriverName", "org.apache.commons.dbcp.BasicDataSource");
        properties.put("openjpa.ConnectionProperties", connectionProperties);
        properties.put("openjpa.DynamicEnhancementAgent", "true");
        properties.put("openjpa.RuntimeUnenhancedClasses", "warn");
        properties.put("openjpa.RemoteCommitProvider", "sjvm");
        properties.put("openjpa.Log", "DefaultLevel=INFO, Runtime=INFO, Tool=INFO, SQL=INFO");
        properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
        properties.put("openjpa.jdbc.QuerySQLCache", "false");
        properties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72," + " PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=31536000,  autoReconnect=true");
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties);
    }
    entityManager = factory.createEntityManager();
    return entityManager;
}
Example 92
Project: azkaban-master  File: MySQLDataSource.java View source code
/**
   * This method overrides {@link BasicDataSource#getConnection()}, in order to have retry logics.
   *
   */
@Override
public synchronized Connection getConnection() throws SQLException {
    Connection connection = null;
    int retryAttempt = 0;
    while (retryAttempt < AzDBUtil.MAX_DB_RETRY_COUNT) {
        try {
            /**
         * when DB connection could not be fetched (e.g., network issue), or connection can not be validated,
         * {@link BasicDataSource} throws a SQL Exception. {@link BasicDataSource#dataSource} will be reset to null.
         * createDataSource() will create a new dataSource.
         * Every Attempt generates a thread-hanging-time, about 75 seconds, which is hard coded, and can not be changed.
         */
            connection = createDataSource().getConnection();
            if (connection != null)
                return connection;
        } catch (SQLException ex) {
            logger.error("Failed to find DB connection. waits 1 minutes and retry. No.Attempt = " + retryAttempt, ex);
        } finally {
            retryAttempt++;
        }
    }
    return null;
}
Example 93
Project: beakerx-master  File: JDBCClient.java View source code
public BasicDataSource getDataSource(String uri) throws DBConnectionException {
    synchronized (this) {
        try {
            BasicDataSource ds = dsMap.get(uri);
            if (ds == null) {
                Driver driver = null;
                for (Driver test : drivers) {
                    if (test.acceptsURL(uri)) {
                        driver = test;
                        break;
                    }
                }
                if (driver == null) {
                    DriverManager.getDriver(uri);
                }
                ds = new BasicDataSource();
                ds.setDriver(driver);
                ds.setUrl(uri);
                dsMap.put(uri, ds);
            }
            return ds;
        } catch (SQLException e) {
            throw new DBConnectionException(uri, e);
        }
    }
}
Example 94
Project: bi-platform-v2-master  File: NonPooledOrJndiDatasourceService.java View source code
private DataSource convert(IDatasource datasource) {
    BasicDataSource basicDatasource = new BasicDataSource();
    basicDatasource.setDriverClassName(datasource.getDriverClass());
    basicDatasource.setMaxActive(datasource.getMaxActConn());
    basicDatasource.setMaxIdle(datasource.getIdleConn());
    basicDatasource.setMaxWait(datasource.getWait());
    basicDatasource.setUrl(datasource.getUrl());
    basicDatasource.setUsername(datasource.getUserName());
    basicDatasource.setPassword(datasource.getPassword());
    basicDatasource.setValidationQuery(datasource.getQuery());
    return basicDatasource;
}
Example 95
Project: carbon-business-process-master  File: JDBCManager.java View source code
public void initFromFileConfig(String dbConfigurationPath) throws AttachmentMgtException {
    String jdbcURL;
    String driver;
    String username;
    String password;
    String validationQuery;
    if (dataSource == null) {
        synchronized (JDBCManager.class) {
            if (dataSource == null) {
                JDBCConfiguration configuration = getDBConfig(dbConfigurationPath);
                jdbcURL = configuration.getJdbcURL();
                driver = configuration.getDriver();
                username = configuration.getUsername();
                password = configuration.getPassword();
                validationQuery = configuration.getValidationQuery();
                if (jdbcURL == null || driver == null || username == null || password == null) {
                    throw new AttachmentMgtException("DB configurations are not properly defined");
                }
                dataSource = new BasicDataSource();
                dataSource.setDriverClassName(driver);
                dataSource.setUrl(jdbcURL);
                dataSource.setUsername(username);
                dataSource.setPassword(password);
                dataSource.setValidationQuery(validationQuery);
            }
        }
    }
}
Example 96
Project: compass-fork-master  File: DbcpDataSourceProvider.java View source code
protected DataSource doCreateDataSource(String url, CompassSettings settings) throws CompassException {
    BasicDataSource dataSource = new BasicDataSource();
    if (!externalAutoCommit) {
        dataSource.setDefaultAutoCommit(autoCommit);
    }
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.DEFAULT_TRANSACTION_ISOLATION) != null) {
        dataSource.setDefaultTransactionIsolation(settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.DEFAULT_TRANSACTION_ISOLATION, 0));
    }
    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.INITIAL_SIZE) != null) {
        dataSource.setInitialSize(settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.INITIAL_SIZE, 0));
    }
    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_ACTIVE) != null) {
        dataSource.setMaxActive(settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_ACTIVE, 0));
    }
    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_IDLE) != null) {
        dataSource.setMaxIdle(settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_IDLE, 0));
    }
    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MIN_IDLE) != null) {
        dataSource.setMinIdle(settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MIN_IDLE, 0));
    }
    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_WAIT) != null) {
        dataSource.setMaxWait(settings.getSettingAsLong(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_WAIT, 0));
    }
    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_OPEN_PREPARED_STATEMENTS) != null) {
        dataSource.setMaxOpenPreparedStatements(settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_OPEN_PREPARED_STATEMENTS, 0));
    }
    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.POOL_PREPARED_STATEMENTS) != null) {
        dataSource.setPoolPreparedStatements(settings.getSettingAsBoolean(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.POOL_PREPARED_STATEMENTS, false));
    }
    return dataSource;
}
Example 97
Project: DASP-master  File: DbcpJdbcFactory.java View source code
/**
     * {@inheritDoc}
     */
@Override
protected DataSource buildDataSource(String driver, String connUrl, String username, String password, DbcpInfo dbcpInfo) throws SQLException {
    int maxActive = dbcpInfo != null ? dbcpInfo.getMaxActive() : DbcpInfo.DEFAULT_MAX_ACTIVE;
    long maxWaitTime = dbcpInfo != null ? dbcpInfo.getMaxWaitTime() : DbcpInfo.DEFAULT_MAX_WAIT_TIME;
    int maxIdle = dbcpInfo != null ? dbcpInfo.getMaxIdle() : DbcpInfo.DEFAULT_MAX_IDLE;
    int minIdle = dbcpInfo != null ? dbcpInfo.getMinIdle() : DbcpInfo.DEFAULT_MIN_IDLE;
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Building a datasource {driver:" + driver + ";connUrl:" + connUrl + ";username:" + username + ";maxActive:" + maxActive + ";maxWait:" + maxWaitTime + ";minIdle:" + minIdle + ";maxIdle:" + maxIdle + "}...");
    }
    try {
        /*
             * Note: we load the driver class here!
             */
        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        throw new SQLException(e);
    }
    BasicDataSource ds = new BasicDataSource();
    ds.setTestOnBorrow(true);
    int maxConnLifetime = (int) (getMaxConnectionLifetime() / 1000);
    if (maxConnLifetime > 0) {
        ds.setRemoveAbandoned(true);
        ds.setRemoveAbandonedTimeout(maxConnLifetime + 100);
    }
    // ds.setDriverClassName(driver);
    ds.setUrl(connUrl);
    ds.setUsername(username);
    ds.setPassword(password);
    ds.setMaxActive(maxActive);
    ds.setMaxIdle(maxIdle);
    ds.setMaxWait(maxWaitTime);
    ds.setMinIdle(minIdle);
    String validationQuery = getValidationQuery(driver);
    if (!StringUtils.isBlank(validationQuery)) {
        ds.setValidationQuery(validationQuery);
        // PostgreSQL still not support the set query timeout method
        if (driver != null && !driver.contains("postgresql")) {
            // set the validation query timeout to 1 second
            ds.setValidationQueryTimeout(1);
        }
    }
    {
        String dsName = calcHash(driver, connUrl, username, password, dbcpInfo);
        DataSourceInfo dsInfo = internalGetDataSourceInfo(dsName);
        dsInfo.setMaxActives(maxActive).setMaxIdles(maxIdle).setMaxWait(maxWaitTime).setMinIdles(minIdle);
    }
    return ds;
}
Example 98
Project: hutool-master  File: DbcpDSFactory.java View source code
@Override
public synchronized DataSource getDataSource(String group) {
    if (group == null) {
        group = StrUtil.EMPTY;
    }
    // 如果已�存在已有数��(连接池)直接返回
    final BasicDataSource existedDataSource = dsMap.get(group);
    if (existedDataSource != null) {
        return existedDataSource;
    }
    BasicDataSource ds = createDataSource(group);
    // 添加到数��池中,以备下次使用
    dsMap.put(group, ds);
    return ds;
}
Example 99
Project: InSpider-master  File: H2GeometryStoreTest.java View source code
@Before
public void setUp() throws Exception {
    h2GeometryStore = new H2GeometryStore();
    Field field = H2GeometryStore.class.getDeclaredField("JDBC_URL_FORMAT");
    field.setAccessible(true);
    field.set(h2GeometryStore, String.format("jdbc:h2:%s/", testFolder.getRoot()) + "%s");
    dataSource = (BasicDataSource) h2GeometryStore.createStore(DB_NAME);
}
Example 100
Project: javamelody-mirror-backup-master  File: TestJdbcWrapper.java View source code
/** Test.
	 * @throws Exception e */
@Test
public // NOPMD
void testCreateDataSourceProxy() throws // NOPMD
Exception {
    // on fait le ménage au cas où TestMonitoringSpringInterceptor ait été exécuté juste avant
    cleanUp();
    assertTrue("getBasicDataSourceProperties0", JdbcWrapper.getBasicDataSourceProperties().isEmpty());
    assertEquals("getMaxConnectionCount0", -1, JdbcWrapper.getMaxConnectionCount());
    final org.apache.tomcat.jdbc.pool.DataSource tomcatJdbcDataSource = new org.apache.tomcat.jdbc.pool.DataSource();
    tomcatJdbcDataSource.setUrl(H2_DATABASE_URL);
    tomcatJdbcDataSource.setDriverClassName("org.h2.Driver");
    tomcatJdbcDataSource.setMaxActive(123);
    final DataSource tomcatJdbcProxy = jdbcWrapper.createDataSourceProxy("test2", tomcatJdbcDataSource);
    assertNotNull("createDataSourceProxy1", tomcatJdbcProxy);
    tomcatJdbcProxy.getConnection().close();
    assertFalse("getBasicDataSourceProperties1", JdbcWrapper.getBasicDataSourceProperties().isEmpty());
    assertEquals("getMaxConnectionCount1", 123, JdbcWrapper.getMaxConnectionCount());
    final org.apache.commons.dbcp.BasicDataSource dbcpDataSource = new org.apache.commons.dbcp.BasicDataSource();
    dbcpDataSource.setUrl(H2_DATABASE_URL);
    dbcpDataSource.setMaxActive(456);
    final DataSource dbcpProxy = jdbcWrapper.createDataSourceProxy(dbcpDataSource);
    assertNotNull("createDataSourceProxy2", dbcpProxy);
    assertFalse("getBasicDataSourceProperties2", JdbcWrapper.getBasicDataSourceProperties().isEmpty());
    assertEquals("getMaxConnectionCount2", 456, JdbcWrapper.getMaxConnectionCount());
    final BasicDataSource tomcatDataSource = new BasicDataSource();
    tomcatDataSource.setUrl(H2_DATABASE_URL);
    tomcatDataSource.setMaxActive(789);
    final DataSource tomcatProxy = jdbcWrapper.createDataSourceProxy("test", tomcatDataSource);
    assertNotNull("createDataSourceProxy3", tomcatProxy);
    assertNotNull("getLogWriter2", tomcatProxy.getLogWriter());
    tomcatProxy.getConnection().close();
    assertFalse("getBasicDataSourceProperties3", JdbcWrapper.getBasicDataSourceProperties().isEmpty());
    assertEquals("getMaxConnectionCount3", 789, JdbcWrapper.getMaxConnectionCount());
    final DataSource dataSource2 = new MyDataSource(tomcatDataSource);
    jdbcWrapper.createDataSourceProxy(dataSource2);
}
Example 101
Project: mybatis-plus-master  File: GlobalConfigurationTest.java View source code
/**
     * 全局�置测试
     */
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    GlobalConfiguration global = GlobalConfiguration.defaults();
    global.setAutoSetDbType(true);
    // 设置全局校验机制为FieldStrategy.Empty
    global.setFieldStrategy(2);
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=UTF-8");
    dataSource.setUsername("root");
    dataSource.setPassword("521");
    dataSource.setMaxTotal(1000);
    GlobalConfiguration.setMetaData(dataSource, global);
    // 加载�置文件
    InputStream inputStream = GlobalConfigurationTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");
    MybatisSessionFactoryBuilder factoryBuilder = new MybatisSessionFactoryBuilder();
    factoryBuilder.setGlobalConfig(global);
    SqlSessionFactory sessionFactory = factoryBuilder.build(inputStream);
    SqlSession session = sessionFactory.openSession(false);
    TestMapper testMapper = session.getMapper(TestMapper.class);
    /*Wrapper type = Condition.instance().eq("id",1).or().in("type", new Object[]{1, 2, 3, 4, 5, 6});
        List list = testMapper.selectList(type);
        System.out.println(list.toString());*/
    Test test = new Test();
    test.setCreateTime(new Date());
    // 开�全局校验字符串会忽略空字符串
    test.setType("");
    testMapper.insert(test);
    SqlSession sqlSession = sessionFactory.openSession(false);
    NotPKMapper pkMapper = sqlSession.getMapper(NotPKMapper.class);
    NotPK notPK = new NotPK();
    notPK.setUuid(UUID.randomUUID().toString());
    int num = pkMapper.insert(notPK);
    Assert.assertTrue(num > 0);
    NotPK notPK1 = pkMapper.selectOne(notPK);
    Assert.assertNotNull(notPK1);
    pkMapper.selectPage(RowBounds.DEFAULT, Condition.create().eq("type", 12121212));
    NotPK notPK2 = null;
    try {
        notPK2 = pkMapper.selectById("1");
    } catch (Exception e) {
        System.out.println("因为没有主键,所以没有注入该方法");
    }
    Assert.assertNull(notPK2);
    int count = pkMapper.selectCount(Condition.EMPTY);
    Assert.assertTrue(count > 0);
    int deleteCount = pkMapper.delete(null);
    Assert.assertTrue(deleteCount > 0);
    session.rollback();
    sqlSession.commit();
}