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

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

Introduction

In this page you can find the example usage for org.apache.commons.dbcp 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.wso2.carbon.user.core.jdbc.PermissionTest.java

public void initRealmStuff() throws Exception {
    String dbFolder = "target/PermissionTest";
    if ((new File(dbFolder)).exists()) {
        deleteDir(new File(dbFolder));
    }/*from ww w. j  a  v a2s.c  om*/

    BasicDataSource ds = new BasicDataSource();
    // ds.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    // ds.setUrl("jdbc:derby:target/databasetest/CARBON_TEST;create=true");

    ds.setDriverClassName(UserCoreTestConstants.DB_DRIVER);
    ds.setUrl(TEST_URL);
    DatabaseCreator creator = new DatabaseCreator(ds);
    creator.createRegistryDatabase();

    realm = new DefaultRealm();

    InputStream inStream = this.getClass().getClassLoader().getResource(JDBCRealmTest.JDBC_TEST_USERMGT_XML)
            .openStream();
    RealmConfiguration realmConfig = TestRealmConfigBuilder.buildRealmConfigWithJDBCConnectionUrl(inStream,
            TEST_URL);
    realm.init(realmConfig, ClaimTestUtil.getClaimTestData(), ClaimTestUtil.getProfileTestData(), 0);
}

From source file:org.wso2.carbon.user.core.jdbc.ReadOnlyJDBCRealmTest.java

public void initRealmStuff() throws Exception {
    String dbFolder = "target/ReadOnlyTest";
    if ((new File(dbFolder)).exists()) {
        deleteDir(new File(dbFolder));
    }/*from  www .  j av  a 2  s  . co  m*/

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(UserCoreTestConstants.DB_DRIVER);
    ds.setUrl("jdbc:h2:target/ReadOnlyTest/CARBON_TEST");

    DatabaseCreator creator = new DatabaseCreator(ds);
    creator.createRegistryDatabase();

    this.addIntialData(ds);
    RealmConfigXMLProcessor builder = new RealmConfigXMLProcessor();
    InputStream inStream = this.getClass().getClassLoader().getResource("jdbc-readonly-test.xml").openStream();
    RealmConfiguration realmConfig = builder.buildRealmConfiguration(inStream);
    inStream.close();
    realm = new DefaultRealm();
    realm.init(realmConfig, ClaimTestUtil.getClaimTestData(), ClaimTestUtil.getProfileTestData(), 0);
    assertTrue(realm.getUserStoreManager().isExistingRole("adminx"));
}

From source file:org.wso2.carbon.user.core.tenant.TestTenantManager.java

public void tenantDbStuff() throws Exception {
    String dbFolder = "target/Tenanttest";
    if ((new File(dbFolder)).exists()) {
        deleteDir(new File(dbFolder));
    }/*from  ww w .j av a 2  s .co  m*/

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(UserCoreTestConstants.DB_DRIVER);
    ds.setUrl("jdbc:h2:target/Tenanttest/TEN_TEST");

    DatabaseCreator creator = new DatabaseCreator(ds);
    creator.createRegistryDatabase();
    tenantMan = new JDBCTenantManager(ds, "super.com");
}

From source file:org.wso2.throttle.core.Throttler.java

/**
 * Copies physical ThrottleTable to this instance's in-memory ThrottleTable.
 *//*w  w  w . j  a v a2 s.  co m*/
private void populateThrottleTable() {
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
    basicDataSource.setUrl("jdbc:mysql://localhost/org_wso2_throttle_DataSource");
    basicDataSource.setUsername("root");
    basicDataSource.setPassword("root");

    Connection connection = null;
    try {
        connection = basicDataSource.getConnection();
        DatabaseMetaData dbm = connection.getMetaData();
        // check if "ThrottleTable" table is there
        ResultSet tables = dbm.getTables(null, null, RDBMS_THROTTLE_TABLE_NAME, null);
        if (tables.next()) { // Table exists
            PreparedStatement stmt = connection.prepareStatement("SELECT * FROM " + RDBMS_THROTTLE_TABLE_NAME);
            ResultSet resultSet = stmt.executeQuery();
            while (resultSet.next()) {
                String key = resultSet.getString(RDBMS_THROTTLE_TABLE_COLUMN_KEY);
                Boolean isThrottled = resultSet.getBoolean(RDBMS_THROTTLE_TABLE_COLUMN_ISTHROTTLED);
                try {
                    getGlobalThrottleStreamInputHandler().send(new Object[] { key, isThrottled });
                } catch (InterruptedException e) {
                    log.error("Error occurred while sending an event.", e);
                }
            }
        } else { // Table does not exist
            log.warn("RDBMS ThrottleTable does not exist. Make sure global throttler server is started.");
        }
    } catch (SQLException e) {
        log.error("Error occurred while copying throttle data from global throttler server.", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                log.error("Error occurred while closing database connection.", e);
            }
        }
    }
}

From source file:org.xbib.io.jdbc.SQLConnectionFactory.java

/**
 * Get connection/*from  www.  ja va2  s  .  c o m*/
 *
 * @param uri
 *
 * @return an SQL connection
 *
 * @throws java.io.IOException
 */
@Override
public Connection<SQLSession> getConnection(final URI uri) throws IOException {
    this.properties = URIUtil.getPropertiesFromURI(uri);
    Context context = null;
    DataSource ds = null;
    for (String name : new String[] { "jdbc/" + properties.getProperty("host"),
            "java:comp/env/" + properties.getProperty("scheme") + ":" + properties.getProperty("host") + ":"
                    + properties.getProperty("port") }) {
        this.jndiName = name;
        try {
            context = new InitialContext();
            Object o = context.lookup(jndiName);
            if (o instanceof DataSource) {
                logger.info("DataSource ''{}'' found in naming context", jndiName);
                ds = (DataSource) o;
                break;
            } else {
                logger.warn("JNDI object {} not a DataSource class: {} - ignored", jndiName, o.getClass());
            }
        } catch (NameNotFoundException e) {
            logger.warn("DataSource ''{}'' not found in context", jndiName);
        } catch (NamingException e) {
            logger.warn(e.getMessage(), e);
        }
    }
    try {
        if (ds == null) {
            BasicDataSource bsource = new BasicDataSource();
            bsource.setDriverClassName(properties.getProperty("driverClassName"));
            String url = properties.getProperty("jdbcScheme") + properties.getProperty("host") + ":"
                    + properties.getProperty("port")
                    + ("jdbc:oracle:thin:@".equals(properties.getProperty("jdbcScheme")) ? ":" : "/")
                    + properties.getProperty("cluster");
            bsource.setUrl(url);
            if (properties.containsKey("username")) {
                bsource.setUsername(properties.getProperty("username"));
            }
            if (properties.containsKey("password")) {
                bsource.setPassword(properties.getProperty("password"));
            }
            if (properties.containsKey("n")) {
                bsource.setInitialSize(Integer.parseInt(properties.getProperty("n")));
                bsource.setMaxActive(Integer.parseInt(properties.getProperty("n")));
            }
            // Other BasicDataSource settings, not used yet:
            //  setAccessToUnderlyingConnectionAllowed(boolean allow)
            //  setDefaultAutoCommit(boolean defaultAutoCommit)
            //  setDefaultCatalog(String defaultCatalog)
            //  setDefaultReadOnly(boolean defaultReadOnly)
            //  setDefaultTransactionIsolation(int defaultTransactionIsolation)
            //  setLogAbandoned(boolean logAbandoned)
            //  setLoginTimeout(int loginTimeout)
            //  setLogWriter(PrintWriter logWriter)
            //  setMaxIdle(int maxIdle)
            //  setMaxOpenPreparedStatements(int maxOpenStatements)
            //  setMaxWait(long maxWait)
            //  setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis)
            //  setMinIdle(int minIdle)
            //  setNumTestsPerEvictionRun(int numTestsPerEvictionRun)
            //  setPoolPreparedStatements(boolean poolingStatements)
            //  setTestOnBorrow(boolean testOnBorrow)
            //  setTestOnReturn(boolean testOnReturn)
            //  setTestWhileIdle(boolean testWhileIdle)
            //  setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis)
            //  setValidationQuery(String validationQuery)
            context.bind(jndiName, bsource);
            ds = (DataSource) bsource;
        }
    } catch (NamingException e) {
        throw new IOException(e.getMessage());
    }
    try {
        ds.getConnection().setAutoCommit("false".equals(properties.getProperty("autoCommit")) ? false : true);
    } catch (SQLException e) {
        throw new IOException(e.getMessage());
    }
    return new SQLConnection(ds);
}

From source file:philaman.cput.cardealer.app.config.AppConfig.java

@Bean
public DataSource dataSource() {
    BasicDataSource ds = new org.apache.commons.dbcp.BasicDataSource();
    ds.setDriverClassName("org.apache.derby.jdbc.ClientDriver");
    ds.setUrl("jdbc:derby://localhost:1527/LimaCarDealers");
    ds.setUsername("app");
    ds.setPassword("app");
    return ds;/* w w w . ja v a  2 s.  c om*/
}

From source file:qa.qcri.nadeef.core.util.sql.DBConnectionPool.java

/**
 * Create a connection pool.//from  w  w  w.j a  v a 2 s .  com
 * @param dbconfig input DB config.
 * @return connection pool instance.
 */
public BasicDataSource createConnectionPool(DBConfig dbconfig) {
    tracer.verbose("Creating connection pool for " + dbconfig.getUrl());
    BasicDataSource result;
    result = new BasicDataSource();
    result.setUrl(dbconfig.getUrl());
    result.setDriverClassName(SQLDialectTools.getDriverName(dbconfig.getDialect()));

    String username = dbconfig.getUserName();
    if (!Strings.isNullOrEmpty(username)) {
        result.setUsername(username);
    }

    String password = dbconfig.getPassword();
    if (!Strings.isNullOrEmpty(password)) {
        result.setPassword(password);
    }

    result.setMaxActive(MAX_ACTIVE);
    result.setMaxIdle(MAX_ACTIVE * 3);
    result.setDefaultAutoCommit(false);
    return result;
}

From source file:qa.qcri.nadeef.core.utils.sql.DBConnectionPool.java

/**
 * Create a connection pool.//from w ww .  jav a 2s .c o m
 * @param dbconfig input DB config.
 * @return connection pool instance.
 */
public BasicDataSource createConnectionPool(DBConfig dbconfig) {
    tracer.fine("Creating connection pool for " + dbconfig.getUrl());
    BasicDataSource result;
    result = new BasicDataSource();
    result.setUrl(dbconfig.getUrl());
    result.setDriverClassName(SQLDialectTools.getDriverName(dbconfig.getDialect()));

    String username = dbconfig.getUserName();
    if (!Strings.isNullOrEmpty(username)) {
        result.setUsername(username);
    }

    String password = dbconfig.getPassword();
    if (!Strings.isNullOrEmpty(password)) {
        result.setPassword(password);
    }

    result.setMaxActive(MAX_ACTIVE);
    result.setMaxIdle(MAX_ACTIVE * 3);
    result.setDefaultAutoCommit(false);
    return result;
}

From source file:ro.zg.scriptdao.core.DbCommandTest.java

public void testDbCommand() throws Exception {
    DefaultCommandManager commandManager = new DefaultCommandManager("TestCommandManager");

    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName("com.mysql.jdbc.Driver");
    bds.setUrl("jdbc:mysql://127.0.0.1:3306/test");
    bds.setUsername("test");
    bds.setPassword("test");

    commandManager.setCommandLoader(new ClasspathCommandLoader(""));
    commandManager.setCommandExecutor(new DbCommandExecutor(bds));
    commandManager.setCommandBuilder(new VelocityCommandBuilder());
    commandManager.load();// w w w.  j  av a 2  s  .  c  o m
    System.out.println(commandManager.getAvailableCommands().length);

    System.out.println("Found " + commandManager.getAvailableCommands().length + " commands.");

    System.out.println("Reloading..");
    commandManager.load();
    System.out.println("After reload " + commandManager.getAvailableCommands().length);

    //      Map args = new HashMap();
    //      args.put("message_id", "3");
    //      args.put("text", "Si mesaju trei... ce fac cu viata mea?");
    //      Object resp = commandManager.executeCommand("InsertIntoMessages", args);
    //      System.out.println(resp);

    //      Map args = new HashMap();
    //      args.put("message_id", 1);
    //      args.put("service","PREPAID.EO310");
    //      args.put("exit_point", "Success");
    //      args.put("input_channel", "SMS");
    //      args.put("output_channel", "SMS");
    //      args.put("order_idx", 1);
    //      args.put("start_date", "2008-04-20");
    //      args.put("end_date", "2008-06-01");
    //      Object resp = commandManager.executeCommand("InsertIntoServicesMessages", args);
    //      System.out.println(resp);

    Map args = new HashMap();
    args.put("service", "PREPAID.EO310");
    args.put("exit_point", "Success");
    args.put("input_channel", "SMS");
    Object resp = commandManager.executeCommand("GetMessagesForService", args);
    System.out.println(resp);
}

From source file:se.unlogic.hierarchy.core.utils.DBCPUtils.java

public static BasicDataSource createConnectionPool(DataSourceDescriptor dataSourceDescriptor) {

    BasicDataSource basicDataSource = new BasicDataSource();

    basicDataSource.setDriverClassName(dataSourceDescriptor.getDriver());
    basicDataSource.setUsername(dataSourceDescriptor.getUsername());
    basicDataSource.setPassword(dataSourceDescriptor.getPassword());
    basicDataSource.setUrl(dataSourceDescriptor.getUrl());
    basicDataSource.setDefaultCatalog(dataSourceDescriptor.getDefaultCatalog());
    basicDataSource.setLogAbandoned(dataSourceDescriptor.logAbandoned());
    basicDataSource.setRemoveAbandoned(dataSourceDescriptor.removeAbandoned());

    if (dataSourceDescriptor.getRemoveTimeout() != null) {
        basicDataSource.setRemoveAbandonedTimeout(dataSourceDescriptor.getRemoveTimeout());
    }/*from w w  w . j a v a 2s  . c o m*/

    basicDataSource.setTestOnBorrow(dataSourceDescriptor.testOnBorrow());
    basicDataSource.setValidationQuery(dataSourceDescriptor.getValidationQuery());
    basicDataSource.setMaxWait(dataSourceDescriptor.getMaxWait());
    basicDataSource.setMaxActive(dataSourceDescriptor.getMaxActive());
    basicDataSource.setMaxIdle(dataSourceDescriptor.getMaxIdle());
    basicDataSource.setMinIdle(dataSourceDescriptor.getMinIdle());

    return basicDataSource;
}