Example usage for org.apache.commons.dbcp2 BasicDataSource setDriverClassName

List of usage examples for org.apache.commons.dbcp2 BasicDataSource setDriverClassName

Introduction

In this page you can find the example usage for org.apache.commons.dbcp2 BasicDataSource setDriverClassName.

Prototype

public synchronized void setDriverClassName(String driverClassName) 

Source Link

Document

Sets the jdbc driver class name.

Note: this method currently has no effect once the pool has been initialized.

Usage

From source file:org.apache.druid.metadata.storage.postgresql.PostgreSQLConnector.java

@Inject
public PostgreSQLConnector(Supplier<MetadataStorageConnectorConfig> config,
        Supplier<MetadataStorageTablesConfig> dbTables, PostgreSQLConnectorConfig connectorConfig) {
    super(config, dbTables);

    final BasicDataSource datasource = getDatasource();
    // PostgreSQL driver is classloader isolated as part of the extension
    // so we need to help JDBC find the driver
    datasource.setDriverClassLoader(getClass().getClassLoader());
    datasource.setDriverClassName("org.postgresql.Driver");

    // SSL Configuration
    if (connectorConfig.isUseSSL()) {
        log.info("SSL is enabled on this PostgreSQL connection.");
        datasource.addConnectionProperty(PGProperty.SSL.getName(), String.valueOf(connectorConfig.isUseSSL()));

        if (connectorConfig.getPassword() != null) {
            datasource.addConnectionProperty(PGProperty.SSL_PASSWORD.getName(), connectorConfig.getPassword());
        }/*from  w  w w.j a va 2s.  co  m*/
        if (connectorConfig.getSslFactory() != null) {
            datasource.addConnectionProperty(PGProperty.SSL_FACTORY.getName(), connectorConfig.getSslFactory());
        }
        if (connectorConfig.getSslFactoryArg() != null) {
            datasource.addConnectionProperty(PGProperty.SSL_FACTORY_ARG.getName(),
                    connectorConfig.getSslFactoryArg());
        }
        if (connectorConfig.getSslMode() != null) {
            datasource.addConnectionProperty(PGProperty.SSL_MODE.getName(), connectorConfig.getSslMode());
        }
        if (connectorConfig.getSslCert() != null) {
            datasource.addConnectionProperty(PGProperty.SSL_CERT.getName(), connectorConfig.getSslCert());
        }
        if (connectorConfig.getSslKey() != null) {
            datasource.addConnectionProperty(PGProperty.SSL_KEY.getName(), connectorConfig.getSslKey());
        }
        if (connectorConfig.getSslRootCert() != null) {
            datasource.addConnectionProperty(PGProperty.SSL_ROOT_CERT.getName(),
                    connectorConfig.getSslRootCert());
        }
        if (connectorConfig.getSslHostNameVerifier() != null) {
            datasource.addConnectionProperty(PGProperty.SSL_HOSTNAME_VERIFIER.getName(),
                    connectorConfig.getSslHostNameVerifier());
        }
        if (connectorConfig.getSslPasswordCallback() != null) {
            datasource.addConnectionProperty(PGProperty.SSL_PASSWORD_CALLBACK.getName(),
                    connectorConfig.getSslPasswordCallback());
        }
    }

    this.dbi = new DBI(datasource);

    log.info("Configured PostgreSQL as metadata storage");
}

From source file:org.apache.jmeter.protocol.jdbc.config.DataSourceElement.java

private BasicDataSource initPool(String maxPool) {
    BasicDataSource dataSource = new BasicDataSource();

    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder(40);
        sb.append("MaxPool: ");
        sb.append(maxPool);/*from w  ww.  ja  v  a2  s  . c om*/
        sb.append(" Timeout: ");
        sb.append(getTimeout());
        sb.append(" TrimInt: ");
        sb.append(getTrimInterval());
        sb.append(" Auto-Commit: ");
        sb.append(isAutocommit());
        log.debug(sb.toString());
    }
    int poolSize = Integer.parseInt(maxPool);
    dataSource.setMinIdle(0);
    dataSource.setInitialSize(poolSize);
    dataSource.setMaxIdle(poolSize);
    dataSource.setMaxTotal(poolSize);
    dataSource.setMaxWaitMillis(Long.parseLong(getTimeout()));

    dataSource.setDefaultAutoCommit(Boolean.valueOf(isAutocommit()));

    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder(40);
        sb.append("KeepAlive: ");
        sb.append(isKeepAlive());
        sb.append(" Age: ");
        sb.append(getConnectionAge());
        sb.append(" CheckQuery: ");
        sb.append(getCheckQuery());
        log.debug(sb.toString());
    }
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setTestOnCreate(false);
    dataSource.setTestWhileIdle(false);

    if (isKeepAlive()) {
        dataSource.setTestWhileIdle(true);
        dataSource.setValidationQuery(getCheckQuery());
        dataSource.setSoftMinEvictableIdleTimeMillis(Long.parseLong(getConnectionAge()));
        dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(getTrimInterval()));
    }

    int transactionIsolation = DataSourceElementBeanInfo.getTransactionIsolationMode(getTransactionIsolation());
    if (transactionIsolation >= 0) {
        dataSource.setDefaultTransactionIsolation(transactionIsolation);
    }

    String _username = getUsername();
    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder(40);
        sb.append("Driver: ");
        sb.append(getDriver());
        sb.append(" DbUrl: ");
        sb.append(getDbUrl());
        sb.append(" User: ");
        sb.append(_username);
        log.debug(sb.toString());
    }
    dataSource.setDriverClassName(getDriver());
    dataSource.setUrl(getDbUrl());

    if (_username.length() > 0) {
        dataSource.setUsername(_username);
        dataSource.setPassword(getPassword());
    }

    // log is required to ensure errors are available
    //source.enableLogging(new LogKitLogger(log));
    if (log.isDebugEnabled()) {
        log.debug("PoolConfiguration:" + this.dataSource);
    }
    return dataSource;
}

From source file:org.assertj.db.database.sqlite.SqliteConfiguration.java

@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.sqlite.JDBC");
    dataSource.setUrl("jdbc:sqlite:target/testDerby.db");
    dataSource.setUsername("");
    dataSource.setPassword("");

    try {// w  w  w . j av a2  s . co  m
        try (Connection connection = dataSource.getConnection();) {
            try (Statement statement = connection.createStatement()) {
                statement.executeUpdate("drop table if exists teSt;");
                statement.executeUpdate("create table teSt (" + " Var1 BIGINT PRIMARY KEY,\n" + " vAr2 BLOB,\n"
                        + " vaR3 CHAR,\n" + " var4 CHAR FOR BIT DATA,\n" + " var5 CLOB,\n" + " var6 DATE,\n"
                        + " var7 DECIMAL,\n" + " var8 DOUBLE,\n" + " var9 DOUBLE PRECISION,\n"
                        + " var10 FLOAT,\n" + " var11 INTEGER,\n" + " var12 LONG VARCHAR,\n"
                        + " var13 LONG VARCHAR FOR BIT DATA,\n" + " var14 NUMERIC,\n" + " var15 REAL,\n"
                        + " var16 SMALLINT,\n" + " var17 TIME,\n" + " var18 TIMESTAMP,\n" + " var19 VARCHAR,\n"
                        + " var20 VARCHAR FOR BIT DATA" + " )");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return dataSource;
}

From source file:org.beast.project.template.config.HibernateConfig.java

@Bean(initMethod = "setup", destroyMethod = "cleanup")
@Override//from w  w  w .ja  v a  2 s  . c  o  m
public DataSource dataSource() {
    /*
     EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
     DataSource ds = builder.setType(EmbeddedDatabaseType.HSQL).build();
     return ds;*/
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(org.hsqldb.jdbcDriver.class.getName());
    basicDataSource.setUsername("sa");
    basicDataSource.setPassword("");
    basicDataSource.setUrl("jdbc:hsqldb:mem:mydb");
    return basicDataSource;
}

From source file:org.beast.project.template.config.MyBatisConfig.java

@Override
public DataSource dataSource() {

    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    //DataSource ds = builder.setType(EmbeddedDatabaseType.HSQL).addScript("schema.sql").build();
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(org.hsqldb.jdbcDriver.class.getName());
    basicDataSource.setUsername("sa");
    basicDataSource.setPassword("");
    basicDataSource.setUrl("jdbc:hsqldb:mem:mydb");
    JdbcTemplate jdbcTemplate = new JdbcTemplate(basicDataSource);
    System.out.println("Creating tables");
    jdbcTemplate.execute("drop table person if exists");
    jdbcTemplate.execute("create table person(id serial, firstName varchar(50), lastName varchar(50))");
    jdbcTemplate.update("INSERT INTO users(firstName, lastName) values (?,?)", "Mike", "Lanyon");
    return basicDataSource;
}

From source file:org.cms.config.AppConfig.java

@Bean(name = "dataSource")
public DataSource getDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/cms_praksa");
    dataSource.setUsername("admin");
    dataSource.setPassword("admin");

    return dataSource;
}

From source file:org.ff4j.springboot.FF4jSpringConfig.java

@Bean
public FF4j getFF4j() {

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(jdbcDriverClassName);
    dataSource.setUrl(jdbcUrl);/*  w w  w. jav  a2s.  com*/
    dataSource.setUsername(jdbcUser);
    dataSource.setPassword(jdbcPassword);
    dataSource.setConnectionProperties("useUnicode=yes;characterEncoding=UTF-8;");

    FF4j ff4j = new FF4j();
    ff4j.setFeatureStore(new FeatureStoreSpringJdbc(dataSource));
    ff4j.setPropertiesStore(new PropertyStoreSpringJdbc(dataSource));
    ff4j.audit(false);

    return ff4j;
}

From source file:org.finra.dm.dao.config.DaoEnvTestSpringModuleConfig.java

/**
 * Get a new DM data source based on an in-memory HSQLDB database. This data source is used for loading the configuration table as an environment property
 * source as well as for the JPA entity manager. It will therefore create/re-create the configuration table which is required for the former. It also
 * inserts required values for both scenarios.
 *
 * @return the test DM data source./*from   www  .j av  a  2  s .c  o m*/
 */
@Bean
public static DataSource dmDataSource() {
    // Create and return a data source that can connect directly to a JDBC URL.
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(org.h2.Driver.class.getName());
    basicDataSource.setUsername("");
    basicDataSource.setPassword("");
    basicDataSource.setUrl("jdbc:h2:mem:dmTestDb");

    // Create and populate the configuration table.
    // This is needed for all data source method calls since it is used to create the environment property source which happens before
    // JPA and other non-static beans are initialized.
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("createConfigurationTableAndData.sql"));
    DatabasePopulatorUtils.execute(resourceDatabasePopulator, basicDataSource); // This is what the DataSourceInitializer does.

    return basicDataSource;
}

From source file:org.finra.herd.dao.config.DaoEnvTestSpringModuleConfig.java

/**
 * Get a new herd data source based on an in-memory HSQLDB database. This data source is used for loading the configuration table as an environment property
 * source as well as for the JPA entity manager. It will therefore create/re-create the configuration table which is required for the former. It also
 * inserts required values for both scenarios.
 *
 * @return the test herd data source./*  w  w  w. ja  v  a 2  s. co  m*/
 */
@Bean
public static DataSource herdDataSource() {
    // Create and return a data source that can connect directly to a JDBC URL.
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(org.h2.Driver.class.getName());
    basicDataSource.setUsername("");
    basicDataSource.setPassword("");
    basicDataSource.setUrl("jdbc:h2:mem:herdTestDb");

    // Create and populate the configuration table.
    // This is needed for all data source method calls since it is used to create the environment property source which happens before
    // JPA and other non-static beans are initialized.
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("createConfigurationTableAndData.sql"));
    DatabasePopulatorUtils.execute(resourceDatabasePopulator, basicDataSource); // This is what the DataSourceInitializer does.

    return basicDataSource;
}

From source file:org.lib4j.dbcp.DataSources.java

/**
 * Create a <code>BasicDataSource</code> given a dbcp JAXB binding.
 *
 * @param dbcp JAXB dbcp binding.//from  w w  w  .j a  v  a 2 s . com
 * @param driverClassLoader Class loader to be used to load the JDBC driver.
 * @return the <code>BasicDataSource</code> instance.
 * @throws SQLException If a database access error occurs.
 */
public static BasicDataSource createDataSource(final Dbcp dbcp, final ClassLoader driverClassLoader)
        throws SQLException {
    final BasicDataSource dataSource = new BasicDataSource();

    final Dbcp.Jdbc jdbc = dbcp.getJdbc();
    dataSource.setDriverClassName(jdbc.getDriverClassName());
    dataSource.setDriverClassLoader(driverClassLoader);

    dataSource.setUrl(jdbc.getUrl());

    dataSource.setUsername(jdbc.getUsername());
    dataSource.setPassword(jdbc.getPassword());

    final Dbcp.Default _default = dbcp.getDefault();
    if (_default != null && _default.getCatalog() != null)
        dataSource.setDefaultCatalog(_default.getCatalog());

    dataSource.setDefaultAutoCommit(
            _default == null || _default.getAutoCommit() == null || _default.getAutoCommit());
    dataSource.setDefaultReadOnly(_default != null && _default.getReadOnly() != null && _default.getReadOnly());
    if (_default != null && _default.getQueryTimeout() != null)
        dataSource.setDefaultQueryTimeout(_default.getQueryTimeout());

    if (_default != null && _default.getTransactionIsolation() != null) {
        if ("NONE".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        else if ("READ_COMMITTED".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        else if ("READ_UNCOMMITTED".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        else if ("REPEATABLE_READ".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        else if ("SERIALIZABLE".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        else
            throw new UnsupportedOperationException(
                    "Unsupported transaction isolation: " + _default.getTransactionIsolation());
    }

    final Dbcp.Connection connection = dbcp.getConnection();
    if (connection != null) {
        if (connection.getProperties() != null)
            for (final Dbcp.Connection.Properties.Property property : connection.getProperties().getProperty())
                if (property.getName() != null && property.getValue() != null)
                    dataSource.addConnectionProperty(property.getName(), property.getValue());

        if (connection.getInitSqls() != null) {
            final List<String> initSqls = new ArrayList<>();
            for (final String initSql : connection.getInitSqls().getInitSql())
                initSqls.add(initSql);

            dataSource.setConnectionInitSqls(initSqls);
        }
    }

    final Dbcp.Size size = dbcp.getSize();
    dataSource.setInitialSize(size == null || size.getInitialSize() == null ? 0 : size.getInitialSize());
    dataSource.setMaxTotal(size == null || size.getMaxTotal() == null ? 8
            : INDEFINITE.equals(size.getMaxTotal()) ? -1 : Integer.parseInt(size.getMaxTotal()));
    dataSource.setMaxIdle(size == null || size.getMaxIdle() == null ? 8
            : INDEFINITE.equals(size.getMaxIdle()) ? -1 : Integer.parseInt(size.getMaxIdle()));
    dataSource.setMinIdle(size == null || size.getMinIdle() == null ? 9 : size.getMinIdle());
    if (size == null || size.getMaxOpenPreparedStatements() == null
            || INDEFINITE.equals(size.getMaxOpenPreparedStatements())) {
        dataSource.setPoolPreparedStatements(false);
    } else {
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxOpenPreparedStatements(Integer.parseInt(size.getMaxOpenPreparedStatements()));
    }

    final Dbcp.Pool pool = dbcp.getPool();
    if (pool == null || pool.getQueue() == null || "lifo".equals(pool.getQueue()))
        dataSource.setLifo(true);
    else if ("fifo".equals(pool.getQueue()))
        dataSource.setLifo(false);
    else
        throw new UnsupportedOperationException("Unsupported queue spec: " + pool.getQueue());

    dataSource.setCacheState(pool != null && pool.getCacheState() != null && pool.getCacheState());
    dataSource.setMaxWaitMillis(
            pool == null || pool.getMaxWait() != null || INDEFINITE.equals(pool.getMaxWait()) ? -1
                    : Long.parseLong(pool.getMaxWait()));
    dataSource.setMaxConnLifetimeMillis(pool == null || pool.getMaxConnectionLifetime() == null
            || INDEFINITE.equals(pool.getMaxConnectionLifetime()) ? 0
                    : Long.parseLong(pool.getMaxConnectionLifetime()));
    dataSource.setEnableAutoCommitOnReturn(_default == null || pool.getEnableAutoCommitOnReturn() == null
            || pool.getEnableAutoCommitOnReturn());
    dataSource.setRollbackOnReturn(
            pool == null || pool.getRollbackOnReturn() == null || pool.getRollbackOnReturn());
    if (pool != null && pool.getRemoveAbandoned() != null) {
        if ("borrow".equals(pool.getRemoveAbandoned().getOn()))
            dataSource.setRemoveAbandonedOnBorrow(true);
        else if ("maintenance".equals(pool.getRemoveAbandoned().getOn()))
            dataSource.setRemoveAbandonedOnMaintenance(true);
        else
            throw new UnsupportedOperationException(
                    "Unsupported remove abandoned spec: " + pool.getRemoveAbandoned().getOn());

        dataSource.setRemoveAbandonedTimeout(pool.getRemoveAbandoned().getTimeout());
    }

    dataSource.setAbandonedUsageTracking(
            pool != null && pool.getAbandonedUsageTracking() != null && pool.getAbandonedUsageTracking());
    dataSource.setAccessToUnderlyingConnectionAllowed(
            pool != null && pool.getAllowAccessToUnderlyingConnection() != null
                    && pool.getAllowAccessToUnderlyingConnection());

    final Dbcp.Pool.Eviction evictor = pool != null && pool.getEviction() != null ? pool.getEviction() : null;
    if (evictor != null) {
        dataSource.setTimeBetweenEvictionRunsMillis(evictor.getTimeBetweenRuns());
        dataSource.setNumTestsPerEvictionRun(evictor.getNumTestsPerRun());
        dataSource.setMinEvictableIdleTimeMillis(
                evictor.getMinIdleTime() == null ? 1800000 : evictor.getMinIdleTime());
        dataSource.setSoftMinEvictableIdleTimeMillis(
                evictor.getSoftMinIdleTime() == null || INDEFINITE.equals(evictor.getSoftMinIdleTime()) ? -1
                        : Long.parseLong(evictor.getSoftMinIdleTime()));
        if (evictor.getPolicyClassName() != null)
            dataSource.setEvictionPolicyClassName(evictor.getPolicyClassName());
    }

    final Dbcp.Validation validation = dbcp.getValidation();
    if (validation != null && validation.getQuery() != null)
        dataSource.setValidationQuery(validation.getQuery());

    dataSource.setTestOnBorrow(
            validation == null || validation.getTestOnBorrow() == null || validation.getTestOnBorrow());
    dataSource.setTestOnReturn(
            validation != null && validation.getTestOnReturn() != null && validation.getTestOnReturn());
    dataSource.setTestWhileIdle(
            validation != null && validation.getTestWhileIdle() != null && validation.getTestWhileIdle());
    if (validation != null && validation.getFastFail() != null) {
        dataSource.setFastFailValidation(true);
        if (validation.getFastFail().getDisconnectionSqlCodes() != null)
            dataSource.setDisconnectionSqlCodes(
                    Arrays.asList(validation.getFastFail().getDisconnectionSqlCodes().split(" ")));
    }

    final Dbcp.Logging logging = dbcp.getLogging();
    if (logging != null) {
        final Logger logger = LoggerFactory.getLogger(DataSources.class);
        final LoggerPrintWriter loggerPrintWriter = new LoggerPrintWriter(logger,
                Level.valueOf(logging.getLevel().toString()));
        dataSource.setLogWriter(loggerPrintWriter);
        dataSource.setLogExpiredConnections(logging.isLogExpiredConnections());
        if (logging.isLogAbandoned()) {
            dataSource.setAbandonedLogWriter(loggerPrintWriter);
            dataSource.setLogAbandoned(true);
        }
    }

    return dataSource;
}