Example usage for org.apache.commons.dbcp BasicDataSource setValidationQuery

List of usage examples for org.apache.commons.dbcp BasicDataSource setValidationQuery

Introduction

In this page you can find the example usage for org.apache.commons.dbcp BasicDataSource setValidationQuery.

Prototype

public synchronized void setValidationQuery(String validationQuery) 

Source Link

Document

Sets the #validationQuery .

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

Usage

From source file:cn.cuizuoli.gotour.config.DataSourceConfig.java

@Bean
public DataSource slaveDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(env.getRequiredProperty("gotour.slave.jdbc.driverClassName"));
    dataSource.setUrl(env.getRequiredProperty("gotour.slave.jdbc.url"));
    dataSource.setUsername(env.getRequiredProperty("gotour.slave.jdbc.username"));
    dataSource.setPassword(env.getRequiredProperty("gotour.slave.jdbc.password"));
    dataSource.setInitialSize(env.getRequiredProperty("jdbc.initialSize", Integer.class));
    dataSource.setMaxActive(env.getRequiredProperty("jdbc.maxActive", Integer.class));
    dataSource.setMaxIdle(env.getRequiredProperty("jdbc.maxIdle", Integer.class));
    dataSource.setMinIdle(env.getRequiredProperty("jdbc.minIdle", Integer.class));
    dataSource.setDefaultAutoCommit(env.getRequiredProperty("jdbc.defaultAutoCommit", Boolean.class));
    dataSource.setPoolPreparedStatements(env.getRequiredProperty("jdbc.poolPreparedStatements", Boolean.class));
    dataSource.setValidationQuery(env.getRequiredProperty("jdbc.validationQuery"));
    dataSource.setTestOnBorrow(env.getRequiredProperty("jdbc.testOnBorrow", Boolean.class));
    dataSource.setTestOnReturn(env.getRequiredProperty("jdbc.testOnReturn", Boolean.class));
    dataSource.setTestWhileIdle(env.getRequiredProperty("jdbc.testWhileIdle", Boolean.class));
    dataSource.setTimeBetweenEvictionRunsMillis(
            env.getRequiredProperty("jdbc.timeBetweenEvictionRunsMillis", Long.class));
    dataSource.setNumTestsPerEvictionRun(env.getRequiredProperty("jdbc.numTestsPerEvictionRun", Integer.class));
    dataSource.setMinEvictableIdleTimeMillis(
            env.getRequiredProperty("jdbc.minEvictableIdleTimeMillis", Long.class));
    return dataSource;
}

From source file:com.ibatis.common.jdbc.DbcpConfiguration.java

private BasicDataSource legacyDbcpConfiguration(Map map) {
    BasicDataSource basicDataSource = null;
    if (map.containsKey("JDBC.Driver")) {
        basicDataSource = new BasicDataSource();
        String driver = (String) map.get("JDBC.Driver");
        String url = (String) map.get("JDBC.ConnectionURL");
        String username = (String) map.get("JDBC.Username");
        String password = (String) map.get("JDBC.Password");
        String validationQuery = (String) map.get("Pool.ValidationQuery");
        String maxActive = (String) map.get("Pool.MaximumActiveConnections");
        String maxIdle = (String) map.get("Pool.MaximumIdleConnections");
        String maxWait = (String) map.get("Pool.MaximumWait");

        basicDataSource.setUrl(url);//  w  ww.  j  av a2  s .co  m
        basicDataSource.setDriverClassName(driver);
        basicDataSource.setUsername(username);
        basicDataSource.setPassword(password);

        if (notEmpty(validationQuery)) {
            basicDataSource.setValidationQuery(validationQuery);
        }

        if (notEmpty(maxActive)) {
            basicDataSource.setMaxActive(Integer.parseInt(maxActive));
        }

        if (notEmpty(maxIdle)) {
            basicDataSource.setMaxIdle(Integer.parseInt(maxIdle));
        }

        if (notEmpty(maxWait)) {
            basicDataSource.setMaxWait(Integer.parseInt(maxWait));
        }

        Iterator props = map.keySet().iterator();
        while (props.hasNext()) {
            String propertyName = (String) props.next();
            if (propertyName.startsWith(ADD_DRIVER_PROPS_PREFIX)) {
                String value = (String) map.get(propertyName);
                basicDataSource.addConnectionProperty(propertyName.substring(ADD_DRIVER_PROPS_PREFIX_LENGTH),
                        value);
            }
        }
    }
    return basicDataSource;
}

From source file:net.firejack.platform.model.config.hibernate.HibernateFactoryBean.java

private void buildHibernateTransactionManager() {
    for (Map.Entry<String, Database> entry : databases.entrySet()) {
        String name = entry.getKey();
        Database database = entry.getValue();

        BasicDataSource dataSource = null;
        try {//from  w w w. ja  va 2  s  .  co  m
            dataSource = context.getBean(name + HIBERNATE_DATA_SOURCE_SUFFIX, BasicDataSource.class);
        } catch (BeansException e) {
            logger.info("Manual Hibernate DataSource: " + name + HIBERNATE_DATA_SOURCE_SUFFIX
                    + " not found use default");
        }

        if (dataSource == null) {
            dataSource = defaultHibernate.getBean(HIBERNATE_DEFAULT_PREFIX + HIBERNATE_DATA_SOURCE_SUFFIX,
                    BasicDataSource.class);
            dataSource.setDriverClassName(database.type.getDriver());
            dataSource.setUrl(database.getUrl());
            dataSource.setUsername(database.getUsername());
            dataSource.setPassword(database.getPassword());
            dataSource.setValidationQuery(database.getType().getValidate());

            context.getBeanFactory().registerSingleton(name + HIBERNATE_DATA_SOURCE_SUFFIX, dataSource);
        }

        Properties properties = null;
        try {
            properties = context.getBean(name + HIBERNATE_PROPERTIES_SUFFIX, Properties.class);
        } catch (BeansException e) {
            logger.info("Manual Hibernate properties: " + name + HIBERNATE_PROPERTIES_SUFFIX
                    + " not found use default");
        }

        if (properties == null) {
            properties = defaultHibernate.getBean(HIBERNATE_DEFAULT_PREFIX + HIBERNATE_PROPERTIES_SUFFIX,
                    Properties.class);
            properties.put(Environment.DIALECT, database.getType().getDialect());

            context.getBeanFactory().registerSingleton(name + HIBERNATE_PROPERTIES_SUFFIX, properties);
        }

        SessionFactory sessionFactory = null;
        try {
            sessionFactory = context.getBean(name + HIBERNATE_SESSION_FACTORY_SUFFIX, SessionFactory.class);
        } catch (BeansException e) {
            logger.info("Manual Hibernate Session Factory: " + name + HIBERNATE_SESSION_FACTORY_SUFFIX
                    + " not found use default");
        }

        if (sessionFactory == null) {
            try {
                AnnotationSessionFactoryBean annotationSessionFactoryBean = new AnnotationSessionFactoryBean();
                annotationSessionFactoryBean.setAnnotatedClasses(new Class[] { BaseEntityModel.class });
                annotationSessionFactoryBean.setDataSource(dataSource);
                annotationSessionFactoryBean.setHibernateProperties(properties);
                annotationSessionFactoryBean.setPackagesToScan(database.getScanPackages());
                annotationSessionFactoryBean.setNamingStrategy(new OpenFlameNamingStrategy(database.getType()));

                if (database.getType() == DatabaseName.MySQL || database.getType() == DatabaseName.MSSQL) {
                    annotationSessionFactoryBean.setLobHandler(new DefaultLobHandler());
                } else if (database.getType() == DatabaseName.Oracle) {
                    annotationSessionFactoryBean.setLobHandler(new OracleLobHandler());
                }

                disposableBeans.add(annotationSessionFactoryBean);
                annotationSessionFactoryBean.afterPropertiesSet();
                sessionFactory = annotationSessionFactoryBean.getObject();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }

        HibernateTemplate template = new HibernateTemplate();
        template.setSessionFactory(sessionFactory);

        context.getBeanFactory().registerSingleton(name + HIBERNATE_TEMPLATE_PREFIX, template);
        database.setHibernateSupport(template);
        logger.info("Initialize Hibernate support for stories: " + database);

        String beanName = name + HIBERNATE_TRANSACTION_MANAGER_SUFFIX;

        ConstructorArgumentValues values = new ConstructorArgumentValues();
        values.addGenericArgumentValue(sessionFactory);

        RootBeanDefinition definition = new RootBeanDefinition(HibernateTransactionManager.class);
        definition.setConstructorArgumentValues(values);
        registers.put(beanName, definition);

        Collection<HibernateSupport> stores = database.getStores();
        for (HibernateSupport store : stores) {
            targets.put(((Advised) store).getTargetClass(), beanName);
        }
    }
}

From source file:jetsennet.orm.datasource.DbcpDataSourceCreator.java

@Override
public DataSource createDatasource(ConnectionInfo conn, DbPoolInfo props) throws SQLException {
    org.apache.commons.dbcp.BasicDataSource dataSource = new org.apache.commons.dbcp.BasicDataSource();
    dataSource.setDriverClassName(conn.driver);
    dataSource.setUrl(conn.url);//w w w.  ja va2  s.  c  o  m
    dataSource.setUsername(conn.user);
    dataSource.setPassword(conn.pwd);

    String connectionProperties = props.get("connectionProperties");
    if (connectionProperties != null && connectionProperties.trim().length() > 0) {
        dataSource.setConnectionProperties(connectionProperties);
    }
    Boolean defaultAutoCommit = Utils.str2Boolean(props.get("defaultAutoCommit"));
    if (defaultAutoCommit != null) {
        dataSource.setDefaultAutoCommit(defaultAutoCommit);
    }
    Boolean defaultReadOnly = Utils.str2Boolean(props.get("defaultReadOnly"));
    if (defaultReadOnly != null) {
        dataSource.setDefaultReadOnly(defaultReadOnly);
    }
    Integer defaultTransactionIsolation = Utils.strToInteger(props.get("defaultTransactionIsolation"));
    if (defaultTransactionIsolation != null) {
        dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
    }
    String defaultCatalog = props.get("defaultCatalog");
    if (defaultCatalog != null && defaultCatalog.trim().length() > 0) {
        dataSource.setDefaultCatalog(defaultCatalog);
    }

    int initialSize = Utils.strToInt(props.get("initialSize"));
    if (initialSize > 0) {
        dataSource.setInitialSize(initialSize);
    }
    int maxActive = Utils.strToInt(props.get("maxActive"));
    if (maxActive > 0) {
        dataSource.setMaxActive(maxActive);
    }
    int maxIdle = Utils.strToInt(props.get("maxIdle"));
    if (maxIdle > 0) {
        dataSource.setMaxIdle(maxIdle);
    }
    int minIdle = Utils.strToInt(props.get("minIdle"));
    if (minIdle > 0) {
        dataSource.setMinIdle(minIdle);
    }
    int maxWait = Utils.strToInt(props.get("maxWait"));
    if (maxWait > 0) {
        dataSource.setMaxWait(maxWait);
    }

    String validationQuery = props.get("validationQuery");
    if (validationQuery != null && validationQuery.trim().length() > 0) {
        dataSource.setValidationQuery(validationQuery);
    }
    Integer validationQueryTimeout = Utils.strToInteger(props.get("validationQueryTimeout"));
    if (validationQueryTimeout != null) {
        dataSource.setValidationQueryTimeout(validationQueryTimeout);
    }
    Boolean testOnBorrow = Utils.str2Boolean(props.get("testOnBorrow"));
    if (testOnBorrow != null) {
        dataSource.setTestOnBorrow(testOnBorrow);
    }
    Boolean testOnReturn = Utils.str2Boolean(props.get("testOnReturn"));
    if (testOnReturn != null) {
        dataSource.setTestOnReturn(testOnReturn);
    }
    Boolean testWhileIdle = Utils.str2Boolean(props.get("testWhileIdle"));
    if (testWhileIdle != null) {
        dataSource.setTestWhileIdle(testWhileIdle);
    }
    Integer timeBetweenEvictionRunsMillis = Utils.strToInteger(props.get("timeBetweenEvictionRunsMillis"));
    if (timeBetweenEvictionRunsMillis != null) {
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    }
    Integer numTestsPerEvictionRun = Utils.strToInteger(props.get("numTestsPerEvictionRun"));
    if (numTestsPerEvictionRun != null) {
        dataSource.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    }
    int minEvictableIdleTimeMillis = Utils.strToInt(props.get("minEvictableIdleTimeMillis"));
    if (minEvictableIdleTimeMillis > 0) {
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    }

    Boolean removeAbandoned = Utils.str2Boolean(props.get("removeAbandoned"));
    if (removeAbandoned != null) {
        dataSource.setRemoveAbandoned(removeAbandoned);
    }
    int removeAbandonedTimeout = Utils.strToInt(props.get("removeAbandonedTimeout"));
    if (removeAbandonedTimeout > 0) {
        dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
    }
    Boolean logAbandoned = Utils.str2Boolean(props.get("logAbandoned"));
    if (logAbandoned != null) {
        dataSource.setLogAbandoned(logAbandoned);
    }
    return dataSource;
}

From source file:com.alibaba.otter.node.etl.common.datasource.impl.DBDataSourceService.java

private DataSource createDataSource(String url, String userName, String password, String driverClassName,
        DataMediaType dataMediaType, String encoding) {
    BasicDataSource dbcpDs = new BasicDataSource();

    dbcpDs.setInitialSize(initialSize);// ?
    dbcpDs.setMaxActive(maxActive);// ?????
    dbcpDs.setMaxIdle(maxIdle);// ??
    dbcpDs.setMinIdle(minIdle);// ?0?
    dbcpDs.setMaxWait(maxWait);// ??-1?
    dbcpDs.setRemoveAbandoned(true);// ??removeAbandonedTimeout
    dbcpDs.setLogAbandoned(true);// ??
    dbcpDs.setRemoveAbandonedTimeout(removeAbandonedTimeout); // ?
    dbcpDs.setNumTestsPerEvictionRun(numTestsPerEvictionRun);// ??
    dbcpDs.setTestOnBorrow(false);// ??
    dbcpDs.setTestOnReturn(false);// ??
    dbcpDs.setTestWhileIdle(true);// ????
    dbcpDs.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); // ????????
    dbcpDs.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); // ???????

    // ??/*from  w  ww  .  j av a 2  s.com*/
    dbcpDs.setDriverClassName(driverClassName);
    dbcpDs.setUrl(url);
    dbcpDs.setUsername(userName);
    dbcpDs.setPassword(password);

    if (dataMediaType.isOracle()) {
        dbcpDs.addConnectionProperty("restrictGetTables", "true");
        dbcpDs.setValidationQuery("select 1 from dual");
    } else if (dataMediaType.isMysql()) {
        // open the batch mode for mysql since 5.1.8
        dbcpDs.addConnectionProperty("useServerPrepStmts", "false");
        dbcpDs.addConnectionProperty("rewriteBatchedStatements", "true");
        dbcpDs.addConnectionProperty("zeroDateTimeBehavior", "convertToNull");// 0000-00-00null
        dbcpDs.addConnectionProperty("yearIsDateType", "false");// ??year?date?
        dbcpDs.addConnectionProperty("noDatetimeStringSync", "true");// ,???
        if (StringUtils.isNotEmpty(encoding)) {
            if (StringUtils.equalsIgnoreCase(encoding, "utf8mb4")) {
                dbcpDs.addConnectionProperty("characterEncoding", "utf8");
                dbcpDs.setConnectionInitSqls(Arrays.asList("set names utf8mb4"));
            } else {
                dbcpDs.addConnectionProperty("characterEncoding", encoding);
            }
        }
        dbcpDs.setValidationQuery("select 1");
    } else {
        logger.error("ERROR ## Unknow database type");
    }

    return dbcpDs;
}

From source file:com.alibaba.otter.common.push.datasource.media.MediaPushDataSource.java

protected DataSource doCreateDataSource(String url) {
    BasicDataSource dbcpDs = new BasicDataSource();

    dbcpDs.setInitialSize(initialSize);// ?
    dbcpDs.setMaxActive(maxActive);// ?????
    dbcpDs.setMaxIdle(maxIdle);// ??
    dbcpDs.setMinIdle(minIdle);// ?0?
    dbcpDs.setMaxWait(maxWait);// ??-1?
    dbcpDs.setRemoveAbandoned(true);// ??removeAbandonedTimeout
    dbcpDs.setLogAbandoned(true);// ??
    dbcpDs.setRemoveAbandonedTimeout(removeAbandonedTimeout); // ?
    dbcpDs.setNumTestsPerEvictionRun(numTestsPerEvictionRun);// ??
    dbcpDs.setTestOnBorrow(false);// ??
    dbcpDs.setTestOnReturn(false);// ??
    dbcpDs.setTestWhileIdle(true);// ????
    dbcpDs.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); // ????????
    dbcpDs.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); // ???????

    // ??//from  w  w w.j  ava  2 s . com
    dbcpDs.setDriverClassName(driverClassName);
    dbcpDs.setUrl(url);
    dbcpDs.setUsername(userName);
    dbcpDs.setPassword(password);

    if (dataMediaType.isOracle()) {
        dbcpDs.addConnectionProperty("restrictGetTables", "true");
        dbcpDs.setValidationQuery("select 1 from dual");
    } else if (dataMediaType.isMysql()) {
        // open the batch mode for mysql since 5.1.8
        dbcpDs.addConnectionProperty("useServerPrepStmts", "false");
        dbcpDs.addConnectionProperty("rewriteBatchedStatements", "true");
        dbcpDs.addConnectionProperty("zeroDateTimeBehavior", "convertToNull");// 0000-00-00null
        dbcpDs.addConnectionProperty("yearIsDateType", "false");// ??year?date?
        if (StringUtils.isNotEmpty(encoding)) {
            dbcpDs.addConnectionProperty("characterEncoding", encoding);
        }
        dbcpDs.setValidationQuery("select 1");
    } else {
        logger.error("ERROR ## Unknow database type");
    }

    return dbcpDs;
}

From source file:net.comze.framework.orm.datasource.DbcpDataSourceFactory.java

private BasicDataSource initialize(Properties properties) {
    ObjectUtils.notNull(properties, "properties");
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(properties.getProperty(JDBC_DRIVER));
    basicDataSource.setUrl(properties.getProperty(JDBC_URL));
    basicDataSource.setUsername(properties.getProperty(JDBC_USERNAME));
    basicDataSource.setPassword(properties.getProperty(JDBC_PASSWORD));

    if (properties.containsKey(DBCP_INITIALSIZE)) {
        basicDataSource.setInitialSize(Integer.parseInt(properties.getProperty(DBCP_INITIALSIZE)));
    }//w w w . j  a va  2  s .com
    if (properties.containsKey(DBCP_MAXACTIVE)) {
        basicDataSource.setMaxActive(Integer.parseInt(properties.getProperty(DBCP_MAXACTIVE)));
    }
    if (properties.containsKey(DBCP_MAXIDLE)) {
        basicDataSource.setMaxIdle(Integer.parseInt(properties.getProperty(DBCP_MAXIDLE)));
    }
    if (properties.containsKey(DBCP_MAXWAIT)) {
        basicDataSource.setMaxWait(Long.parseLong(properties.getProperty(DBCP_MAXWAIT)));
    }
    if (properties.containsKey(DBCP_MINEVICTABLEIDLETIMEMILLIS)) {
        basicDataSource.setMinEvictableIdleTimeMillis(
                Long.parseLong(properties.getProperty(DBCP_MINEVICTABLEIDLETIMEMILLIS)));
    }
    if (properties.containsKey(DBCP_MINIDLE)) {
        basicDataSource.setMinIdle(Integer.parseInt(properties.getProperty(DBCP_MINIDLE)));
    }
    if (properties.containsKey(DBCP_NUMTESTSPEREVICTIONRUN)) {
        basicDataSource.setNumTestsPerEvictionRun(
                Integer.parseInt(properties.getProperty(DBCP_NUMTESTSPEREVICTIONRUN)));
    }
    if (properties.containsKey(DBCP_REMOVEABANDONED)) {
        basicDataSource.setRemoveAbandoned(Boolean.parseBoolean(properties.getProperty(DBCP_REMOVEABANDONED)));
    }
    if (properties.containsKey(DBCP_REMOVEABANDONEDTIMEOUT)) {
        basicDataSource.setRemoveAbandonedTimeout(
                Integer.parseInt(properties.getProperty(DBCP_REMOVEABANDONEDTIMEOUT)));
    }
    if (properties.containsKey(DBCP_TESTONBORROW)) {
        basicDataSource.setTestOnBorrow(Boolean.parseBoolean(properties.getProperty(DBCP_TESTONBORROW)));
    }
    if (properties.containsKey(DBCP_TESTONCREATE)) {
        basicDataSource.setTestOnReturn(Boolean.parseBoolean(properties.getProperty(DBCP_TESTONCREATE)));
    }
    if (properties.containsKey(DBCP_TESTONRETURN)) {
        basicDataSource.setTestOnReturn(Boolean.parseBoolean(properties.getProperty(DBCP_TESTONRETURN)));
    }
    if (properties.containsKey(DBCP_TESTWHILEIDLE)) {
        basicDataSource.setTestWhileIdle(Boolean.parseBoolean(properties.getProperty(DBCP_TESTWHILEIDLE)));
    }
    if (properties.containsKey(DBCP_TIMEBETWEENEVICTIONRUNSMILLIS)) {
        basicDataSource.setTimeBetweenEvictionRunsMillis(
                Long.parseLong(properties.getProperty(DBCP_TIMEBETWEENEVICTIONRUNSMILLIS)));
    }
    if (properties.containsKey(DBCP_VALIDATIONQUERY)) {
        basicDataSource.setValidationQuery(properties.getProperty(DBCP_VALIDATIONQUERY));
    }
    if (properties.containsKey(DBCP_VALIDATIONQUERYTIMEOUT)) {
        basicDataSource.setValidationQueryTimeout(
                Integer.parseInt(properties.getProperty(DBCP_VALIDATIONQUERYTIMEOUT)));
    }
    return basicDataSource;
}

From source file:com.alfaariss.oa.util.database.jdbc.DataSourceFactory.java

private static DataSource addOptionalSettings(IConfigurationManager configurationManager, Element eConfig,
        BasicDataSource dataSource) throws DatabaseException {
    try {//from   www  .  j  a  va 2  s  . c  o  m
        String sMaxActive = configurationManager.getParam(eConfig, "maxactive");
        int iMaxActive = -1;
        if (sMaxActive != null) {
            try {
                iMaxActive = Integer.parseInt(sMaxActive);
            } catch (NumberFormatException e) {
                _logger.error("Wrong 'maxactive' item found in configuration: " + sMaxActive, e);
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }
        }
        dataSource.setMaxActive(iMaxActive);

        String sMaxIdle = configurationManager.getParam(eConfig, "maxidle");
        if (sMaxIdle != null) {
            int iMaxIdle = -1;
            try {
                iMaxIdle = Integer.parseInt(sMaxIdle);
            } catch (NumberFormatException e) {
                _logger.error("Wrong 'maxidle' item found in configuration: " + sMaxIdle, e);
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }
            dataSource.setMaxIdle(iMaxIdle);
        }

        String sMaxWait = configurationManager.getParam(eConfig, "maxwait");
        if (sMaxWait != null) {
            int iMaxWait = -1;
            try {
                iMaxWait = Integer.parseInt(sMaxWait);
            } catch (NumberFormatException e) {
                _logger.error("Wrong 'maxwait' item found in configuration: " + sMaxWait, e);
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }
            dataSource.setMaxWait(iMaxWait);
        }

        String sTestOnBorrow = configurationManager.getParam(eConfig, "testonborrow");
        if (sTestOnBorrow != null) {
            boolean bTestOnBorrow = false;
            if (sTestOnBorrow.equalsIgnoreCase("true"))
                bTestOnBorrow = true;
            else if (!sTestOnBorrow.equalsIgnoreCase("false")) {
                _logger.error("Wrong 'testonborrow' item found in configuration: " + sTestOnBorrow);
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }
            dataSource.setTestOnBorrow(bTestOnBorrow);
        }

        String sTestOnReturn = configurationManager.getParam(eConfig, "testonreturn");
        if (sTestOnReturn != null) {
            boolean bTestOnReturn = false;
            if (sTestOnReturn.equalsIgnoreCase("true"))
                bTestOnReturn = true;
            else if (!sTestOnReturn.equalsIgnoreCase("false")) {
                _logger.error("Wrong 'testonreturn' item found in configuration: " + sTestOnReturn);
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }
            dataSource.setTestOnReturn(bTestOnReturn);
        }

        String sTimeBetweenEvictionRunsMillis = configurationManager.getParam(eConfig,
                "timebetweenevictionrunsmillis");
        if (sTimeBetweenEvictionRunsMillis != null) {
            try {
                long lTimeBetweenEvictionRunsMillis = Long.parseLong(sTimeBetweenEvictionRunsMillis);
                dataSource.setTimeBetweenEvictionRunsMillis(lTimeBetweenEvictionRunsMillis);
            } catch (NumberFormatException e) {
                _logger.error("Wrong 'timebetweenevictionrunsmillis' item found in configuration: "
                        + sTimeBetweenEvictionRunsMillis, e);
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }
        }

        String sNumTestsPerEvictionRun = configurationManager.getParam(eConfig, "numtestsperevictionrun");
        if (sNumTestsPerEvictionRun != null) {
            int iNumTestsPerEvictionRun = -1;
            try {
                iNumTestsPerEvictionRun = Integer.parseInt(sNumTestsPerEvictionRun);
            } catch (NumberFormatException e) {
                _logger.error("Wrong 'numtestsperevictionrun' item found in configuration: "
                        + sNumTestsPerEvictionRun, e);
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }
            dataSource.setNumTestsPerEvictionRun(iNumTestsPerEvictionRun);
        }

        String sMinEvictableIdleTimeMillis = configurationManager.getParam(eConfig,
                "minevictableidletimemillis");
        if (sMinEvictableIdleTimeMillis != null) {
            try {
                long lMinEvictableIdleTimeMillis = Long.parseLong(sMinEvictableIdleTimeMillis);
                dataSource.setMinEvictableIdleTimeMillis(lMinEvictableIdleTimeMillis);
            } catch (NumberFormatException e) {
                _logger.error("Wrong 'minevictableidletimemillis' item found in configuration: "
                        + sMinEvictableIdleTimeMillis, e);
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }
        }

        String sTestWhileIdle = configurationManager.getParam(eConfig, "testwhileidle");
        if (sTestWhileIdle != null) {
            boolean bTestWhileIdle = false;
            if (sTestWhileIdle.equalsIgnoreCase("true"))
                bTestWhileIdle = true;
            else if (!sTestWhileIdle.equalsIgnoreCase("false")) {
                _logger.error("Wrong 'testwhileidle' item found in configuration: " + sTestWhileIdle);
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }
            dataSource.setTestWhileIdle(bTestWhileIdle);
        }

        String sValidationQuery = configurationManager.getParam(eConfig, "validationquery");
        if (sValidationQuery != null) {
            dataSource.setValidationQuery(sValidationQuery);
        }

    } catch (DatabaseException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not create datasource", e);
        throw new DatabaseException(SystemErrors.ERROR_INTERNAL);
    }
    return dataSource;
}

From source file:org.apache.jackrabbit.core.util.db.ConnectionFactory.java

/**
 * Registers a number of data sources./*from  ww w. ja  va2s  .c  o m*/
 *
 * @param dsc the {@link DataSourceConfig} which contains the configuration
 */
public void registerDataSources(DataSourceConfig dsc) throws RepositoryException {
    synchronized (lock) {
        sanityCheck();
        for (DataSourceDefinition def : dsc.getDefinitions()) {
            Class<?> driverClass = getDriverClass(def.getDriver());
            if (driverClass != null && Context.class.isAssignableFrom(driverClass)) {
                DataSource ds = getJndiDataSource((Class<Context>) driverClass, def.getUrl());
                nameToDataSource.put(def.getLogicalName(), ds);
                nameToDataSourceDef.put(def.getLogicalName(), def);
            } else {
                BasicDataSource bds = getDriverDataSource(driverClass, def.getUrl(), def.getUser(),
                        def.getPassword());
                if (def.getMaxPoolSize() > 0) {
                    bds.setMaxActive(def.getMaxPoolSize());
                }
                if (def.getValidationQuery() != null && !"".equals(def.getValidationQuery().trim())) {
                    bds.setValidationQuery(def.getValidationQuery());
                }
                nameToDataSource.put(def.getLogicalName(), bds);
                nameToDataSourceDef.put(def.getLogicalName(), def);
            }
        }
    }
}

From source file:org.apache.jackrabbit.core.util.db.ConnectionFactory.java

/**
 * Creates and returns a pooling JDBC {@link DataSource} for accessing
 * the database identified by the given driver class and JDBC
 * connection URL. The driver class can be <code>null</code> if
 * a specific driver has not been configured.
 *
 * @param driverClass the JDBC driver class, or <code>null</code>
 * @param url the JDBC connection URL/*from  w  w  w .j a va 2 s .c  om*/
 * @return pooling DataSource for accessing the specified database
 */
private BasicDataSource getDriverDataSource(Class<?> driverClass, String url, String user, String password) {
    BasicDataSource ds = new BasicDataSource();
    created.add(ds);

    if (driverClass != null) {
        Driver instance = null;
        try {
            // Workaround for Apache Derby:
            // The JDBC specification recommends the Class.forName
            // method without the .newInstance() method call,
            // but it is required after a Derby 'shutdown'
            instance = (Driver) driverClass.newInstance();
        } catch (Throwable e) {
            // Ignore exceptions as there's no requirement for
            // a JDBC driver class to have a public default constructor
        }
        if (instance != null) {
            if (instance.jdbcCompliant()) {
                // JCR-3445 At the moment the PostgreSQL isn't compliant because it doesn't implement this method...                   
                ds.setValidationQueryTimeout(3);
            }
        }
        ds.setDriverClassName(driverClass.getName());
    }

    ds.setUrl(url);
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setDefaultAutoCommit(true);
    ds.setTestOnBorrow(false);
    ds.setTestWhileIdle(true);
    ds.setTimeBetweenEvictionRunsMillis(600000); // 10 Minutes
    ds.setMinEvictableIdleTimeMillis(60000); // 1 Minute
    ds.setMaxActive(-1); // unlimited
    ds.setMaxIdle(GenericObjectPool.DEFAULT_MAX_IDLE + 10);
    ds.setValidationQuery(guessValidationQuery(url));
    ds.setAccessToUnderlyingConnectionAllowed(true);
    ds.setPoolPreparedStatements(true);
    ds.setMaxOpenPreparedStatements(-1); // unlimited
    return ds;
}