Java Code Examples for org.apache.commons.dbcp2.BasicDataSource#setValidationQuery()

The following examples show how to use org.apache.commons.dbcp2.BasicDataSource#setValidationQuery() . 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: DataSourceManager.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void createPoolIfAbsent(IDataSource dataSource) {
	Assert.assertNotNull(dataSource, "Missing input datasource");
	Assert.assertNotNull(dataSource.getJdbcPoolConfiguration(), "Connection pool information is not provided");

	logger.debug("Creating connection pool for datasource " + dataSource.getLabel());
	BasicDataSource pool = new BasicDataSource();
	pool.setDriverClassName(dataSource.getDriver());
	pool.setUrl(dataSource.getUrlConnection());
	pool.setUsername(dataSource.getUser());
	pool.setPassword(dataSource.getPwd());
	pool.setMaxTotal(dataSource.getJdbcPoolConfiguration().getMaxTotal());
	pool.setMaxWaitMillis(dataSource.getJdbcPoolConfiguration().getMaxWait());
	pool.setRemoveAbandonedOnBorrow(dataSource.getJdbcPoolConfiguration().getRemoveAbandonedOnBorrow());
	pool.setRemoveAbandonedOnMaintenance(dataSource.getJdbcPoolConfiguration().getRemoveAbandonedOnMaintenance());
	pool.setRemoveAbandonedTimeout(dataSource.getJdbcPoolConfiguration().getAbandonedTimeout());
	pool.setLogAbandoned(dataSource.getJdbcPoolConfiguration().getLogAbandoned());
	pool.setTestOnReturn(dataSource.getJdbcPoolConfiguration().getTestOnReturn());
	pool.setTestWhileIdle(dataSource.getJdbcPoolConfiguration().getTestWhileIdle());
	pool.setTimeBetweenEvictionRunsMillis(dataSource.getJdbcPoolConfiguration().getTimeBetweenEvictionRuns());
	pool.setMinEvictableIdleTimeMillis(dataSource.getJdbcPoolConfiguration().getMinEvictableIdleTimeMillis());
	pool.setValidationQuery(dataSource.getJdbcPoolConfiguration().getValidationQuery());

	dataSources.put(dataSource, pool);
}
 
Example 2
Source File: PgConnectionHelper.java    From pg-index-health with Apache License 2.0 5 votes vote down vote up
private static void setCommonProperties(@Nonnull final BasicDataSource dataSource,
                                        @Nonnull final String userName,
                                        @Nonnull final String password) {
    dataSource.setDriverClassName("org.postgresql.Driver");
    dataSource.setUsername(userName);
    dataSource.setPassword(password);
    dataSource.setValidationQuery("select 1");
    dataSource.setMaxTotal(1);
    dataSource.setMaxIdle(1);
    dataSource.setMaxOpenPreparedStatements(1);
}
 
Example 3
Source File: HerdMetastoreConfig.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
@Bean(destroyMethod = "")
public DataSource getDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl( dburl );
    dataSource.setUsername( dbUser );
    dataSource.setPassword( dbPass );
    dataSource.setInitialSize( 2 );
    dataSource.setValidationQuery( validationQuery );

    return dataSource;
}
 
Example 4
Source File: DataSourceUtil.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private static DataSource createDBCP(final DatabaseType databaseType, final String dataSourceName) {
    BasicDataSource result = new BasicDataSource();
    DatabaseEnvironment databaseEnvironment = IntegrateTestEnvironment.getInstance().getDatabaseEnvironments().get(databaseType);
    result.setDriverClassName(databaseEnvironment.getDriverClassName());
    result.setUrl(null == dataSourceName ? databaseEnvironment.getURL() : databaseEnvironment.getURL(dataSourceName));
    result.setUsername(databaseEnvironment.getUsername());
    result.setPassword(databaseEnvironment.getPassword());
    result.setMaxTotal(2);
    result.setValidationQuery("SELECT 1");
    if ("Oracle".equals(databaseType.getName())) {
        result.setConnectionInitSqls(Collections.singleton("ALTER SESSION SET CURRENT_SCHEMA = " + dataSourceName));
    }
    return result;
}
 
Example 5
Source File: DBCPDataSourceBuilder.java    From micro-server with Apache License 2.0 5 votes vote down vote up
private void retrySetup(BasicDataSource ds) {
	if (!"org.hibernate.dialect.HSQLDialect".equals(mainEnv.getDialect())) {
		ds.setTestOnBorrow(dbcpEnv.isTestOnBorrow());
		ds.setValidationQuery(dbcpEnv.getValidationQuery());
		ds.setMaxTotal(dbcpEnv.getMaxTotal());
		ds.setMinEvictableIdleTimeMillis(dbcpEnv.getMinEvictableIdleTime());
		ds.setTimeBetweenEvictionRunsMillis(dbcpEnv.getTimeBetweenEvictionRuns());
		ds.setNumTestsPerEvictionRun(dbcpEnv.getNumTestsPerEvictionRun());
		ds.setTestWhileIdle(dbcpEnv.isTestWhileIdle());
		ds.setTestOnReturn(dbcpEnv.isTestOnReturn());
	}
}
 
Example 6
Source File: DBCPDataSourceServiceImporter.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
protected BasicDataSource setupDataSourcePool( DataSourceConfiguration config )
        throws Exception
{
    BasicDataSource pool = new BasicDataSource();

    Class.forName( config.driver().get() );
    pool.setDriverClassName( config.driver().get() );
    pool.setUrl( config.url().get() );

    if ( !config.username().get().equals( "" ) ) {
        pool.setUsername( config.username().get() );
        pool.setPassword( config.password().get() );
    }

    if ( config.minPoolSize().get() != null ) {
        pool.setMinIdle( config.minPoolSize().get() );
    }
    if ( config.maxPoolSize().get() != null ) {
        pool.setMaxTotal( config.maxPoolSize().get() );
    }
    if ( config.loginTimeoutSeconds().get() != null ) {
        pool.setLoginTimeout( config.loginTimeoutSeconds().get() );
    }
    if ( config.maxConnectionAgeSeconds().get() != null ) {
        pool.setMinEvictableIdleTimeMillis( config.maxConnectionAgeSeconds().get() * 1000 );
    }
    if ( config.validationQuery().get() != null ) {
        pool.setValidationQuery( config.validationQuery().get() );
    }

    return pool;
}
 
Example 7
Source File: DataSourceContainer.java    From DBus with Apache License 2.0 4 votes vote down vote up
public boolean register(JdbcVo conf) {
    boolean isOk = true;
    try {
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName(conf.getDriverClass());
        bds.setUrl(conf.getUrl());
        bds.setUsername(conf.getUserName());
        bds.setPassword(conf.getPassword());
        bds.setInitialSize(conf.getInitialSize());
        bds.setMaxTotal(conf.getMaxActive());
        bds.setMaxIdle(conf.getMaxIdle());
        bds.setMinIdle(conf.getMinIdle());
        // 设置等待获取连接的最长时间
        // bds.setMaxWaitMillis(20 * 1000);
        // validQuery 只给test idle 使用,不给 test Borrow使用, 为什么?
        // 发现 oracle版本 insert心跳被block, 下面的link 有人说 可以通过设置TestOnBorrow=false 解决。
        // https://stackoverflow.com/questions/4853732/blocking-on-dbcp-connection-pool-open-and-close-connnection-is-database-conne
        bds.setTestOnBorrow(true);
        bds.setTestWhileIdle(false);

        if (StringUtils.equalsIgnoreCase(Constants.CONFIG_DB_TYPE_ORA, conf.getType())) {
            bds.setValidationQuery("select 1 from dual");
            bds.setValidationQueryTimeout(5);
        } else if (StringUtils.equalsIgnoreCase(Constants.CONFIG_DB_TYPE_MYSQL, conf.getType())) {
            bds.setValidationQuery("select 1");
            bds.setValidationQueryTimeout(5);
        }

        /*bds.setTimeBetweenEvictionRunsMillis(1000 * 300);
        if (org.apache.commons.lang.StringUtils.equals(Constants.CONFIG_DB_TYPE_ORA, conf.getType())) {
            bds.setValidationQuery("select 1 from dual");
            bds.setValidationQueryTimeout(1);
        } else if (org.apache.commons.lang.StringUtils.equals(Constants.CONFIG_DB_TYPE_MYSQL, conf.getType())) {
            bds.setValidationQuery("select 1");
            bds.setValidationQueryTimeout(1);
        }*/
        LoggerFactory.getLogger().info("create datasource key:" + conf.getKey() + " url:" + conf.getUrl());
        cmap.put(conf.getKey(), bds);

        // 为了支持查询主库和被库的延时,一个ds需要同时建立同主库和被库的连接
        if (conf instanceof DsVo) {
            DsVo ds = (DsVo) conf;
            if (StringUtils.isNotBlank(ds.getSlvaeUrl())) {
                BasicDataSource slaveBds = new BasicDataSource();
                slaveBds.setDriverClassName(ds.getDriverClass());
                slaveBds.setUrl(ds.getSlvaeUrl());
                slaveBds.setUsername(ds.getUserName());
                slaveBds.setPassword(ds.getPassword());
                slaveBds.setInitialSize(ds.getInitialSize());
                slaveBds.setMaxTotal(ds.getMaxActive());
                slaveBds.setMaxIdle(ds.getMaxIdle());
                slaveBds.setMinIdle(ds.getMinIdle());
                slaveBds.setTestOnBorrow(true);
                slaveBds.setTestWhileIdle(false);

                if (StringUtils.equalsIgnoreCase(Constants.CONFIG_DB_TYPE_ORA, conf.getType())) {
                    slaveBds.setValidationQuery("select 1 from dual");
                    slaveBds.setValidationQueryTimeout(5);
                } else if (StringUtils.equalsIgnoreCase(Constants.CONFIG_DB_TYPE_MYSQL, conf.getType())) {
                    slaveBds.setValidationQuery("select 1");
                    slaveBds.setValidationQueryTimeout(5);
                }

                // 设置等待获取连接的最长时间
                // slaveBds.setMaxWaitMillis(20 * 1000);
                String key = StringUtils.join(new String[]{ds.getKey(), "slave"}, "_");
                LoggerFactory.getLogger().info("create datasource key:" + key + " url:" + ds.getSlvaeUrl());
                cmap.put(key, slaveBds);
            } else {
                LoggerFactory.getLogger().warn("db container initDsPool key " + ds.getKey() + " of slave url is empty.");
            }
        }

    } catch (Exception e) {
        LoggerFactory.getLogger().error("[db container initDsPool key " + conf.getKey() + " datasource error!]", e);
        isOk = false;
    }
    return isOk;
}
 
Example 8
Source File: DbConnPostgreSQL.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
/**
 * NOTE: This method must not use log4j for logging as this may cause locking issues
 */
@Override
public DataSource getDataSource() {

    // PostgreSQL does not provide connection pool (as of version 42.1.3) so make one using Apache Commons DBCP 
    ds = new BasicDataSource();

    // max number of active connections
    Integer maxTotal = AtsSystemProperties.getPropertyAsNumber("dbcp.maxTotal");
    if (maxTotal == null) {
        maxTotal = 8;
    } else {
        log.info("Max number of active connections is "
                 + maxTotal);
    }
    ds.setMaxTotal(maxTotal);

    // wait time for new connection
    Integer maxWaitMillis = AtsSystemProperties.getPropertyAsNumber("dbcp.maxWaitMillis");
    if (maxWaitMillis == null) {
        maxWaitMillis = 60 * 1000;
    } else {
        log.info("Connection creation wait is "
                 + maxWaitMillis
                 + " msec");
    }
    ds.setMaxWaitMillis(maxWaitMillis);

    String logAbandoned = System.getProperty("dbcp.logAbandoned");
    if (logAbandoned != null && ("true".equalsIgnoreCase(logAbandoned))
        || "1".equalsIgnoreCase(logAbandoned)) {
        String removeAbandonedTimeoutString = System.getProperty("dbcp.removeAbandonedTimeout");
        int removeAbandonedTimeout = (int) ds.getMaxWaitMillis() / (2 * 1000);
        if (!StringUtils.isNullOrEmpty(removeAbandonedTimeoutString)) {
            removeAbandonedTimeout = Integer.parseInt(removeAbandonedTimeoutString);
        }
        log.info(
                 "Will log and remove abandoned connections if not cleaned in "
                 + removeAbandonedTimeout
                 + " sec");
        // log not closed connections
        ds.setLogAbandoned(true); // issue stack trace of not closed connection
        ds.setAbandonedUsageTracking(true);
        ds.setLogExpiredConnections(true);
        ds.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        ds.setRemoveAbandonedOnBorrow(true);
        ds.setRemoveAbandonedOnMaintenance(true);
        ds.setAbandonedLogWriter(new PrintWriter(System.err));
    }
    ds.setValidationQuery("SELECT 1");
    ds.setDriverClassName(getDriverClass().getName());
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setUrl(getURL());
    return ds;
}
 
Example 9
Source File: Dbcp2DataSourcePool.java    From Zebra with Apache License 2.0 4 votes vote down vote up
@Override
public DataSource build(DataSourceConfig config, boolean withDefaultValue) {
	BasicDataSource dbcp2DataSource = new BasicDataSource();

	dbcp2DataSource.setUrl(config.getJdbcUrl());
	dbcp2DataSource.setUsername(config.getUsername());
	dbcp2DataSource.setPassword(config.getPassword());
	dbcp2DataSource.setDriverClassName(StringUtils.isNotBlank(config.getDriverClass()) ? config.getDriverClass()
	      : JdbcDriverClassHelper.getDriverClassNameByJdbcUrl(config.getJdbcUrl()));

	if (withDefaultValue) {
		dbcp2DataSource.setInitialSize(getIntProperty(config, "initialPoolSize", 5));
		dbcp2DataSource.setMaxTotal(getIntProperty(config, "maxPoolSize", 30));
		dbcp2DataSource.setMinIdle(getIntProperty(config, "minPoolSize", 5));
		dbcp2DataSource.setMaxIdle(getIntProperty(config, "maxPoolSize", 20));
		dbcp2DataSource.setMaxWaitMillis(getIntProperty(config, "checkoutTimeout", 1000));
		dbcp2DataSource.setValidationQuery(getStringProperty(config, "preferredTestQuery", "SELECT 1"));
		dbcp2DataSource.setMinEvictableIdleTimeMillis(getIntProperty(config, "minEvictableIdleTimeMillis", 1800000));// 30min
		dbcp2DataSource
		      .setTimeBetweenEvictionRunsMillis(getIntProperty(config, "timeBetweenEvictionRunsMillis", 30000)); // 30s
		dbcp2DataSource.setRemoveAbandonedTimeout(getIntProperty(config, "removeAbandonedTimeout", 300)); // 30s
		dbcp2DataSource.setNumTestsPerEvictionRun(getIntProperty(config, "numTestsPerEvictionRun", 6)); // 30s
		dbcp2DataSource.setValidationQueryTimeout(getIntProperty(config, "validationQueryTimeout", 0));
		if (StringUtils.isNotBlank(getStringProperty(config, "connectionInitSql", null))) {
			List<String> initSqls = new ArrayList<String>();
			initSqls.add(getStringProperty(config, "connectionInitSql", null));
			dbcp2DataSource.setConnectionInitSqls(initSqls);
		}

		dbcp2DataSource.setTestWhileIdle(true);
		dbcp2DataSource.setTestOnBorrow(false);
		dbcp2DataSource.setTestOnReturn(false);
		dbcp2DataSource.setRemoveAbandonedOnBorrow(true);
		dbcp2DataSource.setRemoveAbandonedOnMaintenance(true);
	} else {
		try {
			PropertiesInit<BasicDataSource> propertiesInit = new PropertiesInit<BasicDataSource>(dbcp2DataSource);
			propertiesInit.initPoolProperties(config);
		} catch (Exception e) {
			throw new ZebraConfigException(String.format("dbcp2 dataSource [%s] created error : ", config.getId()), e);
		}
	}

	this.pool = dbcp2DataSource;
	LOGGER.info(String.format("New dataSource [%s] created.", config.getId()));

	return this.pool;
}
 
Example 10
Source File: HadoopDBCPConnectionPool.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Configures connection pool by creating an instance of the
 * {@link BasicDataSource} based on configuration provided with
 * {@link ConfigurationContext}.
 *
 * This operation makes no guarantees that the actual connection could be
 * made since the underlying system may still go off-line during normal
 * operation of the connection pool.
 *
 * @param context
 *            the configuration context
 * @throws InitializationException
 *             if unable to create a database connection
 */
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws IOException {
    // Get Configuration instance from specified resources
    final String configFiles = context.getProperty(HADOOP_CONFIGURATION_RESOURCES).evaluateAttributeExpressions().getValue();
    final Configuration hadoopConfig = getConfigurationFromFiles(configFiles);

    // Add any dynamic properties to the HBase Configuration
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        final PropertyDescriptor descriptor = entry.getKey();
        if (descriptor.isDynamic()) {
            hadoopConfig.set(descriptor.getName(), context.getProperty(descriptor).evaluateAttributeExpressions().getValue());
        }
    }

    // If security is enabled then determine how to authenticate based on the various principal/keytab/password options
    if (SecurityUtil.isSecurityEnabled(hadoopConfig)) {
        final String explicitPrincipal = context.getProperty(kerberosProperties.getKerberosPrincipal()).evaluateAttributeExpressions().getValue();
        final String explicitKeytab = context.getProperty(kerberosProperties.getKerberosKeytab()).evaluateAttributeExpressions().getValue();
        final String explicitPassword = context.getProperty(kerberosProperties.getKerberosPassword()).getValue();
        final KerberosCredentialsService credentialsService = context.getProperty(KERBEROS_CREDENTIALS_SERVICE).asControllerService(KerberosCredentialsService.class);

        final String resolvedPrincipal;
        final String resolvedKeytab;
        if (credentialsService != null) {
            resolvedPrincipal = credentialsService.getPrincipal();
            resolvedKeytab = credentialsService.getKeytab();
        } else {
            resolvedPrincipal = explicitPrincipal;
            resolvedKeytab = explicitKeytab;
        }

        if (resolvedKeytab != null) {
            kerberosUser = new KerberosKeytabUser(resolvedPrincipal, resolvedKeytab);
            getLogger().info("Security Enabled, logging in as principal {} with keytab {}", new Object[] {resolvedPrincipal, resolvedKeytab});
        } else if (explicitPassword != null) {
            kerberosUser = new KerberosPasswordUser(resolvedPrincipal, explicitPassword);
            getLogger().info("Security Enabled, logging in as principal {} with password", new Object[] {resolvedPrincipal});
        } else {
            throw new IOException("Unable to authenticate with Kerberos, no keytab or password was provided");
        }

        ugi = SecurityUtil.getUgiForKerberosUser(hadoopConfig, kerberosUser);
        getLogger().info("Successfully logged in as principal " + resolvedPrincipal);
    } else {
        getLogger().info("Simple Authentication");
    }

    // Initialize the DataSource...
    final String dbUrl = context.getProperty(DATABASE_URL).evaluateAttributeExpressions().getValue();
    final String driverName = context.getProperty(DB_DRIVERNAME).evaluateAttributeExpressions().getValue();
    final String user = context.getProperty(DB_USER).evaluateAttributeExpressions().getValue();
    final String passw = context.getProperty(DB_PASSWORD).evaluateAttributeExpressions().getValue();
    final Integer maxTotal = context.getProperty(MAX_TOTAL_CONNECTIONS).evaluateAttributeExpressions().asInteger();
    final String validationQuery = context.getProperty(VALIDATION_QUERY).evaluateAttributeExpressions().getValue();
    final Long maxWaitMillis = extractMillisWithInfinite(context.getProperty(MAX_WAIT_TIME).evaluateAttributeExpressions());
    final Integer minIdle = context.getProperty(MIN_IDLE).evaluateAttributeExpressions().asInteger();
    final Integer maxIdle = context.getProperty(MAX_IDLE).evaluateAttributeExpressions().asInteger();
    final Long maxConnLifetimeMillis = extractMillisWithInfinite(context.getProperty(MAX_CONN_LIFETIME).evaluateAttributeExpressions());
    final Long timeBetweenEvictionRunsMillis = extractMillisWithInfinite(context.getProperty(EVICTION_RUN_PERIOD).evaluateAttributeExpressions());
    final Long minEvictableIdleTimeMillis = extractMillisWithInfinite(context.getProperty(MIN_EVICTABLE_IDLE_TIME).evaluateAttributeExpressions());
    final Long softMinEvictableIdleTimeMillis = extractMillisWithInfinite(context.getProperty(SOFT_MIN_EVICTABLE_IDLE_TIME).evaluateAttributeExpressions());

    dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverName);
    dataSource.setDriverClassLoader(this.getClass().getClassLoader());
    dataSource.setUrl(dbUrl);
    dataSource.setUsername(user);
    dataSource.setPassword(passw);
    dataSource.setMaxWaitMillis(maxWaitMillis);
    dataSource.setMaxTotal(maxTotal);
    dataSource.setMinIdle(minIdle);
    dataSource.setMaxIdle(maxIdle);
    dataSource.setMaxConnLifetimeMillis(maxConnLifetimeMillis);
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    dataSource.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);

    if (StringUtils.isEmpty(validationQuery)) {
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestOnBorrow(true);
    }
}
 
Example 11
Source File: DBCPConnectionPool.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Configures connection pool by creating an instance of the
 * {@link BasicDataSource} based on configuration provided with
 * {@link ConfigurationContext}.
 *
 * This operation makes no guarantees that the actual connection could be
 * made since the underlying system may still go off-line during normal
 * operation of the connection pool.
 *
 * @param context
 *            the configuration context
 * @throws InitializationException
 *             if unable to create a database connection
 */
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {

    final String drv = context.getProperty(DB_DRIVERNAME).evaluateAttributeExpressions().getValue();
    final String user = context.getProperty(DB_USER).evaluateAttributeExpressions().getValue();
    final String passw = context.getProperty(DB_PASSWORD).evaluateAttributeExpressions().getValue();
    final Integer maxTotal = context.getProperty(MAX_TOTAL_CONNECTIONS).evaluateAttributeExpressions().asInteger();
    final String validationQuery = context.getProperty(VALIDATION_QUERY).evaluateAttributeExpressions().getValue();
    final Long maxWaitMillis = extractMillisWithInfinite(context.getProperty(MAX_WAIT_TIME).evaluateAttributeExpressions());
    final Integer minIdle = context.getProperty(MIN_IDLE).evaluateAttributeExpressions().asInteger();
    final Integer maxIdle = context.getProperty(MAX_IDLE).evaluateAttributeExpressions().asInteger();
    final Long maxConnLifetimeMillis = extractMillisWithInfinite(context.getProperty(MAX_CONN_LIFETIME).evaluateAttributeExpressions());
    final Long timeBetweenEvictionRunsMillis = extractMillisWithInfinite(context.getProperty(EVICTION_RUN_PERIOD).evaluateAttributeExpressions());
    final Long minEvictableIdleTimeMillis = extractMillisWithInfinite(context.getProperty(MIN_EVICTABLE_IDLE_TIME).evaluateAttributeExpressions());
    final Long softMinEvictableIdleTimeMillis = extractMillisWithInfinite(context.getProperty(SOFT_MIN_EVICTABLE_IDLE_TIME).evaluateAttributeExpressions());
    final KerberosCredentialsService kerberosCredentialsService = context.getProperty(KERBEROS_CREDENTIALS_SERVICE).asControllerService(KerberosCredentialsService.class);
    final String kerberosPrincipal = context.getProperty(KERBEROS_PRINCIPAL).evaluateAttributeExpressions().getValue();
    final String kerberosPassword = context.getProperty(KERBEROS_PASSWORD).getValue();

    if (kerberosCredentialsService != null) {
        kerberosUser = new KerberosKeytabUser(kerberosCredentialsService.getPrincipal(), kerberosCredentialsService.getKeytab());
    } else if (!StringUtils.isBlank(kerberosPrincipal) && !StringUtils.isBlank(kerberosPassword)) {
        kerberosUser = new KerberosPasswordUser(kerberosPrincipal, kerberosPassword);
    }

    if (kerberosUser != null) {
        try {
            kerberosUser.login();
        } catch (LoginException e) {
            throw new InitializationException("Unable to authenticate Kerberos principal", e);
        }
    }

    dataSource = new BasicDataSource();
    dataSource.setDriverClassName(drv);

    // Optional driver URL, when exist, this URL will be used to locate driver jar file location
    final String urlString = context.getProperty(DB_DRIVER_LOCATION).evaluateAttributeExpressions().getValue();
    dataSource.setDriverClassLoader(getDriverClassLoader(urlString, drv));

    final String dburl = context.getProperty(DATABASE_URL).evaluateAttributeExpressions().getValue();

    dataSource.setMaxWaitMillis(maxWaitMillis);
    dataSource.setMaxTotal(maxTotal);
    dataSource.setMinIdle(minIdle);
    dataSource.setMaxIdle(maxIdle);
    dataSource.setMaxConnLifetimeMillis(maxConnLifetimeMillis);
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    dataSource.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);

    if (validationQuery!=null && !validationQuery.isEmpty()) {
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestOnBorrow(true);
    }

    dataSource.setUrl(dburl);
    dataSource.setUsername(user);
    dataSource.setPassword(passw);

    context.getProperties().keySet().stream().filter(PropertyDescriptor::isDynamic)
            .forEach((dynamicPropDescriptor) -> dataSource.addConnectionProperty(dynamicPropDescriptor.getName(),
                    context.getProperty(dynamicPropDescriptor).evaluateAttributeExpressions().getValue()));

}