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

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

Introduction

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

Prototype

BasicDataSource

Source Link

Usage

From source file:jeeves.resources.dbms.ApacheDBCPool.java

/**
 * Builds the pool using init parameters from jeeves config.
 *//*from   w  w  w .  j  av  a 2  s  .  c  o  m*/
private void parseJeevesDBConfig(Element config) throws Exception {
    url = config.getChildText(Jeeves.Res.Pool.URL);

    String user = config.getChildText(Jeeves.Res.Pool.USER);
    String passwd = config.getChildText(Jeeves.Res.Pool.PASSWORD);
    String driver = config.getChildText(Jeeves.Res.Pool.DRIVER);
    String size = config.getChildText(Jeeves.Res.Pool.POOL_SIZE);
    String maxw = config.getChildText(Jeeves.Res.Pool.MAX_WAIT);
    String maxIdle = config.getChildText(Jeeves.Res.Pool.MAX_IDLE);
    String minIdle = config.getChildText(Jeeves.Res.Pool.MIN_IDLE);
    String maxActive = config.getChildText(Jeeves.Res.Pool.MAX_ACTIVE);
    String testWhileIdleStr = config.getChildText(Jeeves.Res.Pool.TEST_WHILE_IDLE);
    String timeBetweenEvictionRunsMillisStr = config
            .getChildText(Jeeves.Res.Pool.TIME_BETWEEN_EVICTION_RUNS_MILLIS);
    String minEvictableIdleTimeMillisStr = config.getChildText(Jeeves.Res.Pool.MIN_EVICTABLE_IDLE_TIME_MILLIS);
    String numTestsPerEvictionRunStr = config.getChildText(Jeeves.Res.Pool.NUM_TESTS_PER_EVICTION_RUN);
    String validationQuery = config.getChildText(Jeeves.Res.Pool.VALIDATION_QUERY);
    String transactionIsolation = config.getChildText(Jeeves.Res.Pool.TRANSACTION_ISOLATION);
    if (transactionIsolation == null) {
        // use READ_COMMITTED for everything by default except McKoi which 
        // only supports SERIALIZABLE 
        transactionIsolation = Jeeves.Res.Pool.TRANSACTION_ISOLATION_READ_COMMITTED;
        if (url.toUpperCase().contains("MCKOI"))
            transactionIsolation = Jeeves.Res.Pool.TRANSACTION_ISOLATION_SERIALIZABLE;
    } else {
        Set<String> isolations = new HashSet<String>();
        isolations.add(Jeeves.Res.Pool.TRANSACTION_ISOLATION_SERIALIZABLE);
        isolations.add(Jeeves.Res.Pool.TRANSACTION_ISOLATION_READ_COMMITTED);
        isolations.add(Jeeves.Res.Pool.TRANSACTION_ISOLATION_REPEATABLE_READ);

        if (!isolations.contains(transactionIsolation.toUpperCase())) {
            throw new IllegalArgumentException(
                    "Invalid " + Jeeves.Res.Pool.TRANSACTION_ISOLATION + " parameter value: "
                            + transactionIsolation + ". Should be one of " + isolations.toString());
        }
    }
    warning("Using transaction isolation setting " + transactionIsolation);

    this.name = url;

    int poolSize = (size == null) ? Jeeves.Res.Pool.DEF_POOL_SIZE : Integer.parseInt(size);
    int maxWait = (maxw == null) ? Jeeves.Res.Pool.DEF_MAX_WAIT : Integer.parseInt(maxw);

    // set maximum number of prepared statements in pool cache
    int iMaxOpen = getPreparedStatementCacheSize(config);

    boolean testWhileIdle = false;
    if (testWhileIdleStr != null) {
        testWhileIdle = testWhileIdleStr.equals("true");
    }

    long timeBetweenEvictionRunsMillis = -1;
    if (timeBetweenEvictionRunsMillisStr != null) {
        timeBetweenEvictionRunsMillis = Long.parseLong(timeBetweenEvictionRunsMillisStr);
    }

    long minEvictableIdleTimeMillis = 1000 * 60 * 30;
    if (minEvictableIdleTimeMillisStr != null) {
        minEvictableIdleTimeMillis = Long.parseLong(minEvictableIdleTimeMillisStr);
    }

    int numTestsPerEvictionRun = 3;
    if (numTestsPerEvictionRunStr != null) {
        numTestsPerEvictionRun = Integer.parseInt(numTestsPerEvictionRunStr);
    }

    // create the datasource 
    basicDataSource = new BasicDataSource();

    basicDataSource.setDriverClassName(driver);

    basicDataSource.setRemoveAbandoned(true);
    basicDataSource.setRemoveAbandonedTimeout(60 * 60);
    basicDataSource.setLogAbandoned(true);

    // configure the rest of the pool from params
    // http://commons.apache.org/dbcp/configuration.html
    if (maxActive != null) {
        basicDataSource.setMaxActive(Integer.parseInt(maxActive));
    } else {
        basicDataSource.setMaxActive(poolSize);
    }
    if (maxIdle != null) {
        basicDataSource.setMaxIdle(Integer.parseInt(maxIdle));
    } else {
        basicDataSource.setMaxIdle(poolSize);
    }
    if (minIdle != null) {
        basicDataSource.setMinIdle(Integer.parseInt(minIdle));
    } else {
        basicDataSource.setMinIdle(0);
    }
    basicDataSource.setMaxWait(maxWait);

    // always test connections when we get them from the pool    
    basicDataSource.setTestOnBorrow(true);

    // time between runs of idle evictor thread                  
    basicDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    // test idle connections                    
    basicDataSource.setTestWhileIdle(testWhileIdle);
    // let idle connections sit in there forever
    basicDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    // test all idle connections each run
    basicDataSource.setNumTestsPerEvictionRun(numTestsPerEvictionRun);

    // set maximum number of prepared statements in pool cache, if not set
    // then switch it off altogether
    if (iMaxOpen != -1) {
        basicDataSource.setPoolPreparedStatements(true);
        basicDataSource.setMaxOpenPreparedStatements(iMaxOpen);
    } else {
        basicDataSource.setPoolPreparedStatements(false);
        basicDataSource.setMaxOpenPreparedStatements(-1);
    }

    if (validationQuery != null && validationQuery.trim().length() > 0) {
        basicDataSource.setValidationQuery(validationQuery);
    }
    basicDataSource.setDefaultReadOnly(false);
    basicDataSource.setDefaultAutoCommit(false);

    basicDataSource.setUrl(url);
    basicDataSource.setUsername(user);
    basicDataSource.setPassword(passwd);

    basicDataSource.setInitialSize(poolSize);

}

From source file:de.langmi.spring.batch.examples.readers.support.CompositeCursorItemReaderTest.java

/**
 * Create a HSQLDB in-memory based datasource.
 *
 * @param url/*  w  w w.j a va  2 s . c o  m*/
 * @return 
 */
private DataSource createDataSource(final String url) {
    // DataSource Setup with apache commons 
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
    dataSource.setUrl(url);
    dataSource.setUsername("sa");
    dataSource.setPassword("");

    return dataSource;
}

From source file:com.cubeia.backoffice.users.migration.MySQLMigrationAdapter.java

private void createDataSource() {
    dataSource = new BasicDataSource();
    dataSource.setUrl(get("url"));
    dataSource.setDriverClassName(get("driver"));
    dataSource.setUsername(get("username"));
    dataSource.setPassword(get("password"));
    dataSource.setMaxActive(10);//from  w w w  .j av a 2s  .  com
    dataSource.setMaxIdle(5);
    dataSource.setInitialSize(5);
    dataSource.setValidationQuery("SELECT 1");
}

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); // ???????

    // ??/*www. jav  a 2s .c o  m*/
    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:fi.ni.IFC_ClassModel.java

public void listRDF(OutputStream outputStream, String path, VirtConfig virt) throws IOException, SQLException {

    BufferedWriter out = null;//from w w  w. java2s . com
    Connection c = null;
    String prefix_query = "PREFIX : <" + path + "> " + "PREFIX instances: <http://drum.cs.hut.fi/instances#> "
            + "PREFIX owl: <" + Namespace.OWL + "> " + "PREFIX ifc: <" + Namespace.IFC + "> " + "PREFIX xsd: <"
            + Namespace.XSD + "> " + "INSERT IN GRAPH <" + path + "> { ";

    try {
        //Setup file output
        out = new BufferedWriter(new OutputStreamWriter(outputStream));
        out.write("@prefix : <" + path + ">.\n");
        out.write("@prefix instances: <http://drum.cs.hut.fi/instances#>. \n");
        out.write("@prefix owl: <" + Namespace.OWL + "> .\n");
        out.write("@prefix ifc: <" + Namespace.IFC + "> .\n");
        out.write("@prefix xsd: <" + Namespace.XSD + "> .\n");
        out.write("\n");

        //If necessary, setup virtuoso connection
        if (virt != null) {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setUsername(virt.user);
            dataSource.setPassword(virt.password);
            dataSource.setUrl(virt.jdbc_uri);
            dataSource.setMaxActive(100);
            dataSource.setDriverClassName("virtuoso.jdbc4.Driver");
            c = dataSource.getConnection();
        }

        for (Map.Entry<Long, Thing> entry : object_buffer.entrySet()) {
            Thing gobject = entry.getValue();
            String triples = generateTriples(gobject);
            out.write(triples);

            if (virt != null) {
                Statement stmt = c.createStatement();
                StringBuilder queryString = new StringBuilder();
                queryString.append(prefix_query);
                queryString.append(triples);
                queryString.append("}");
                boolean more = stmt.execute("sparql " + queryString.toString());
                if (!more) {
                    System.err.println("INSERT failed.");
                }
                if (stmt != null)
                    stmt.close();
            }
        }

    } finally {
        if (out != null)
            out.close();
        if (c != null)
            c.close();
    }
}

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

private static DataSource createByConfiguration(IConfigurationManager configurationManager, Element eConfig)
        throws DatabaseException {
    BasicDataSource ds = null;/*from ww  w. java  2 s.  com*/
    try {
        ds = new BasicDataSource();

        String sDriver = configurationManager.getParam(eConfig, "driver");
        if (sDriver == null) {
            _logger.warn("No 'driver' item found in configuration");
            throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
        }
        ds.setDriverClassName(sDriver);

        String sURL = configurationManager.getParam(eConfig, "url");
        if (sURL == null) {
            _logger.warn("No 'url' item found in configuration");
            throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
        }
        ds.setUrl(sURL);

        String sUser = configurationManager.getParam(eConfig, "username");
        if (sUser == null) {
            _logger.warn("No 'username' item found in configuration");
            throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
        }
        ds.setUsername(sUser);

        String sPassword = configurationManager.getParam(eConfig, "password");
        if (sPassword == null) {
            _logger.warn("No 'password' item found in configuration");
            throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
        }
        ds.setPassword(sPassword);

        addOptionalSettings(configurationManager, eConfig, ds);
    } catch (DatabaseException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not initialize object", e);
        throw new DatabaseException(SystemErrors.ERROR_INTERNAL);
    }
    return ds;
}

From source file:net.hydromatic.optiq.test.JdbcTest.java

/**
 * Creates a connection with a given query provider. If provider is null,
 * uses the connection as its own provider. The connection contains a
 * schema called "foodmart" backed by a JDBC connection to MySQL.
 *
 * @param queryProvider Query provider//  w  w w  . j  av  a  2 s .  c o  m
 * @param withClone Whether to create a "foodmart2" schema as in-memory
 *     clone
 * @return Connection
 * @throws ClassNotFoundException
 * @throws SQLException
 */
static OptiqConnection getConnection(QueryProvider queryProvider, boolean withClone)
        throws ClassNotFoundException, SQLException {
    Class.forName("net.hydromatic.optiq.jdbc.Driver");
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:optiq:");
    OptiqConnection optiqConnection = connection.unwrap(OptiqConnection.class);
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:mysql://localhost");
    dataSource.setUsername("foodmart");
    dataSource.setPassword("foodmart");

    JdbcSchema foodmart = JdbcSchema.create(optiqConnection.getRootSchema(), dataSource, "foodmart", null,
            "foodmart");
    if (withClone) {
        CloneSchema.create(optiqConnection.getRootSchema(), "foodmart2", foodmart);
    }
    optiqConnection.setSchema("foodmart2");
    return optiqConnection;
}

From source file:com.alibaba.druid.benckmark.pool.PoolPerformanceTest.java

@Test
public void test_dbcp() throws Exception {
    final BasicDataSource dataSource = new BasicDataSource();

    dataSource.setInitialSize(initialSize);
    dataSource.setMaxActive(maxActive);// w  w w.  j ava  2  s .  c om
    dataSource.setMinIdle(minPoolSize);
    dataSource.setMaxIdle(maxPoolSize);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(jdbcUrl);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    dataSource.setValidationQuery("SELECT 1");
    dataSource.setTestOnBorrow(false);
    System.out.println(dataSource.getClass().getSimpleName());
    for (int i = 0; i < loopCount; ++i) {
        p0(dataSource, "dbcp", threadCount);
    }
    System.out.println();
    dataSource.close();
    TestDriver.instance.reset();
}

From source file:com.emc.ecs.sync.source.AtmosSource.java

@Override
public void parseCustomOptions(CommandLine line) {
    AtmosUtil.AtmosUri atmosUri = AtmosUtil.parseUri(sourceUri);
    endpoints = atmosUri.endpoints;//from w  w  w.ja va  2s.  com
    uid = atmosUri.uid;
    secret = atmosUri.secret;
    namespaceRoot = atmosUri.rootPath;

    if (line.hasOption(SOURCE_OIDLIST_OPTION))
        oidFile = line.getOptionValue(SOURCE_OIDLIST_OPTION);

    if (line.hasOption(SOURCE_NAMELIST_OPTION))
        nameFile = line.getOptionValue(SOURCE_NAMELIST_OPTION);

    if (line.hasOption(SOURCE_SQLQUERY_OPTION)) {
        query = line.getOptionValue(SOURCE_SQLQUERY_OPTION);

        // Initialize a connection pool
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(line.getOptionValue(JDBC_URL_OPT));
        if (line.hasOption(JDBC_DRIVER_OPT))
            ds.setDriverClassName(line.getOptionValue(JDBC_DRIVER_OPT));
        ds.setUsername(line.getOptionValue(JDBC_USER_OPT));
        ds.setPassword(line.getOptionValue(JDBC_PASSWORD_OPT));
        ds.setMaxActive(200);
        ds.setMaxOpenPreparedStatements(180);
        setDataSource(ds);
    }

    deleteTags = line.hasOption(DELETE_TAGS_OPT);
}

From source file:com.test.HibernateDerbyLockingTest.java

public void testSpringWithDataSource() throws Exception {
    final BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(EmbeddedDriver.class.getName());
    dataSource.setUrl("jdbc:derby:lockingtest;create=true");
    dataSource.setUsername("sa");
    dataSource.setPassword("sa");

    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "create");
    properties.setProperty("hibernate.dialect", "org.bpmscript.hibernate.DerbyDialect");
    properties.setProperty("hibernate.show_sql", "true");

    // properties.setProperty("hibernate.connection.driver_class",
    // EmbeddedDriver.class.getName());
    // properties.setProperty("hibernate.connection.url",
    // "jdbc:derby:lockingtest;create=true");
    // properties.setProperty("hibernate.connection.username", "sa");
    // properties.setProperty("hibernate.connection.password", "sa");
    // properties.setProperty("hibernate.connection.pool_size", "10");

    final AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
    sessionFactoryBean.setLobHandler(new DefaultLobHandler());
    sessionFactoryBean.setHibernateProperties(properties);
    sessionFactoryBean.setAnnotatedClasses(new Class[] { Person.class });
    sessionFactoryBean.setDataSource(dataSource);
    sessionFactoryBean.afterPropertiesSet();

    SessionFactory sessionFactory = (SessionFactory) sessionFactoryBean.getObject();
    try {/*w  w w  .  ja v a 2 s. co  m*/
        runTest(sessionFactory);
    } finally {
        sessionFactory.close();
    }
}