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

The following are top voted examples for showing how to use org.apache.tomcat.jdbc.pool.DataSource. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tomcat7   File: SimplePOJOExample.java   Source Code and License 6 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 2
Project: tomcat7   File: PoolCleanerTest.java   Source Code and 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 3
Project: tomcat7   File: TestSizePreservation.java   Source Code and 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 4
Project: apache-tomcat-7.0.73-with-comment   File: PoolCleanerTest.java   Source Code and 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 5
Project: apache-tomcat-7.0.73-with-comment   File: TestSizePreservation.java   Source Code and 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 6
Project: careconnect-reference-implementation   File: DataSourceConfig.java   Source Code and License 6 votes vote down vote up
@Bean
public EntityManagerFactory entityManagerFactory(DataSource dataSource) {
    final Database database = Database.valueOf(vendor.toUpperCase());
    /*
    final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setShowSql(showSql);
    vendorAdapter.setGenerateDdl(showDdl);
    vendorAdapter.setDatabase(database);
    */

    final LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setPersistenceUnitName("CCRI_PU");
   // factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("uk.nhs.careconnect.ri.entity");
    factory.setDataSource(dataSource);
    factory.setPersistenceProvider(new HibernatePersistenceProvider());
    factory.setJpaProperties(jpaProperties());
    factory.afterPropertiesSet();


    return factory.getObject();
}
 
Example 7
Project: java-a-to-z   File: DbManager.java   Source Code and License 6 votes vote down vote up
/**
 * Connects to specified database.
 */
private void connectToDb() {
    this.loadProperties();
    PoolProperties p = new PoolProperties();
    p.setUrl(this.prs.getProperty("url"));
    p.setDriverClassName(SQL_DRIVER);
    p.setUsername(this.prs.getProperty("user"));
    p.setPassword(this.prs.getProperty("password"));
    DataSource datasource = new DataSource();
    datasource.setPoolProperties(p);
    try {
        this.conn = datasource.getConnection();
    } catch (SQLException e) {
        LOG.error(e.getMessage(), e);
    }
}
 
Example 8
Project: java-a-to-z   File: DbManager.java   Source Code and License 6 votes vote down vote up
/**
 * Connects to specified database.
 */
private void connectToDb() {
    this.loadProperties();

    PoolProperties p = new PoolProperties();
    DataSource datasource = new DataSource();
    p.setUrl(this.prs.getProperty("url"));
    p.setDriverClassName(SQL_DRIVER);
    p.setUsername(this.prs.getProperty("user"));
    p.setPassword(this.prs.getProperty("password"));
    datasource.setPoolProperties(p);
    try {
        this.conn = datasource.getConnection();
    } catch (SQLException e) {
        LOG.error(e.getMessage(), e);
    }
    this.createTable();
}
 
Example 9
Project: java-a-to-z   File: DbManager.java   Source Code and License 6 votes vote down vote up
/**
 * Connects to specified database.
 */
private void connectToDb() {
    this.loadProperties();
    PoolProperties p = new PoolProperties();
    p.setUrl(this.prs.getProperty("url"));
    p.setDriverClassName(SQL_DRIVER);
    p.setUsername(this.prs.getProperty("user"));
    p.setPassword(this.prs.getProperty("password"));
    DataSource datasource = new DataSource();
    datasource.setPoolProperties(p);
    try {
        this.conn = datasource.getConnection();
        System.out.println(this.conn);
    } catch (SQLException e) {
        LOG.error(e.getMessage(), e);
    }
    this.createTable();
}
 
Example 10
Project: java-a-to-z   File: DbManager.java   Source Code and License 6 votes vote down vote up
/**
 * Connects to specified database.
 */
private void connectToDb() {
    this.loadProperties();
    PoolProperties p = new PoolProperties();
    p.setUrl(this.prs.getProperty("url"));
    p.setDriverClassName(SQL_DRIVER);
    p.setUsername(this.prs.getProperty("user"));
    p.setPassword(this.prs.getProperty("password"));
    DataSource datasource = new DataSource();
    datasource.setPoolProperties(p);
    try {
        this.conn = datasource.getConnection();
        System.out.println(this.conn);
    } catch (SQLException e) {
        LOG.error(e.getMessage(), e);
    }
    this.createTable();
}
 
Example 11
Project: SpringbootMultiDatasourceSample   File: AbstractDatasourceProperties.java   Source Code and License 6 votes vote down vote up
@Bean
public DataSource createDataSourceBean(){
       DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
       ds.setDriverClassName(this.dataSourceProperties.getDriverClassName());
       
       ds.setMaxActive(this.dataSourceProperties.getMaxActive());
       ds.setMaxIdle(this.dataSourceProperties.getMaxIdle());
       ds.setMinIdle(this.dataSourceProperties.getMinIdle());
       ds.setInitialSize(this.dataSourceProperties.getInitialSize());
       
       ds.setValidationQuery(this.dataSourceProperties.getValidationQuery());
       ds.setTestOnBorrow(this.dataSourceProperties.getTestOnBorrow());
       ds.setTestWhileIdle(this.dataSourceProperties.getTestWhileIdle());
       ds.setTimeBetweenEvictionRunsMillis(this.dataSourceProperties.getTimeBetweenEvictionRunsMillis());
       ds.setMinEvictableIdleTimeMillis(this.dataSourceProperties.getMinEvictableIdleTimeMillis());
       
       ds.setUrl(this.getUrl());
       ds.setUsername(this.getUsername());
       ds.setPassword(this.getPassword());
       return ds;
}
 
Example 12
Project: gemfirexd-oss   File: PooledConnectionTomcat.java   Source Code and License 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
Project: Capstone2016   File: DBInterfaceTests.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws IOException {
    // Get the relative path context
    final String servletContextPath = AllTests.getServletContextPath();
    final String sep = File.separator;
    dbConfigPath = servletContextPath + "/web/WEB-INF/dbconfig.properties.dev".replace("/", sep);

    // Load the db config properties
    Properties prop = new Properties();
    try (InputStream input = new FileInputStream(dbConfigPath)) {
        prop.load(input);
    }
    PoolProperties p = new PoolProperties();

    p.setDriverClassName(  prop.getProperty("driver")  );
    p.setUsername(         prop.getProperty("user")    );
    p.setPassword(         prop.getProperty("password"));
    p.setUrl(              prop.getProperty("url")     );
    p.setValidationQuery(  "SELECT 1;"                  );

    ds = new DataSource(p);
}
 
Example 14
Project: Capstone2016   File: NestHttpTests.java   Source Code and License 6 votes vote down vote up
/**
 * For wiping the test database before running tests, so we know they are atomic
 * @throws SQLException
 * @throws IOException 
 */
protected static void NestWipeDB() throws SQLException, IOException {
    // Wipe the DB so we know the tests are atomic.
    
    // First read the repeatable SQL DB schema into memory.
    String dbSchema = null;
    try (Scanner scanner = new Scanner(new File(DBCREATESCRIPT_PATH));) {
        dbSchema = scanner.useDelimiter("\\A").next();
    }
    if (dbSchema == null) {
        throw new IOException("Unable to load repeatable database schema");
    }
    
    // Next wipe the db
    DataSource dsTest = Common.getNestDS(DBCONFIGPATH_TEST);
    try (
        Connection conn = dsTest.getConnection();
        Statement st = conn.createStatement();        
    ) {
        boolean hasResults = st.execute(dbSchema);
    }
    dsTest.close();
}
 
Example 15
Project: Capstone2016   File: NestHttpTests.java   Source Code and License 6 votes vote down vote up
/**
 * Remove the created entities directly via the db so we don't worry about bugs in DELETE.
 * @param entitiesList These should be names of tables in the database!
 * @param ids This should have keys for each value in entitiesList!
 * @return
 * @throws SQLException
 * @throws IOException 
 */
protected static boolean dbDeleteEntities(List<String> entitiesList, Map<String,Long> ids) throws SQLException, IOException {
    DataSource dsTest = Common.getNestDS(DBCONFIGPATH_TEST);
    
    for(int i = entitiesList.size()-1; i >= 0; i--) {
        
        // Get the entities to delete
        final String tablename = entitiesList.get(i);
        Long id = ids.get(tablename);
        // It's late, okay!?
        final String columnname = (!tablename.equals("users"))? tablename+"_id" : "user_id";
        
        try (
            Connection conn = dsTest.getConnection();
            Statement st = conn.createStatement();        
        ) {
            boolean hasResults = st.execute("DELETE FROM "+tablename+" WHERE "+columnname+" = "+id+";");
        }
    }
    dsTest.close();
    return true;
}
 
Example 16
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: DataSourceJsonSerializationTests.java   Source Code and License 6 votes vote down vote up
@Override
public void serialize(DataSource value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException, JsonProcessingException {
	jgen.writeStartObject();
	for (PropertyDescriptor property : BeanUtils
			.getPropertyDescriptors(DataSource.class)) {
		Method reader = property.getReadMethod();
		if (reader != null && property.getWriteMethod() != null
				&& this.conversionService.canConvert(String.class,
						property.getPropertyType())) {
			jgen.writeObjectField(property.getName(),
					ReflectionUtils.invokeMethod(reader, value));
		}
	}
	jgen.writeEndObject();
}
 
Example 17
Project: spring-boot-concourse   File: DataSourceJsonSerializationTests.java   Source Code and License 6 votes vote down vote up
@Override
public void serialize(DataSource value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException, JsonProcessingException {
	jgen.writeStartObject();
	for (PropertyDescriptor property : BeanUtils
			.getPropertyDescriptors(DataSource.class)) {
		Method reader = property.getReadMethod();
		if (reader != null && property.getWriteMethod() != null
				&& this.conversionService.canConvert(String.class,
						property.getPropertyType())) {
			jgen.writeObjectField(property.getName(),
					ReflectionUtils.invokeMethod(reader, value));
		}
	}
	jgen.writeEndObject();
}
 
Example 18
Project: contestparser   File: DataSourceJsonSerializationTests.java   Source Code and License 6 votes vote down vote up
@Override
public void serialize(DataSource value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException, JsonProcessingException {
	jgen.writeStartObject();
	for (PropertyDescriptor property : BeanUtils
			.getPropertyDescriptors(DataSource.class)) {
		Method reader = property.getReadMethod();
		if (reader != null && property.getWriteMethod() != null
				&& this.conversionService.canConvert(String.class,
						property.getPropertyType())) {
			jgen.writeObjectField(property.getName(),
					ReflectionUtils.invokeMethod(reader, value));
		}
	}
	jgen.writeEndObject();
}
 
Example 19
Project: gemfirexd-oss   File: PooledConnectionTomcat.java   Source Code and License 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 20
Project: psi-probe   File: TomcatJdbcPoolDatasourceAccessor.java   Source Code and License 6 votes vote down vote up
@Override
public DataSourceInfo getInfo(Object resource) throws Exception {
  DataSourceInfo dataSourceInfo = null;
  if (canMap(resource)) {
    DataSource source = (DataSource) resource;
    dataSourceInfo = new DataSourceInfo();
    dataSourceInfo.setBusyConnections(source.getNumActive());
    dataSourceInfo.setEstablishedConnections(source.getNumIdle() + source.getNumActive());
    dataSourceInfo.setMaxConnections(source.getMaxActive());
    dataSourceInfo.setJdbcUrl(source.getUrl());
    dataSourceInfo.setUsername(source.getUsername());
    dataSourceInfo.setResettable(false);
    dataSourceInfo.setType("tomcat-jdbc");
  }
  return dataSourceInfo;
}
 
Example 21
Project: psi-probe   File: TomEEJdbcPoolDatasourceAccessor.java   Source Code and License 6 votes vote down vote up
@Override
public DataSourceInfo getInfo(Object resource) throws Exception {
  DataSourceInfo dataSourceInfo = null;
  if (canMap(resource)) {
    DataSource source = (DataSource) resource;
    dataSourceInfo = new DataSourceInfo();
    dataSourceInfo.setBusyConnections(source.getNumActive());
    dataSourceInfo.setEstablishedConnections(source.getNumIdle() + source.getNumActive());
    dataSourceInfo.setMaxConnections(source.getMaxActive());
    dataSourceInfo.setJdbcUrl(source.getUrl());
    dataSourceInfo.setUsername(source.getUsername());
    dataSourceInfo.setResettable(false);
    dataSourceInfo.setType("tomcat-jdbc");
  }
  return dataSourceInfo;
}
 
Example 22
Project: flow   File: TomcatSchema.java   Source Code and License 6 votes vote down vote up
public TomcatSchema(@Nonnull Config config) {
	checkNotNull(config);

	log.debug("{} sql.url: {}", config.getName(), config.getString("sql.url"));

	PoolProperties poolProps = new PoolProperties();
	poolProps.setUrl(config.getString("sql.url"));
	poolProps.setUsername(config.getString("sql.login"));
	poolProps.setPassword(config.getString("sql.password"));
	poolProps.setDriverClassName(config.getString("sql.driver"));
	poolProps.setMinIdle(config.getInt("sql.pool.minIdle", 1));
	poolProps.setMaxIdle(config.getInt("sql.pool.maxIdle", 3));
	poolProps.setMaxActive(config.getInt("sql.pool.maxActive", 5));
	poolProps.setInitialSize(poolProps.getMinIdle());
	poolProps.setValidationQuery("SELECT 1");
	poolProps.setValidationQueryTimeout((int) config.getTime("sql.pool.validationQueryTimeout", "5s"));
	poolProps.setTestOnBorrow(config.getBoolean("sql.pool.testOnBorrow", true));
	poolProps.setDefaultReadOnly(config.getBoolean("sql.pool.defaultReadOnly", true));
	dataSource = new DataSource(poolProps);
	streaming = config.getBoolean("sql.streaming", false);
}
 
Example 23
Project: Spring-Security-Thymeleaf-Integration   File: AppConfig.java   Source Code and License 6 votes vote down vote up
@Bean
public DataSource dataSource() {
    logger.info("Create DataSource bean. JDBC URL " + env.getProperty("database.url") + ", for username: " + env.getProperty("database.user"));
    try {
        PoolProperties poolProperties = new PoolProperties();
        poolProperties.setUsername(env.getProperty("database.user"));
        poolProperties.setPassword(env.getProperty("database.password"));
        poolProperties.setUrl(env.getProperty("database.url"));
        poolProperties.setDriverClassName("com.mysql.jdbc.Driver");
        poolProperties.setMaxActive(50);
        poolProperties.setMaxIdle(50);
        poolProperties.setInitialSize(1);

        return new DataSource(poolProperties);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}
 
Example 24
Project: class-guard   File: PoolCleanerTest.java   Source Code and 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 25
Project: class-guard   File: TestSizePreservation.java   Source Code and 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 26
Project: apache-tomcat-7.0.57   File: PoolCleanerTest.java   Source Code and 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 27
Project: apache-tomcat-7.0.57   File: TestSizePreservation.java   Source Code and 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 28
Project: carbon-data   File: JDBCPoolSQLConfig.java   Source Code and License 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 29
Project: WBSAirback   File: TestSizePreservation.java   Source Code and 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 30
Project: recommendation-bay   File: ImportJob.java   Source Code and License 6 votes vote down vote up
private void initDBConnecting() {
    PoolProperties pp = new PoolProperties();

    pp.setUrl("jdbc:postgresql://minecraft.habales.de:5432/recbay");
    pp.setUsername("recbay");
    pp.setPassword("yicMymojtyk9");
    pp.setDriverClassName("org.postgresql.Driver");

    DataSource ds = new DataSource(pp);
    ds.setCommitOnReturn(false);

    // create session and assign it to the thread
    DbSession session = new DbThreadSession(new ConnectionPoolDataSourceConnectionProvider(ds));

    session.beginTransaction(new DbTransactionMode().setReadOnly(false));
}
 
Example 31
Project: lakeside-java   File: MysqlDataSource.java   Source Code and License 6 votes vote down vote up
public MysqlDataSource(String jdbcurl,String userName,String password){
	DataSource cdataSource = new DataSource();
	if(isReplicationConnection(jdbcurl)){
		cdataSource.setDriverClassName(REPLICATION_DRIVER);
		log.info("will create mysql connection with replication mode");
	}else{
		cdataSource.setDriverClassName(SINGLETON_DRIVER);
		log.info("will create mysql connection with standard mode");
	}
	cdataSource.setUrl(jdbcurl);
	cdataSource.setUsername(userName);
	cdataSource.setPassword(password);
	cdataSource.setMaxActive(50);
	cdataSource.setMaxIdle(10);
	cdataSource.setMinIdle(0);
	cdataSource.setInitialSize(1);
	cdataSource.setDefaultAutoCommit(true);
	/** 连接Idle10分钟后超时,每1分钟检查一次 **/
	cdataSource.setTimeBetweenEvictionRunsMillis(60000);
	cdataSource.setMinEvictableIdleTimeMillis(600000);
	/*---------*/
	this.dataSource = cdataSource;
	jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
 
Example 32
Project: camunda-bpm-platform   File: PerfTestProcessEngine.java   Source Code and License 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 33
Project: aceql-http   File: DataSourceStore.java   Source Code and License 5 votes vote down vote up
/**
 * Method to be called by users servlets to get info on the JDBC Pool DataSources created for each database.
 * <br><br>
 * The {@link DefaultPoolsInfo} servlet with url-pattern {@code /default_pools_info} is provided to query some info
 * for of each database {@code DataSource}.
 * <br>
 * @return the the {@code Map} of {@code org.apache.tomcat.jdbc.pool.DataSource} per database
 */
public static Map<String, DataSource> getDataSources() {
    Set<String> databases = ServletParametersStore.getDatabaseNames();
    
    Map<String, DataSource> dataSourceSet = new HashMap<>();
    
    if (databases == null || databases.isEmpty()) {
        return dataSourceSet;
    }
    
    for (String database : databases) {
        dataSourceSet.put(database, (org.apache.tomcat.jdbc.pool.DataSource)TomcatSqlModeStore.getDataSource(database));
    }
    return dataSourceSet;
}
 
Example 34
Project: aceql-http   File: TestTomcatJdbcPoolBehavior.java   Source Code and License 5 votes vote down vote up
public static void createPool() throws Exception {
// Modify this code in order to extract a Connection from your
// connection pooling system:

// Driver parameters to use:
String driverClassName = "org.postgresql.Driver";
String url = "jdbc:postgresql://localhost:5432/kawansoft_example";
String username = "user1";
String password = "password1";

// Creating the DataSource bean and populating the values:
// Mandatory values to set
PoolProperties p = new PoolProperties();
p.setDriverClassName(driverClassName);
p.setUrl(url);
p.setUsername(username);
p.setPassword(password);

// Other possible values to set
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(2);
p.setInitialSize(2);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(60);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(2);
p.setMaxIdle(2);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors("ConnectionState;StatementFinalizer");

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

   }
 
Example 35
Project: apache-tomcat-7.0.73-with-comment   File: SimplePOJOExample.java   Source Code and License 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 36
Project: java-a-to-z   File: DbManager.java   Source Code and License 5 votes vote down vote up
/**
 * Connects to specified database.
 */
private void connectToDb() {
    PoolProperties p = new PoolProperties();
    p.setUrl(this.prs.getProperty("url"));
    p.setDriverClassName(SQL_DRIVER);
    p.setUsername(this.prs.getProperty("user"));
    p.setPassword(this.prs.getProperty("password"));
    DataSource datasource = new DataSource();
    datasource.setPoolProperties(p);
    try {
        this.conn = datasource.getConnection();
    } catch (SQLException e) {
        LOG.error(e.getMessage(), e);
    }
}
 
Example 37
Project: seqcode-core   File: DatabaseConnectionManager.java   Source Code and License 5 votes vote down vote up
/**
 * returns the default read-only connection for this role 
 */
public static Connection getConnection(String role) throws SQLException, UnknownRoleException {
    Properties props = null;
    try {
    	role = getRealRole(role);
    	if(!usedRoles.contains(role))
    		usedRoles.add(role);
        String user, schema;
        if (defaultUsers.containsKey(role) && 
            defaultSchemas.containsKey(role)) {
            user = defaultUsers.get(role);
            schema = defaultSchemas.get(role);
        } else {
            props = getPropertiesForRole(role);
            user = props.getProperty("user");
            schema = props.getProperty("schema");
            defaultUsers.put(role,user);
            defaultSchemas.put(role,schema);
        }
        String key = role + user + schema;
        if (!sources.containsKey(key)) {
            if (props == null)
                props = getPropertiesForRole(role);
            addDataSource(key,props);
        }
        DataSource src = sources.get(key);            
        Connection cxn = src.getConnection();
        cxnSource.put(cxn,src);
        return cxn;
    } catch (IOException ex) {
        throw new RuntimeException("Couldn't read properties for " + role,ex);
    }
}
 
Example 38
Project: seqcode-core   File: DatabaseConnectionManager.java   Source Code and License 5 votes vote down vote up
/**
 * returns the type (ORACLE, MYSQL, UNKNOWN) of this
 * Connection
 */
public static int getType(Connection c) {
    DataSource p = cxnSource.get(c);
    if (p == null) {
        return UNKNOWN;
    } else {
        return sourceType.get(p);
    }
}
 
Example 39
Project: retz   File: LegacyDBMigration.java   Source Code and License 5 votes vote down vote up
public static void migrate(DataSource dataSource) throws SQLException, IOException {
    try (Connection conn = dataSource.getConnection()) { //pool.getConnection()) {
        conn.setAutoCommit(false);
        DatabaseMetaData meta = conn.getMetaData();

        if (!meta.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE)) {
            LOG.error("Current database ({}) does not support required isolation level ({})",
                    dataSource.getUrl(), Connection.TRANSACTION_SERIALIZABLE);
            throw new RuntimeException("Current database does not support serializable");
        }
        maybeCreateTables(conn);
        conn.commit();
    }
}
 
Example 40
Project: gemfirexd-oss   File: PooledConnectionTomcat.java   Source Code and License 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 41
Project: openbravo-brazil   File: JdbcExternalConnectionPool.java   Source Code and License 5 votes vote down vote up
/**
 * This method closes apache jdbc connection pool.
 */
@Override
public void closePool() {
  DataSource ds = getDataSource();
  if (ds != null) {
    // Closes the pool and all idle connections. true parameter is for close the active
    // connections too.
    ds.close(true);
  }
  super.closePool();
}
 
Example 42
Project: Capstone2016   File: DBConnectTests.java   Source Code and License 5 votes vote down vote up
/**
 * Test that the handler can connect to the test db server using the Common method
 * @throws IOException
 * @throws SQLException 
 */
@Test
public void TestDatabaseConnects() throws IOException, SQLException {
    // Load the db config properties
    DataSource dsTest = Common.getNestDS(dbConfigPathTest);
    Connection conn = dsTest.getConnection();
    Statement st = conn.createStatement();
    ResultSet rsh = st.executeQuery("SELECT 1;");
    
    assertTrue(rsh.isBeforeFirst());
    rsh.close();
    st.close();
    conn.close();
    dsTest.close();
}
 
Example 43
Project: Capstone2016   File: DBConnectTests.java   Source Code and License 5 votes vote down vote up
/**
 * Test that the handler can connect to the prod db server using the Common method
 * @throws IOException
 * @throws SQLException 
 */
@Test
public void ProdDatabaseConnects() throws IOException, SQLException {
    // Load the db config properties
    DataSource dsProd = Common.getNestDS(dbConfigPathProd);
    Connection conn = dsProd.getConnection();
    Statement st = conn.createStatement();
    ResultSet rsh = st.executeQuery("SELECT 1;");

    assertTrue(rsh.isBeforeFirst());
    rsh.close();
    st.close();
    conn.close();
    dsProd.close();
}
 
Example 44
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: TomcatDataSourcePoolMetadataTests.java   Source Code and License 5 votes vote down vote up
@Override
public void getValidationQuery() {
	DataSource dataSource = createDataSource(0, 4);
	dataSource.setValidationQuery("SELECT FROM FOO");
	assertThat(new TomcatDataSourcePoolMetadata(dataSource).getValidationQuery())
			.isEqualTo("SELECT FROM FOO");
}
 
Example 45
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: TomcatDataSourcePoolMetadataTests.java   Source Code and License 5 votes vote down vote up
private DataSource createDataSource(int minSize, int maxSize) {
	DataSource dataSource = (DataSource) initializeBuilder().type(DataSource.class)
			.build();
	dataSource.setMinIdle(minSize);
	dataSource.setMaxActive(maxSize);

	// Avoid warnings
	dataSource.setInitialSize(minSize);
	dataSource.setMaxIdle(maxSize);
	return dataSource;
}
 
Example 46
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: DataSourceJsonSerializationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void serializerFactory() throws Exception {
	DataSource dataSource = new DataSource();
	SerializerFactory factory = BeanSerializerFactory.instance
			.withSerializerModifier(new GenericSerializerModifier());
	ObjectMapper mapper = new ObjectMapper();
	mapper.setSerializerFactory(factory);
	String value = mapper.writeValueAsString(dataSource);
	assertThat(value.contains("\"url\":")).isTrue();
}
 
Example 47
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: DataSourceJsonSerializationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void serializerWithMixin() throws Exception {
	DataSource dataSource = new DataSource();
	ObjectMapper mapper = new ObjectMapper();
	mapper.addMixIn(DataSource.class, DataSourceJson.class);
	String value = mapper.writeValueAsString(dataSource);
	assertThat(value.contains("\"url\":")).isTrue();
	assertThat(StringUtils.countOccurrencesOf(value, "\"url\"")).isEqualTo(1);
}
 
Example 48
Project: spring-boot-concourse   File: TomcatDataSourcePoolMetadataTests.java   Source Code and License 5 votes vote down vote up
@Override
public void getValidationQuery() {
	DataSource dataSource = createDataSource(0, 4);
	dataSource.setValidationQuery("SELECT FROM FOO");
	assertThat(new TomcatDataSourcePoolMetadata(dataSource).getValidationQuery())
			.isEqualTo("SELECT FROM FOO");
}
 
Example 49
Project: spring-boot-concourse   File: TomcatDataSourcePoolMetadataTests.java   Source Code and License 5 votes vote down vote up
private DataSource createDataSource(int minSize, int maxSize) {
	DataSource dataSource = (DataSource) initializeBuilder().type(DataSource.class)
			.build();
	dataSource.setMinIdle(minSize);
	dataSource.setMaxActive(maxSize);

	// Avoid warnings
	dataSource.setInitialSize(minSize);
	dataSource.setMaxIdle(maxSize);
	return dataSource;
}
 
Example 50
Project: spring-boot-concourse   File: DataSourceJsonSerializationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void serializerFactory() throws Exception {
	DataSource dataSource = new DataSource();
	SerializerFactory factory = BeanSerializerFactory.instance
			.withSerializerModifier(new GenericSerializerModifier());
	ObjectMapper mapper = new ObjectMapper();
	mapper.setSerializerFactory(factory);
	String value = mapper.writeValueAsString(dataSource);
	assertThat(value.contains("\"url\":")).isTrue();
}
 
Example 51
Project: spring-boot-concourse   File: DataSourceJsonSerializationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void serializerWithMixin() throws Exception {
	DataSource dataSource = new DataSource();
	ObjectMapper mapper = new ObjectMapper();
	mapper.addMixIn(DataSource.class, DataSourceJson.class);
	String value = mapper.writeValueAsString(dataSource);
	assertThat(value.contains("\"url\":")).isTrue();
	assertThat(StringUtils.countOccurrencesOf(value, "\"url\"")).isEqualTo(1);
}
 
Example 52
Project: csi   File: CsiDataSourceProvider.java   Source Code and License 5 votes vote down vote up
public CsiDataSourceProvider() {
	this.dataSource = new DataSource();
	dataSource.setUrl("jdbc:h2:mem:dataSource");
	dataSource.setDriverClassName("org.h2.Driver");
	dataSource.setUsername("sa");
	dataSource.setPassword("");
	dataSource.setMaxActive(10);
	dataSource.setMinIdle(1);
	dataSource.setValidationQuery("SELECT 1 from DUAL;");
}
 
Example 53
Project: contestparser   File: TomcatDataSourcePoolMetadataTests.java   Source Code and License 5 votes vote down vote up
@Override
public void getValidationQuery() {
	DataSource dataSource = createDataSource(0, 4);
	dataSource.setValidationQuery("SELECT FROM FOO");
	assertEquals("SELECT FROM FOO",
			new TomcatDataSourcePoolMetadata(dataSource).getValidationQuery());
}
 
Example 54
Project: contestparser   File: TomcatDataSourcePoolMetadataTests.java   Source Code and License 5 votes vote down vote up
private DataSource createDataSource(int minSize, int maxSize) {
	DataSource dataSource = (DataSource) initializeBuilder().type(DataSource.class)
			.build();
	dataSource.setMinIdle(minSize);
	dataSource.setMaxActive(maxSize);

	// Avoid warnings
	dataSource.setInitialSize(minSize);
	dataSource.setMaxIdle(maxSize);
	return dataSource;
}
 
Example 55
Project: contestparser   File: DataSourceJsonSerializationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void serializerFactory() throws Exception {
	DataSource dataSource = new DataSource();
	SerializerFactory factory = BeanSerializerFactory.instance
			.withSerializerModifier(new GenericSerializerModifier());
	ObjectMapper mapper = new ObjectMapper();
	mapper.setSerializerFactory(factory);
	String value = mapper.writeValueAsString(dataSource);
	assertTrue(value.contains("\"url\":"));
}
 
Example 56
Project: contestparser   File: DataSourceJsonSerializationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void serializerWithMixin() throws Exception {
	DataSource dataSource = new DataSource();
	ObjectMapper mapper = new ObjectMapper();
	mapper.addMixIn(DataSource.class, DataSourceJson.class);
	String value = mapper.writeValueAsString(dataSource);
	assertTrue(value.contains("\"url\":"));
	assertEquals(1, StringUtils.countOccurrencesOf(value, "\"url\""));
}
 
Example 57
Project: gemfirexd-oss   File: PooledConnectionTomcat.java   Source Code and License 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 58
Project: spring-data-rest-mvc-react   File: DataConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
    DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
    dataSource.setDriverClassName(jdbcDriverClassName);
    dataSource.setUrl(jdbcUrl);
    dataSource.setUsername(jdbcUsername);
    dataSource.setPassword(jdbcPassword);
    dataSource.setInitialSize(jdbcInitialSize);
    dataSource.setMaxActive(jdbcMaxActive);
    dataSource.setMaxIdle(jdbcMaxIdle);
    dataSource.setMinIdle(jdbcMinIdle);
    return dataSource;
}
 
Example 59
Project: javase-study   File: DataSourceTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() {
    PoolProperties p = new PoolProperties();
    p.setUrl("jdbc:mysql://localhost:3306/mysql");
    p.setDriverClassName("com.mysql.jdbc.Driver");
    p.setUsername("root");
    p.setPassword("");
    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.setLogAbandoned(true);
    p.setRemoveAbandoned(true);
    p.setFairQueue(true);
    p.setJdbcInterceptors(
            "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" +
                    "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
    dataSource = new DataSource();
    dataSource.setPoolProperties(p);
}
 
Example 60
Project: javase-study   File: DbUtilsTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() {
    PoolProperties p = new PoolProperties();
    p.setUrl("jdbc:mysql://localhost:3306/admin");
    p.setDriverClassName("com.mysql.jdbc.Driver");
    p.setUsername("root");
    p.setPassword("");
    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.setLogAbandoned(true);
    p.setRemoveAbandoned(true);
    p.setFairQueue(true);
    p.setJdbcInterceptors(
            "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" +
                    "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
    dataSource = new DataSource();
    dataSource.setPoolProperties(p);
}