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

The following examples show how to use org.apache.tomcat.jdbc.pool.DataSource. 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: TestSizePreservation.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void initSimplePoolProperties() {
    PoolConfiguration p = new DefaultProperties();
    ds = new org.apache.tomcat.jdbc.pool.DataSource();
    ds.setPoolProperties(p);

    ds.getPoolProperties().setDriverClassName(Driver.class.getName());
    ds.getPoolProperties().setUrl(Driver.url);
    ds.getPoolProperties().setFairQueue(true);
    ds.getPoolProperties().setJmxEnabled(false);
    ds.getPoolProperties().setTestWhileIdle(true);
    ds.getPoolProperties().setTestOnBorrow(false);
    ds.getPoolProperties().setTestOnReturn(false);
    ds.getPoolProperties().setValidationInterval(30000);
    ds.getPoolProperties().setTimeBetweenEvictionRunsMillis(30000);
    ds.getPoolProperties().setInitialSize(100);
    ds.getPoolProperties().setMaxActive(100);
    ds.getPoolProperties().setMinIdle(0);
    ds.getPoolProperties().setMaxIdle(0);
    ds.getPoolProperties().setMaxWait(10000);
    ds.getPoolProperties().setRemoveAbandonedTimeout(10);
    ds.getPoolProperties().setMinEvictableIdleTimeMillis(10000);
    ds.getPoolProperties().setLogAbandoned(false);
    ds.getPoolProperties().setRemoveAbandoned(false);
    ds.getPoolProperties().setUseLock(true);
}
 
Example #2
Source File: TestSizePreservation.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void initSimplePoolProperties() {
    PoolConfiguration p = new DefaultProperties();
    ds = new org.apache.tomcat.jdbc.pool.DataSource();
    ds.setPoolProperties(p);

    ds.getPoolProperties().setDriverClassName(Driver.class.getName());
    ds.getPoolProperties().setUrl(Driver.url);
    ds.getPoolProperties().setFairQueue(true);
    ds.getPoolProperties().setJmxEnabled(false);
    ds.getPoolProperties().setTestWhileIdle(true);
    ds.getPoolProperties().setTestOnBorrow(false);
    ds.getPoolProperties().setTestOnReturn(false);
    ds.getPoolProperties().setValidationInterval(30000);
    ds.getPoolProperties().setTimeBetweenEvictionRunsMillis(30000);
    ds.getPoolProperties().setInitialSize(100);
    ds.getPoolProperties().setMaxActive(100);
    ds.getPoolProperties().setMinIdle(0);
    ds.getPoolProperties().setMaxIdle(0);
    ds.getPoolProperties().setMaxWait(10000);
    ds.getPoolProperties().setRemoveAbandonedTimeout(10);
    ds.getPoolProperties().setMinEvictableIdleTimeMillis(10000);
    ds.getPoolProperties().setLogAbandoned(false);
    ds.getPoolProperties().setRemoveAbandoned(false);
    ds.getPoolProperties().setUseLock(true);
}
 
Example #3
Source File: JDBCPoolSQLConfig.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Override
public DataSource getDataSource() throws DataServiceFault {
	if (this.dataSource == null) {
	    synchronized (this) {
	    	/* this second check is necessary, in case another thread already initialized it */
		    if (this.dataSource == null) {
		        try {
			        RDBMSDataSource rdbmsDS = new RDBMSDataSource(
					        this.createConfigFromProps(this.getProperties()));
			        this.dataSource = rdbmsDS.getDataSource();
		        } catch (Exception e) {
			        throw new DataServiceFault(e,
                                                  "Error creating JDBC Pool SQL Config: "	+ e.getMessage());
		        }
		    }
	    }
	}
	return dataSource;
}
 
Example #4
Source File: Utils.java    From radman with MIT License 6 votes vote down vote up
static LocalContainerEntityManagerFactoryBean buildEntityManager(DataSource dataSource,
                                                                 JpaProperties jpaProperties,
                                                                 String entitiesPackage,
                                                                 String persistenceUnitName) {
    LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
    entityManager.setDataSource(dataSource);
    entityManager.setPackagesToScan(entitiesPackage);
    entityManager.setPersistenceUnitName(persistenceUnitName);
    entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

    HashMap<String, Object> properties = new HashMap<>();
    properties.put("hibernate.hbm2ddl.auto", jpaProperties.getHibernate().getDdlAuto());
    properties.put("hibernate.dialect", jpaProperties.getHibernate().getDialect());
    properties.put("show-sql", jpaProperties.getShowSql());

    entityManager.setJpaPropertyMap(properties);
    return entityManager;
}
 
Example #5
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 #6
Source File: PoolCleanerTest.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void test2PoolCleaners() throws Exception {
    datasource.getPoolProperties().setTimeBetweenEvictionRunsMillis(2000);
    datasource.getPoolProperties().setTestWhileIdle(true);

    DataSource ds2 = new DataSource(datasource.getPoolProperties());

    Assert.assertEquals("Pool cleaner should not be started yet.",0,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNull("Pool timer should be null", ConnectionPool.getPoolTimer());
    Assert.assertEquals("Pool cleaner threads should not be present.",0, countPoolCleanerThreads());

    datasource.getConnection().close();
    ds2.getConnection().close();
    Assert.assertEquals("Pool cleaner should have 2 cleaner.",2,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNotNull("Pool timer should not be null", ConnectionPool.getPoolTimer());
    Assert.assertEquals("Pool cleaner threads should be 1.",1, countPoolCleanerThreads());

    datasource.close();
    Assert.assertEquals("Pool cleaner should have 1 cleaner.",1,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNotNull("Pool timer should not be null", ConnectionPool.getPoolTimer());

    ds2.close();
    Assert.assertEquals("Pool shutdown, no cleaners should be present.",0,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNull("Pool timer should be null after shutdown", ConnectionPool.getPoolTimer());
    Assert.assertEquals("Pool cleaner threads should not be present after close.",0, countPoolCleanerThreads());
}
 
Example #7
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 #8
Source File: PoolCleanerTest.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void test2PoolCleaners() throws Exception {
    datasource.getPoolProperties().setTimeBetweenEvictionRunsMillis(2000);
    datasource.getPoolProperties().setTestWhileIdle(true);

    DataSource ds2 = new DataSource(datasource.getPoolProperties());

    Assert.assertEquals("Pool cleaner should not be started yet.",0,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNull("Pool timer should be null", ConnectionPool.getPoolTimer());
    Assert.assertEquals("Pool cleaner threads should not be present.",0, countPoolCleanerThreads());

    datasource.getConnection().close();
    ds2.getConnection().close();
    Assert.assertEquals("Pool cleaner should have 2 cleaner.",2,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNotNull("Pool timer should not be null", ConnectionPool.getPoolTimer());
    Assert.assertEquals("Pool cleaner threads should be 1.",1, countPoolCleanerThreads());

    datasource.close();
    Assert.assertEquals("Pool cleaner should have 1 cleaner.",1,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNotNull("Pool timer should not be null", ConnectionPool.getPoolTimer());

    ds2.close();
    Assert.assertEquals("Pool shutdown, no cleaners should be present.",0,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNull("Pool timer should be null after shutdown", ConnectionPool.getPoolTimer());
    Assert.assertEquals("Pool cleaner threads should not be present after close.",0, countPoolCleanerThreads());
}
 
Example #9
Source File: PooledConnectionTomcat.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private static void setupDataSource(Isolation isolation) {
  ds = new DataSource();

  try {    
    ds.setPoolProperties(getPoolProperties()); //set earlier to avoid overriding the isolation setting
    
    ds.setMaxActive(100);
    
    if (isolation == Isolation.NONE) {
      ds.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
    } else if (isolation == Isolation.READ_COMMITTED) {
      ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
      ds.setDefaultAutoCommit(false);
    } else {
      ds.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
      ds.setDefaultAutoCommit(false);
    }
    
    dsSet = true;
    Log.getLogWriter().info("tomcat data source url is set as " + ds.getUrl());
    Log.getLogWriter().info("tomcat data source DefaultTransactionIsolation is set to " + ds.getDefaultTransactionIsolation());
    Log.getLogWriter().info("tomcat data source DefaultAutoCommit is set to " + ds.getDefaultAutoCommit());
  } catch (Exception e) {
    throw new TestException("could not set data source" + TestHelper.getStackTrace(e));
  }
}
 
Example #10
Source File: PoolCleanerTest.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void test2PoolCleaners() throws Exception {
    datasource.getPoolProperties().setTimeBetweenEvictionRunsMillis(2000);
    datasource.getPoolProperties().setTestWhileIdle(true);

    DataSource ds2 = new DataSource(datasource.getPoolProperties());

    Assert.assertEquals("Pool cleaner should not be started yet.",0,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNull("Pool timer should be null", ConnectionPool.getPoolTimer());
    Assert.assertEquals("Pool cleaner threads should not be present.",0, countPoolCleanerThreads());

    datasource.getConnection().close();
    ds2.getConnection().close();
    Assert.assertEquals("Pool cleaner should have 2 cleaner.",2,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNotNull("Pool timer should not be null", ConnectionPool.getPoolTimer());
    Assert.assertEquals("Pool cleaner threads should be 1.",1, countPoolCleanerThreads());

    datasource.close();
    Assert.assertEquals("Pool cleaner should have 1 cleaner.",1,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNotNull("Pool timer should not be null", ConnectionPool.getPoolTimer());

    ds2.close();
    Assert.assertEquals("Pool shutdown, no cleaners should be present.",0,ConnectionPool.getPoolCleaners().size() );
    Assert.assertNull("Pool timer should be null after shutdown", ConnectionPool.getPoolTimer());
    Assert.assertEquals("Pool cleaner threads should not be present after close.",0, countPoolCleanerThreads());
}
 
Example #11
Source File: TestSizePreservation.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void initSimplePoolProperties() {
    PoolConfiguration p = new DefaultProperties();
    ds = new org.apache.tomcat.jdbc.pool.DataSource();
    ds.setPoolProperties(p);

    ds.getPoolProperties().setDriverClassName(Driver.class.getName());
    ds.getPoolProperties().setUrl(Driver.url);
    ds.getPoolProperties().setFairQueue(true);
    ds.getPoolProperties().setJmxEnabled(false);
    ds.getPoolProperties().setTestWhileIdle(true);
    ds.getPoolProperties().setTestOnBorrow(false);
    ds.getPoolProperties().setTestOnReturn(false);
    ds.getPoolProperties().setValidationInterval(30000);
    ds.getPoolProperties().setTimeBetweenEvictionRunsMillis(30000);
    ds.getPoolProperties().setInitialSize(100);
    ds.getPoolProperties().setMaxActive(100);
    ds.getPoolProperties().setMinIdle(0);
    ds.getPoolProperties().setMaxIdle(0);
    ds.getPoolProperties().setMaxWait(10000);
    ds.getPoolProperties().setRemoveAbandonedTimeout(10);
    ds.getPoolProperties().setMinEvictableIdleTimeMillis(10000);
    ds.getPoolProperties().setLogAbandoned(false);
    ds.getPoolProperties().setRemoveAbandoned(false);
    ds.getPoolProperties().setUseLock(true);
}
 
Example #12
Source File: PooledConnectionTomcat.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private static void setupDataSource(Isolation isolation) {
  ds = new DataSource();

  try {    
    ds.setPoolProperties(getPoolProperties()); //set earlier to avoid overriding the isolation setting
    
    ds.setMaxActive(100);
    
    if (isolation == Isolation.NONE) {
      ds.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
    } else if (isolation == Isolation.READ_COMMITTED) {
      ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
      ds.setDefaultAutoCommit(false);
    } else {
      ds.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
      ds.setDefaultAutoCommit(false);
    }
    
    dsSet = true;
    Log.getLogWriter().info("tomcat data source url is set as " + ds.getUrl());
    Log.getLogWriter().info("tomcat data source DefaultTransactionIsolation is set to " + ds.getDefaultTransactionIsolation());
    Log.getLogWriter().info("tomcat data source DefaultAutoCommit is set to " + ds.getDefaultAutoCommit());
  } catch (Exception e) {
    throw new TestException("could not set data source" + TestHelper.getStackTrace(e));
  }
}
 
Example #13
Source File: TomcatJdbcDataSourceFactoryTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void testCloseDataSource() throws Exception {
	TomcatJdbcDataSourceFactory tomcatJdbcDataSourceFactory = new TomcatJdbcDataSourceFactory();
	tomcatJdbcDataSourceFactory.setInitialSize(0);

	DataSourceInformation dataSourceInformation = new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "user", "password");
	DataSource dataSource = tomcatJdbcDataSourceFactory
			.createDataSource(dataSourceInformation);
	assertThat(dataSource).isNotNull();

	ConnectionPool pool = dataSource.createPool();
	assertThat(pool.isClosed()).isFalse();
	tomcatJdbcDataSourceFactory.closeDataSource(dataSource);
	assertThat(pool.isClosed()).isTrue();
}
 
Example #14
Source File: SqlResponseCacheLoader.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * This method gets the dimension filters for the given dataset from the presto data source,
 * and returns them as map of dimension name to values
 * @param dataset
 * @return dimension filters map
 */
public Map<String, List<String>> getDimensionFilters(String dataset) throws Exception {
  LOG.info("Getting dimension filters for " + dataset);
  DatasetConfigDTO datasetConfig = ThirdEyeUtils.getDatasetConfigFromName(dataset);

  String sourceName = dataset.split("\\.")[0];
  String tableName = SqlUtils.computeSqlTableName(dataset);
  DataSource dataSource = getDataSourceFromDataset(dataset);

  Map<String, List<String>> dimensionFilters = new HashMap<>();

  for (String dimension: datasetConfig.getDimensions()) {
    dimensionFilters.put(dimension, new ArrayList<>());
    try (Connection conn = dataSource.getConnection();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(SqlUtils.getDimensionFiltersSQL(dimension, tableName, sourceName));) {
      while (rs.next()) {
        dimensionFilters.get(dimension).add(rs.getString(1));
      }
    }
    catch (Exception e) {
        throw e;
    }
  }
  return dimensionFilters;
}
 
Example #15
Source File: SqlResponseCacheLoader.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method that return a DataSource object corresponding to the dataset
 *
 * @param dataset name of dataset
 * @return DataSource object: datasource for the dataset
 */
private DataSource getDataSourceFromDataset(String dataset) {
  String[] tableComponents = dataset.split("\\.");
  String sourceName = tableComponents[0];
  String dbName = tableComponents[1];

  if (sourceName.equals(PRESTO)) {
    return prestoDBNameToDataSourceMap.get(dbName);
  } else if (sourceName.equals(MYSQL)) {
    return mysqlDBNameToDataSourceMap.get(dbName);
  } else if (sourceName.equals(VERTICA)) {
    return verticaDBNameToDataSourceMap.get(dbName);
  } else {
    return h2DataSource;
  }
}
 
Example #16
Source File: SqlUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Insert a table to SQL database, currently only used by H2, that can be read by ThirdEye
 *
 * @param ds DataSource object
 * @param tableName table name
 * @param timeColumn time column name
 * @param metrics list of metrics
 * @param dimensions list of dimensions
 * @throws SQLException SQL exception if SQL failed
 */
public static void createTableOverride(DataSource ds, String tableName,
    String timeColumn, List<String> metrics, List<String> dimensions) throws SQLException {
  StringBuilder sb = new StringBuilder();
  sb.append("drop table if exists ").append(tableName).append(";");
  sb.append("create table ").append(tableName).append(" (");

  for (String metric: metrics) {
    sb.append(metric).append(" decimal(50,3), ");
  }
  for (String dimension: dimensions) {
    sb.append(dimension).append(" varchar(50), ");
  }
  sb.append(timeColumn).append(" varchar(50) ) ENGINE=InnoDB;");

  String sql = sb.toString();

  LOG.info("Creating H2 table: " + sql);

  try (Connection connection = ds.getConnection();
      Statement statement = connection.createStatement()){
    statement.execute(sql);
  }
}
 
Example #17
Source File: SqlUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Run SQL query to insert a row in a CSV file to a datasource, for now only used by H2 initialization
 *
 * @param tableName table name
 * @param columnNames column names in CSV, separated by ,
 * @param items row items
 * @throws SQLException
 */
public static void insertCSVRow(DataSource ds, String tableName, String columnNames, String[] items) throws SQLException {
  // Put quotes around values that contains spaces
  StringBuilder sb = new StringBuilder();
  String prefix = "";
  for (String item: items) {
    sb.append(prefix);
    prefix = ",";
    if (!StringUtils.isNumeric(item)) {
      sb.append('\'').append(item).append('\'');
    } else {
      sb.append(item);
    }
  }

  String sql = String.format("INSERT INTO %s(%s) VALUES(%s)", tableName, columnNames, sb.toString());
  try (Connection connection = ds.getConnection();
      Statement statement = connection.createStatement()){
    statement.execute(sql);
  }
}
 
Example #18
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 #19
Source File: DatabaseService.java    From easy-sync with Apache License 2.0 5 votes vote down vote up
protected DataSource createDataSource(Mysql mysql) {

        DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(mysql.getUrl());
        dataSource.setUsername(mysql.getUser());
        dataSource.setPassword(mysql.getPassword());
        dataSource.setValidationQuery("select 1");
        dataSource.setTestWhileIdle(true);
        dataSource.setTimeBetweenEvictionRunsMillis(30*1000);
        return dataSource;
    }
 
Example #20
Source File: SqlResponseCacheLoader.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the max time in millis for dataset in presto
 * @param dataset
 * @return max date time in millis
 */
public long getMaxDataTime(String dataset) throws Exception {
  LOG.info("Getting max data time for " + dataset);
  DatasetConfigDTO datasetConfig = ThirdEyeUtils.getDatasetConfigFromName(dataset);
  TimeSpec timeSpec = ThirdEyeUtils.getTimestampTimeSpecFromDatasetConfig(datasetConfig);
  DateTimeZone timeZone = Utils.getDataTimeZone(dataset);
  long maxTime = 0;

  String sourceName = dataset.split("\\.")[0];
  String tableName = SqlUtils.computeSqlTableName(dataset);
  DataSource dataSource = getDataSourceFromDataset(dataset);

  try (Connection conn = dataSource.getConnection();
      Statement stmt = conn.createStatement();
      ResultSet rs = stmt.executeQuery(SqlUtils.getMaxDataTimeSQL(timeSpec.getColumnName(), tableName, sourceName))) {
    if (rs.next()) {
      String maxTimeString = rs.getString(1);
      if (maxTimeString.indexOf('.') >= 0) {
        maxTimeString = maxTimeString.substring(0, maxTimeString.indexOf('.'));
      }

      String timeFormat = timeSpec.getFormat();

      if (StringUtils.isBlank(timeFormat) || TimeSpec.SINCE_EPOCH_FORMAT.equals(timeFormat)) {
        maxTime = timeSpec.getDataGranularity().toMillis(Long.valueOf(maxTimeString) - 1, timeZone);
      } else {
        DateTimeFormatter inputDataDateTimeFormatter =
            DateTimeFormat.forPattern(timeFormat).withZone(timeZone);
        DateTime endDateTime = DateTime.parse(maxTimeString, inputDataDateTimeFormatter);
        Period oneBucket = datasetConfig.bucketTimeGranularity().toPeriod();
        maxTime = endDateTime.plus(oneBucket).getMillis() - 1;
      }
    }
  } catch (Exception e) {
    throw e;
  }
  return maxTime;
}
 
Example #21
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 #22
Source File: RDBMSDataSource.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public DataSource getDataSource() {
	if (this.dataSource == null) {
		this.dataSource = new DataSource(poolProperties);
	}
               if (poolProperties.isJmxEnabled()) {
                       this.registerMBean();
               }
	return this.dataSource;
}
 
Example #23
Source File: PooledConnectionTomcat.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static DataSource getDataSource(Isolation isolation) {
  if (ds == null) {
    setupDataSource(isolation);
    MasterController.sleepForMs(1000);
    Log.getLogWriter().info("max active is " + ds.getMaxActive());
  }

  return ds;
}
 
Example #24
Source File: Utils.java    From radman with MIT License 5 votes vote down vote up
static SpringLiquibase buildLiquibase(DataSource dataSource, LiquibaseProperties properties) {
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog(properties.getChangeLog());
    liquibase.setContexts(properties.getContexts());
    liquibase.setDefaultSchema(properties.getDefaultSchema());
    liquibase.setDropFirst(properties.isDropFirst());
    liquibase.setShouldRun(properties.isEnabled());
    liquibase.setLabels(properties.getLabels());
    liquibase.setChangeLogParameters(properties.getParameters());
    liquibase.setRollbackFile(properties.getRollbackFile());
    return liquibase;
}
 
Example #25
Source File: FlexyPoolConfiguration.java    From flexy-pool with Apache License 2.0 5 votes vote down vote up
@Bean
public Configuration<DataSource> configuration() {
    return new Configuration.Builder<DataSource>(
            uniqueId,
            poolingDataSource,
            TomcatCPPoolAdapter.FACTORY
    ).build();
}
 
Example #26
Source File: FlexyPoolConfiguration.java    From flexy-pool with Apache License 2.0 5 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "stop")
public FlexyPoolDataSource dataSource() {
    Configuration<DataSource> configuration = configuration();
    return new FlexyPoolDataSource<DataSource>(configuration,
            new IncrementPoolOnTimeoutConnectionAcquiringStrategy.Factory(5),
            new RetryConnectionAcquiringStrategy.Factory(2)
    );
}
 
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: TomcatJdbcDataSourceFactoryTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testCreateWithDefaultSettings() throws Exception {
	TomcatJdbcDataSourceFactory tomcatJdbcDataSourceFactory = new TomcatJdbcDataSourceFactory();

	DataSourceInformation dataSourceInformation = new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "user", "password");
	DataSource dataSource = tomcatJdbcDataSourceFactory
			.createDataSource(dataSourceInformation);
	assertThat(dataSource).isNotNull();

	assertThat(dataSource.getDriverClassName()).isEqualTo("com.mysql.jdbc.Driver");
	assertThat(dataSource.getUrl()).isEqualTo("jdbc:mysql://localhost:3306/test");
	assertThat(dataSource.getUsername()).isEqualTo("user");
}
 
Example #29
Source File: TomcatJdbcDataSourceFactoryTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testWithCustomDatabasePlatformSupport() throws Exception {
	TomcatJdbcDataSourceFactory tomcatJdbcDataSourceFactory = new TomcatJdbcDataSourceFactory();

	tomcatJdbcDataSourceFactory
			.setDatabasePlatformSupport(new MapBasedDatabasePlatformSupport() {

				@Override
				protected Map<DatabaseType, String> getDriverClassNameMappings() {
					return Collections.singletonMap(DatabaseType.MYSQL,
							"com.mysql.driver");
				}

				@Override
				protected Map<DatabaseType, String> getSchemeNames() {
					return Collections.singletonMap(DatabaseType.MYSQL, "jdbc:sql");
				}

				@Override
				protected Map<DatabaseType, String> getAuthenticationInfo() {
					return Collections.emptyMap();
				}
			});

	DataSourceInformation dataSourceInformation = new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "user", "password");
	DataSource dataSource = tomcatJdbcDataSourceFactory
			.createDataSource(dataSourceInformation);
	assertThat(dataSource).isNotNull();

	assertThat(dataSource.getDriverClassName()).isEqualTo("com.mysql.driver");
	assertThat(dataSource.getUrl()).isEqualTo("jdbc:sql://localhost:3306/test");
	assertThat(dataSource.getUsername()).isEqualTo("user");
}
 
Example #30
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());
}