org.apache.tomcat.jdbc.pool.PoolProperties Java Examples

The following examples show how to use org.apache.tomcat.jdbc.pool.PoolProperties. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PerfTestProcessEngine.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected static javax.sql.DataSource createDatasource(Properties properties) {

    PoolProperties p = new PoolProperties();
    p.setUrl(properties.getProperty("databaseUrl"));
    p.setDriverClassName(properties.getProperty("databaseDriver"));
    p.setUsername(properties.getProperty("databaseUser"));
    p.setPassword(properties.getProperty("databasePassword"));

    p.setJmxEnabled(false);

    p.setMaxActive(100);
    p.setInitialSize(10);

    DataSource datasource = new DataSource();
    datasource.setPoolProperties(p);

    return datasource;
  }
 
Example #2
Source File: Bug54978.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testIllegalValidationQuery() {
    PoolProperties poolProperties = new DefaultProperties();
    poolProperties.setMinIdle(0);
    poolProperties.setInitialSize(1);
    poolProperties.setMaxActive(1);
    poolProperties.setMaxWait(5000);
    poolProperties.setMaxAge(100);
    poolProperties.setRemoveAbandoned(false);
    poolProperties.setTestOnBorrow(true);
    poolProperties.setTestOnConnect(false);
    poolProperties.setValidationQuery("sdadsada");
    final DataSource ds = new DataSource(poolProperties);
    try {
        ds.getConnection().close();
        Assert.fail("Validation should have failed.");
    }catch (SQLException x) {
    }
}
 
Example #3
Source File: Bug54978.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testIllegalValidationQueryWithLegalInit() throws SQLException {
    PoolProperties poolProperties = new DefaultProperties();
    poolProperties.setMinIdle(0);
    poolProperties.setInitialSize(1);
    poolProperties.setMaxActive(1);
    poolProperties.setMaxWait(5000);
    poolProperties.setMaxAge(100);
    poolProperties.setRemoveAbandoned(false);
    poolProperties.setTestOnBorrow(true);
    poolProperties.setTestOnConnect(false);
    poolProperties.setValidationQuery("sdadsada");
    poolProperties.setInitSQL("SELECT 1");
    final DataSource ds = new DataSource(poolProperties);
    ds.getConnection().close();
}
 
Example #4
Source File: TomcatJdbcDataSourceFactory.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Override
public org.apache.tomcat.jdbc.pool.DataSource createDataSource(
		DataSourceInformation dataSourceInformation) {
	// create a method scoped instance
	PoolConfiguration configurationToUse = new PoolProperties();

	// copy all general properties
	BeanUtils.copyProperties(this, configurationToUse);

	configurationToUse.setDriverClassName(this.databasePlatformSupport
			.getDriverClassNameForDatabase(dataSourceInformation.getDatabaseType()));
	configurationToUse.setUrl(this.databasePlatformSupport.getDatabaseUrlForDatabase(
			dataSourceInformation.getDatabaseType(),
			dataSourceInformation.getHostName(), dataSourceInformation.getPort(),
			dataSourceInformation.getDatabaseName()));
	configurationToUse.setUsername(dataSourceInformation.getUserName());
	configurationToUse.setPassword(dataSourceInformation.getPassword());

	return new org.apache.tomcat.jdbc.pool.DataSource(configurationToUse);
}
 
Example #5
Source File: PoolPropertiesHolder.java    From das with Apache License 2.0 6 votes vote down vote up
public PoolProperties getPoolProperties(String url, String userName) {
    if (url == null || url.length() == 0) {
        return null;
    }
    if (userName == null || userName.length() == 0) {
        return null;
    }

    url = getShortString(url, SEMICOLON);
    userName = getShortString(userName, AT);
    ConcurrentHashMap<String, PoolProperties> map = poolPropertiesMap.get(url);
    if (map == null) {
        return null;
    }
    return map.get(userName);
}
 
Example #6
Source File: TestJdbcInterceptorConfigParsing.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBasic() throws Exception {
    String interceptorConfig = "FirstInterceptor;SecondInterceptor(parm1=value1,parm2=value2)";
    PoolProperties props = new PoolProperties();
    props.setJdbcInterceptors(interceptorConfig);
    InterceptorDefinition[] interceptorDefs = props.getJdbcInterceptorsAsArray();
    Assert.assertNotNull(interceptorDefs);

    // 3 items because parser automatically inserts TrapException interceptor to front of list
    Assert.assertEquals(interceptorDefs.length, 3);
    Assert.assertEquals(interceptorDefs[0].getClassName(), TrapException.class.getName());

    Assert.assertNotNull(interceptorDefs[1]);
    Assert.assertEquals(interceptorDefs[1].getClassName(), "FirstInterceptor");
    Assert.assertNotNull(interceptorDefs[2]);
    Assert.assertEquals(interceptorDefs[2].getClassName(), "SecondInterceptor");

    Map<String, InterceptorProperty> secondProps = interceptorDefs[2].getProperties();
    Assert.assertNotNull(secondProps);
    Assert.assertEquals(secondProps.size(), 2);
    Assert.assertNotNull(secondProps.get("parm1"));
    Assert.assertEquals(secondProps.get("parm1").getValue(), "value1");
    Assert.assertNotNull(secondProps.get("parm2"));
    Assert.assertEquals(secondProps.get("parm2").getValue(), "value2");
}
 
Example #7
Source File: DatabaseUtil.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private static void setIsolationLevel(PoolProperties poolProperties, String isolationLevelString) {

        if (StringUtils.isNotEmpty(isolationLevelString)) {
            if (JDBCRealmConstants.TX_ISOLATION_LEVELS.NONE.equals(isolationLevelString)) {
                poolProperties.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
            } else if (JDBCRealmConstants.TX_ISOLATION_LEVELS.READ_UNCOMMITTED.equals(isolationLevelString)) {
                poolProperties.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            } else if (JDBCRealmConstants.TX_ISOLATION_LEVELS.READ_COMMITTED.equals(isolationLevelString)) {
                poolProperties.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            } else if (JDBCRealmConstants.TX_ISOLATION_LEVELS.REPEATABLE_READ.equals(isolationLevelString)) {
                poolProperties.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            } else if (JDBCRealmConstants.TX_ISOLATION_LEVELS.SERIALIZABLE.equals(isolationLevelString)) {
                poolProperties.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
            }
        }
    }
 
Example #8
Source File: TomcatDataSourceService.java    From qmq with Apache License 2.0 6 votes vote down vote up
@Override
public DataSource makeDataSource(String url, String driverClassName, String username, String pwd) {
    PoolConfiguration p = new PoolProperties();
    p.setMinIdle(0);
    p.setMaxActive(2);
    p.setMaxIdle(0);
    p.setInitialSize(0);
    p.setMaxWait(10000);
    p.setDriverClassName(driverClassName);
    p.setUrl(url);
    p.setUsername(username);
    p.setPassword(pwd);
    p.setValidationQuery("select 1");
    p.setTestOnBorrow(true);

    org.apache.tomcat.jdbc.pool.DataSource datasource = new org.apache.tomcat.jdbc.pool.DataSource();
    datasource.setPoolProperties(p);
    return datasource;
}
 
Example #9
Source File: DataSourceValidator.java    From dal with Apache License 2.0 6 votes vote down vote up
private QueryParameter getQueryParameter(int validateAction) {
    QueryParameter parameter = null;
    if (validateAction != PooledConnection.VALIDATE_INIT)
        return parameter;

    PoolProperties poolProperties = getPoolProperties();
    if (poolProperties == null)
        return parameter;

    String query = poolProperties.getInitSQL();
    int validationQueryTimeout = poolProperties.getValidationQueryTimeout();
    if (validationQueryTimeout <= 0) {
        validationQueryTimeout = DEFAULT_VALIDATE_TIMEOUT_IN_SECONDS;
    }

    parameter = new QueryParameter();
    parameter.setQuery(query);
    parameter.setValidationQueryTimeout(validationQueryTimeout);
    return parameter;
}
 
Example #10
Source File: DataSourceUtil.java    From dal with Apache License 2.0 5 votes vote down vote up
private static DataSource createDataSource(String url, String userName, String password, String driverClass)
        throws Exception {
    PoolProperties p = new PoolProperties();

    p.setUrl(url);
    p.setUsername(userName);
    p.setPassword(password);
    p.setDriverClassName(driverClass);
    p.setJmxEnabled(false);
    p.setTestWhileIdle(false);
    p.setTestOnBorrow(true);
    p.setTestOnReturn(false);
    p.setValidationQuery("SELECT 1");
    p.setValidationQueryTimeout(5);
    p.setValidationInterval(30000L);
    p.setTimeBetweenEvictionRunsMillis(5000);
    p.setMaxActive(100);
    p.setMinIdle(0);
    p.setMaxWait(10000);
    p.setMaxAge(0L);
    p.setInitialSize(1);
    p.setRemoveAbandonedTimeout(60);
    p.setRemoveAbandoned(true);
    p.setLogAbandoned(true);
    p.setMinEvictableIdleTimeMillis(30000);
    p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
            + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");

    org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource(p);
    ds.createPool();
    return ds;
}
 
Example #11
Source File: SimplePOJOExample.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    PoolConfiguration p = new PoolProperties();
    p.setUrl("jdbc:mysql://localhost:3306/mysql?autoReconnect=true");
    p.setDriverClassName("com.mysql.jdbc.Driver");
    p.setUsername("root");
    p.setPassword("password");
    p.setJmxEnabled(true);
    p.setTestWhileIdle(false);
    p.setTestOnBorrow(true);
    p.setValidationQuery("SELECT 1");
    p.setTestOnReturn(false);
    p.setValidationInterval(30000);
    p.setTimeBetweenEvictionRunsMillis(30000);
    p.setMaxActive(100);
    p.setInitialSize(10);
    p.setMaxWait(10000);
    p.setRemoveAbandonedTimeout(60);
    p.setMinEvictableIdleTimeMillis(30000);
    p.setMinIdle(10);
    p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
    p.setLogAbandoned(true);
    p.setRemoveAbandoned(true);
    DataSource datasource = new DataSource();
    datasource.setPoolProperties(p);

    Connection con = null;
    try {
      con = datasource.getConnection();
      Statement st = con.createStatement();
      ResultSet rs = st.executeQuery("select * from user");
      int cnt = 1;
      while (rs.next()) {
          System.out.println((cnt++)+". Host:" +rs.getString("Host")+" User:"+rs.getString("User")+" Password:"+rs.getString("Password"));
      }
      rs.close();
      st.close();
    } finally {
      if (con!=null) try {con.close();}catch (Exception ignore) {}
    }
}
 
Example #12
Source File: SingleDataSource.java    From dal with Apache License 2.0 5 votes vote down vote up
private void setPoolPropertiesIntoValidator(PoolProperties poolProperties) {
    if (poolProperties == null)
        return;

    Validator validator = poolProperties.getValidator();
    if (validator == null)
        return;

    if (!(validator instanceof ValidatorProxy))
        return;

    ValidatorProxy dsValidator = (ValidatorProxy) validator;
    dsValidator.setPoolProperties(poolProperties);
}
 
Example #13
Source File: SingleDataSource.java    From dal with Apache License 2.0 5 votes vote down vote up
private void createDataSource(String name, DataSourceConfigure dataSourceConfigure) {
    try {
        PoolProperties poolProperties = poolPropertiesHelper.convert(dataSourceConfigure);
        setPoolPropertiesIntoValidator(poolProperties);

        final org.apache.tomcat.jdbc.pool.DataSource dataSource = new DalTomcatDataSource(poolProperties);
        this.dataSource = dataSource;
    } catch (Throwable e) {
        LOGGER.error(String.format("Error creating datasource for %s", name), e);
    }
}
 
Example #14
Source File: DatabasePoolConfigParser.java    From dal with Apache License 2.0 5 votes vote down vote up
public DatabasePoolConfig getDatabasePoolConfig(String name) {
    DataSourceConfigure configure = DataSourceConfigureLocatorManager.getInstance().getDataSourceConfigure(name);
    PoolProperties poolProperties = new PoolProperties();

    poolProperties.setTestWhileIdle(configure.getBooleanProperty(TESTWHILEIDLE, DEFAULT_TESTWHILEIDLE));
    poolProperties.setTestOnBorrow(configure.getBooleanProperty(TESTONBORROW, DEFAULT_TESTONBORROW));
    poolProperties.setTestOnReturn(configure.getBooleanProperty(TESTONRETURN, DEFAULT_TESTONRETURN));

    poolProperties.setValidationQuery(configure.getProperty(VALIDATIONQUERY, DEFAULT_VALIDATIONQUERY));
    poolProperties.setValidationQueryTimeout(
            configure.getIntProperty(VALIDATIONQUERYTIMEOUT, DEFAULT_VALIDATIONQUERYTIMEOUT));
    poolProperties.setValidationInterval(configure.getLongProperty(VALIDATIONINTERVAL, DEFAULT_VALIDATIONINTERVAL));

    poolProperties.setTimeBetweenEvictionRunsMillis(
            configure.getIntProperty(TIMEBETWEENEVICTIONRUNSMILLIS, DEFAULT_TIMEBETWEENEVICTIONRUNSMILLIS));
    poolProperties.setMinEvictableIdleTimeMillis(DEFAULT_MINEVICTABLEIDLETIMEMILLIS);

    poolProperties.setMaxAge(configure.getIntProperty(MAX_AGE, DEFAULT_MAXAGE));
    poolProperties.setMaxActive(configure.getIntProperty(MAXACTIVE, DEFAULT_MAXACTIVE));
    poolProperties.setMinIdle(configure.getIntProperty(MINIDLE, DEFAULT_MINIDLE));
    poolProperties.setMaxWait(configure.getIntProperty(MAXWAIT, DEFAULT_MAXWAIT));
    poolProperties.setInitialSize(configure.getIntProperty(INITIALSIZE, DEFAULT_INITIALSIZE));

    poolProperties.setRemoveAbandonedTimeout(
            configure.getIntProperty(REMOVEABANDONEDTIMEOUT, DEFAULT_REMOVEABANDONEDTIMEOUT));
    poolProperties.setRemoveAbandoned(configure.getBooleanProperty(REMOVEABANDONED, DEFAULT_REMOVEABANDONED));
    poolProperties.setLogAbandoned(configure.getBooleanProperty(LOGABANDONED, DEFAULT_LOGABANDONED));

    poolProperties
            .setConnectionProperties(configure.getProperty(CONNECTIONPROPERTIES, DEFAULT_CONNECTIONPROPERTIES));
    poolProperties.setValidatorClassName(configure.getProperty(VALIDATORCLASSNAME, DEFAULT_VALIDATORCLASSNAME));

    poolProperties.setJmxEnabled(DEFAULT_JMXENABLED);
    poolProperties.setJdbcInterceptors(configure.getProperty(JDBC_INTERCEPTORS, DEFAULT_JDBCINTERCEPTORS));

    return new DatabasePoolConfig(poolProperties);
}
 
Example #15
Source File: PooledConnectionTomcat.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static PoolProperties getPoolProperties() {
  Endpoint locatorEndPoint = (Endpoint) (NetworkServerHelper.getNetworkLocatorEndpoints()).get(0);
  String hostname = getHostNameFromEndpoint(locatorEndPoint);
  int port = getPortFromEndpoint(locatorEndPoint); 
  
  connProp.putAll(getExtraConnProp());
  
  PoolProperties p = new PoolProperties();
 
  StringBuilder sb = new StringBuilder();
  
  for (Iterator iter = connProp.entrySet().iterator(); iter.hasNext(); ) {
    Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
    
    sb.append(entry.getKey() + "=" + entry.getValue() +";");
  }
  int lastIndex = sb.lastIndexOf(";");
  if (lastIndex != -1) sb.deleteCharAt(lastIndex);
  
  p.setConnectionProperties(sb.toString());
  
  Log.getLogWriter().info("Tomcat data source setting the following connection prop: " + sb.toString());
   
  p.setUrl(protocol + hostname+ ":" + port);
  p.setDriverClassName(driver);
  return p;
}
 
Example #16
Source File: PoolStatsInterceptor.java    From metacat with Apache License 2.0 5 votes vote down vote up
@Override
public void setProperties(final Map<String, PoolProperties.InterceptorProperty> properties) {
    super.setProperties(properties);
    final PoolProperties.InterceptorProperty nameProperty = properties.get(PROP_METRIC_NAME);
    if (nameProperty != null) {
        setMetricName(nameProperty.getValue());
    }
}
 
Example #17
Source File: Bug54225.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testPool() throws SQLException {
    PoolProperties poolProperties = new DefaultProperties();
    poolProperties.setMinIdle(0);
    poolProperties.setInitialSize(0);
    poolProperties.setMaxWait(5000);
    poolProperties.setRemoveAbandoned(true);
    poolProperties.setRemoveAbandonedTimeout(300);
    poolProperties.setRollbackOnReturn(true);
    poolProperties.setInitSQL(initSQL);
    final DataSource ds = new DataSource(poolProperties);
    ds.getConnection().close();
    Assert.assertNull(poolProperties.getInitSQL());
}
 
Example #18
Source File: SimplePOJOExample.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    PoolConfiguration p = new PoolProperties();
    p.setUrl("jdbc:mysql://localhost:3306/mysql?autoReconnect=true");
    p.setDriverClassName("com.mysql.jdbc.Driver");
    p.setUsername("root");
    p.setPassword("password");
    p.setJmxEnabled(true);
    p.setTestWhileIdle(false);
    p.setTestOnBorrow(true);
    p.setValidationQuery("SELECT 1");
    p.setTestOnReturn(false);
    p.setValidationInterval(30000);
    p.setTimeBetweenEvictionRunsMillis(30000);
    p.setMaxActive(100);
    p.setInitialSize(10);
    p.setMaxWait(10000);
    p.setRemoveAbandonedTimeout(60);
    p.setMinEvictableIdleTimeMillis(30000);
    p.setMinIdle(10);
    p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
    p.setLogAbandoned(true);
    p.setRemoveAbandoned(true);
    DataSource datasource = new DataSource();
    datasource.setPoolProperties(p);

    Connection con = null;
    try {
      con = datasource.getConnection();
      Statement st = con.createStatement();
      ResultSet rs = st.executeQuery("select * from user");
      int cnt = 1;
      while (rs.next()) {
          System.out.println((cnt++)+". Host:" +rs.getString("Host")+" User:"+rs.getString("User")+" Password:"+rs.getString("Password"));
      }
      rs.close();
      st.close();
    } finally {
      if (con!=null) try {con.close();}catch (Exception ignore) {}
    }
}
 
Example #19
Source File: BaseDeviceManagementCertificateTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private DataSource getDataSource(DataSourceConfig config) {
    PoolProperties properties = new PoolProperties();
    properties.setUrl(config.getUrl());
    properties.setDriverClassName(config.getDriverClassName());
    properties.setUsername(config.getUser());
    properties.setPassword(config.getPassword());
    return new org.apache.tomcat.jdbc.pool.DataSource(properties);
}
 
Example #20
Source File: BaseDeviceManagementTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
protected DataSource getDataSource(DataSourceConfig config) {
    if (!isMock()) {
        PoolProperties properties = new PoolProperties();
        properties.setUrl(config.getUrl());
        properties.setDriverClassName(config.getDriverClassName());
        properties.setUsername(config.getUser());
        properties.setPassword(config.getPassword());
        return new org.apache.tomcat.jdbc.pool.DataSource(properties);
    } else {
        return new MockDataSource(config.getUrl());
    }
}
 
Example #21
Source File: BasePolicyManagementDAOTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private DataSource getDataSource(DataSourceConfig config) {
    PoolProperties properties = new PoolProperties();
    properties.setUrl(config.getUrl());
    properties.setDriverClassName(config.getDriverClassName());
    properties.setUsername(config.getUser());
    properties.setPassword(config.getPassword());
    return new org.apache.tomcat.jdbc.pool.DataSource(properties);
}
 
Example #22
Source File: PooledConnectionTomcat.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static PoolProperties getPoolProperties() {
  Endpoint locatorEndPoint = (Endpoint) (NetworkServerHelper.getNetworkLocatorEndpoints()).get(0);
  String hostname = getHostNameFromEndpoint(locatorEndPoint);
  int port = getPortFromEndpoint(locatorEndPoint); 
  
  connProp.putAll(getExtraConnProp());
  
  PoolProperties p = new PoolProperties();
 
  StringBuilder sb = new StringBuilder();
  
  for (Iterator iter = connProp.entrySet().iterator(); iter.hasNext(); ) {
    Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
    
    sb.append(entry.getKey() + "=" + entry.getValue() +";");
  }
  int lastIndex = sb.lastIndexOf(";");
  if (lastIndex != -1) sb.deleteCharAt(lastIndex);
  
  p.setConnectionProperties(sb.toString());
  
  Log.getLogWriter().info("Tomcat data source setting the following connection prop: " + sb.toString());
   
  p.setUrl(protocol + hostname+ ":" + port);
  p.setDriverClassName(driver);
  return p;
}
 
Example #23
Source File: JDBCDriverWithPoolTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private static DataSource getTomcatDataSourceWithDriverClassName() {
    PoolProperties poolProperties = new PoolProperties();
    poolProperties.setUrl(URL + ";TEST=TOMCAT_WITH_CLASSNAME"); // append a dummy URL element to ensure different DB per test
    poolProperties.setValidationQuery("SELECT 1");
    poolProperties.setMinIdle(3);
    poolProperties.setMaxActive(10);
    poolProperties.setDriverClassName(ContainerDatabaseDriver.class.getName());

    return new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
}
 
Example #24
Source File: JDBCDriverWithPoolTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private static DataSource getTomcatDataSource() {
    PoolProperties poolProperties = new PoolProperties();
    poolProperties.setUrl(URL + ";TEST=TOMCAT"); // append a dummy URL element to ensure different DB per test
    poolProperties.setValidationQuery("SELECT 1");
    poolProperties.setInitialSize(3);
    poolProperties.setMaxActive(10);

    return new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
}
 
Example #25
Source File: MockedTomcatJdbcConnection.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a mocked SQL connection, that looks like a tomcat-jdbc pooled connection.
 * @param username the username to use
 * @param password the password to use
 * @return the connection
 * @throws SQLException
 */
public static Connection create(String username, String password) throws SQLException {
    PoolProperties poolProps = new PoolProperties();
    poolProps.setUsername(username);
    poolProps.setPassword(password);
    poolProps.setDataSource(new MockDataSource());
    ConnectionPool pool = new ConnectionPool(poolProps);
    PooledConnection pooledConnection = new PooledConnection(poolProps, pool);
    pooledConnection.connect();
    ProxyConnection proxyConnection = new ProxyConnection(null, pooledConnection, true) {};
    DisposableConnectionFacade invocationHandler = new DisposableConnectionFacade(proxyConnection) {};
    Connection connection = (Connection) Proxy.newProxyInstance(DisposableConnectionFacade.class.getClassLoader(), new Class[] {Connection.class}, invocationHandler);
    return connection;
}
 
Example #26
Source File: LocalXADataSource.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
private void createConnectionPool() throws SQLException {
	PoolProperties props = new PoolProperties();
    props.setUrl(this.getUrl());
    props.setUsername(this.getUsername());
    props.setPassword(this.getPassword());
    props.setDriverClassName(this.getDriverClassName());
    props.setValidationQuery(this.getValidationQuery());
    this.connectionPool = new ConnectionPool(props);
}
 
Example #27
Source File: SQLService.java    From odo with Apache License 2.0 5 votes vote down vote up
/**
 * Obtain instance of the SQL Service
 *
 * @return instance of SQLService
 * @throws Exception exception
 */
public static SQLService getInstance() throws Exception {
    if (_instance == null) {
        _instance = new SQLService();
        _instance.startServer();

        // default pool size is 20
        // can be overriden by env variable
        int dbPool = 20;
        if (Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE) != null) {
            dbPool = Integer.valueOf(Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE));
        }

        // initialize connection pool
        PoolProperties p = new PoolProperties();
        String connectString = "jdbc:h2:tcp://" + _instance.databaseHost + ":" + _instance.port + "/./" +
            _instance.databaseName + "/proxydb;MULTI_THREADED=true;AUTO_RECONNECT=TRUE;AUTOCOMMIT=ON";
        p.setUrl(connectString);
        p.setDriverClassName("org.h2.Driver");
        p.setUsername("sa");
        p.setJmxEnabled(true);
        p.setTestWhileIdle(false);
        p.setTestOnBorrow(true);
        p.setValidationQuery("SELECT 1");
        p.setTestOnReturn(false);
        p.setValidationInterval(5000);
        p.setTimeBetweenEvictionRunsMillis(30000);
        p.setMaxActive(dbPool);
        p.setInitialSize(5);
        p.setMaxWait(30000);
        p.setRemoveAbandonedTimeout(60);
        p.setMinEvictableIdleTimeMillis(30000);
        p.setMinIdle(10);
        p.setLogAbandoned(true);
        p.setRemoveAbandoned(true);
        _instance.datasource = new DataSource();
        _instance.datasource.setPoolProperties(p);
    }
    return _instance;
}
 
Example #28
Source File: PoolPropertiesHolder.java    From das with Apache License 2.0 5 votes vote down vote up
public void setPoolProperties(PoolProperties poolProperties) {
    if (poolProperties == null) {
        return;
    }

    String url = poolProperties.getUrl();
    if (url == null || url.length() == 0) {
        return;
    }

    String userName = poolProperties.getUsername();
    if (userName == null || userName.length() == 0) {
        return;
    }

    url = getShortString(url, SEMICOLON);
    userName = getShortString(userName, AT);
    ConcurrentHashMap<String, PoolProperties> map = poolPropertiesMap.get(url);

    if (map == null) {
        synchronized (LOCK) {
            map = poolPropertiesMap.get(url);
            if (map == null) {
                map = new ConcurrentHashMap<>();
                poolPropertiesMap.put(url, map);
            }
        }
    }

    /*
     * if (!map.containsKey(userName)) { synchronized (LOCK2) { if (!map.containsKey(userName)) { map.put(userName,
     * poolProperties); } } }
     */

    // avoid caching for InitSQL
    synchronized (LOCK2) {
        map.put(userName, poolProperties);
    }
}
 
Example #29
Source File: StatementFinalizer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void setProperties(Map<String, PoolProperties.InterceptorProperty> properties) {
    super.setProperties(properties);

    PoolProperties.InterceptorProperty logProperty = properties.get("trace");
    if (null != logProperty) {
        logCreationStack = logProperty.getValueAsBoolean(logCreationStack);
    }
}
 
Example #30
Source File: Bug54227.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testPool() throws SQLException, InterruptedException {
    PoolProperties poolProperties = new DefaultProperties();
    poolProperties.setMinIdle(0);
    poolProperties.setInitialSize(0);
    poolProperties.setMaxActive(1);
    poolProperties.setMaxWait(5000);
    poolProperties.setMaxAge(100);
    poolProperties.setRemoveAbandoned(false);

    final DataSource ds = new DataSource(poolProperties);
    Connection con;
    Connection actual1;
    Connection actual2;

    con = ds.getConnection();
    actual1 = ((PooledConnection)con).getConnection();
    con.close();
    con = ds.getConnection();
    actual2 = ((PooledConnection)con).getConnection();
    Assert.assertSame(actual1, actual2);
    con.close();
    Thread.sleep(150);
    con = ds.getConnection();
    actual2 = ((PooledConnection)con).getConnection();
    Assert.assertNotSame(actual1, actual2);
    con.close();
}