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

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

Introduction

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

Prototype

public synchronized void setUrl(String url) 

Source Link

Document

Sets the #url .

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

Usage

From source file:cz.muni.fi.pv168.project.hotelmanager.RoomManagerImplTest.java

@Before
public void setUp() throws SQLException {

    BasicDataSource bds = new BasicDataSource();
    //set JDBC driver and URL
    bds.setDriverClassName(EmbeddedDriver.class.getName());
    bds.setUrl("jdbc:derby:memory:TestRoomManagerDB;create=true");
    //populate db with tables and data
    new ResourceDatabasePopulator(new ClassPathResource("schema-javadb.sql")).execute(bds);
    this.dataSource = bds;
    manager = new RoomManagerImpl(bds);

}

From source file:com.zaxxer.hikari.benchmark.BenchBase.java

private void setupDBCP2basic() throws SQLException {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(dbDriver);/*from ww  w. ja  v  a2s  . c  o  m*/
    ds.setUsername("sa");
    ds.setPassword("");
    ds.setUrl(jdbcURL);
    ds.setMaxTotal(maxPoolSize);
    ds.setDefaultAutoCommit(false);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    ds.getConnection().createStatement().execute("CREATE TABLE IF NOT EXISTS test (column varchar);");
    DS = ds;
}

From source file:moviemanager.backend.SpringConfig.java

@Bean
public DataSource dataSource() {
    /*BasicDataSource bds = new BasicDataSource(); //Apache DBCP connection pooling DataSource
    bds.setDriverClassName(env.getProperty("jdbc.driver"));
    bds.setUrl(env.getProperty("jdbc.url"));
    bds.setUsername(env.getProperty("jdbc.user"));
    bds.setPassword(env.getProperty("jdbc.password"));
    return bds;*//* w  w  w.  j a v  a  2s.  com*/
    /*Properties conf = new Properties();
    BasicDataSource ds = new BasicDataSource();
    try {            
        conf.load(SpringConfig.class.getResourceAsStream("/myconf.properties"));            
    } catch (IOException ex) {
    //log.error("Loading properties has failed!");
    }
    try {
        DriverManager.getConnection(conf.getProperty("jdbc.url"));
            
    } catch (SQLException ex) {
        try {
            Connection conn = DriverManager.getConnection(conf.getProperty("jdbc.url"), conf.getProperty("jdbc.user"), conf.getProperty("jdbc.password"));
            //Connection conn = DriverManager.getConnection("org.apache.jdbc.ClientDriver" + "create=true;", "administrator", "admin");
        } catch (SQLException ex1) {
            Logger.getLogger(SpringConfig.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }
            
    ds.setUrl(conf.getProperty("jdbc.url"));      
            
    return ds;*/
    Properties conf = new Properties();
    BasicDataSource ds = new BasicDataSource();
    try {
        conf.load(SpringConfig.class.getResourceAsStream("/myconf.properties"));
    } catch (IOException ex) {
        //log.error("Loading properties has failed!");
    }
    ds.setUrl(conf.getProperty("jdbc.url"));
    ds.setDriverClassName(conf.getProperty("jdbc.driver"));
    ds.setUsername(conf.getProperty("jdbc.user"));
    ds.setPassword(conf.getProperty("jdbc.password"));

    return ds;
    /*
    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName("org.apache.derby.jdbc.ClientDriver");
    bds.setUrl("jdbc:derby://localhost:1527/MovieManagerDtb");
    bds.setUsername("administrator");
    bds.setPassword("admin");
    return bds;*/

    /*return new EmbeddedDatabaseBuilder()
        .setType(DERBY)
        .build();*/
}

From source file:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImplTest.java

@Test
public void testBasicDataSource() throws Exception {

    String jdbcDriverClassPath = globalConfiguration.getJdbcDriverClassPath();
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { new URL(jdbcDriverClassPath) },
            Thread.currentThread().getContextClassLoader());

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(globalConfiguration.getJdbcDriverClassName());
    basicDataSource.setUrl(globalConfiguration.getJdbcConnectionURI());
    basicDataSource.setUsername(globalConfiguration.getJdbcUsername());
    basicDataSource.setPassword(globalConfiguration.getJdbcPassword());

    // Does not work in 1.4, fixed in 1.4.1
    basicDataSource.setDriverClassLoader(urlClassLoader);

    try {//from   www  .  j av a  2s  .  c  om
        Connection connection = basicDataSource.getConnection();
        assertNotNull(connection);
    } catch (SQLException e) {
        // As expected when using DBCP 1.4
    }
}

From source file:com.ebay.pulsar.analytics.dao.RDBMS.java

private boolean init(boolean force) {
    if (dataSource == null || force) {
        final BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUsername(userName);
        dataSource.setPassword(userPwd);
        dataSource.setUrl(url);
        dataSource.setTestOnBorrow(true);
        if (validationQuery != null)
            dataSource.setValidationQuery(validationQuery);
        dataSource.setDriverClassLoader(Thread.currentThread().getContextClassLoader());
        dataSource.setDriverClassName(driver);
        this.setDataSource(dataSource);
    }//from   w w w  .  j  a  v a  2 s.c  om
    return true;
}

From source file:AccomManagerImplTest.java

@Before
public void setUp() throws SQLException {

    BasicDataSource bds = new BasicDataSource();
    bds.setUrl("jdbc:derby:memory:AccomManagerTest;create=true");
    this.dataSource = bds;
    //create new empty table before every test
    try (Connection conn = bds.getConnection()) {
        conn.prepareStatement("CREATE TABLE ACCOMODATION("
                + "ID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY," + "GUESTID INTEGER NOT NULL,"
                + "ROOMID INTEGER NOT NULL," + "STARTDATE DATE," + "ENDDATE DATE)").executeUpdate();
    }//from w  w  w  .  j av  a 2  s.co m
    try (Connection conn = bds.getConnection()) {
        conn.prepareStatement(
                "CREATE TABLE GUEST(" + "ID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,"
                        + "NAME VARCHAR(50) NOT NULL," + "CREDITCARD VARCHAR(50))")
                .executeUpdate();
    }
    try (Connection conn = bds.getConnection()) {
        conn.prepareStatement(
                "CREATE TABLE ROOM(" + "ID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,"
                        + "ROOMNUMBER INT," + "CAPACITY INT NOT NULL," + "FLOOR INT NOT NULL)")
                .executeUpdate();
    }
    accomManager = new AccomManagerImpl(bds);
    roomManager = new RoomManagerImpl(bds);
    guestManager = new GuestManagerImpl(bds);
}

From source file:com.dsf.dbxtract.cdc.AppJournalDeleteTest.java

/**
 * Rigourous Test :-)/* w w w . ja  va2 s .  co m*/
 * 
 * @throws Exception
 *             in case of any error
 */
@Test(timeOut = 120000)
public void testAppWithJournalDelete() throws Exception {

    final Config config = new Config(configFile);

    BasicDataSource ds = new BasicDataSource();
    Source source = config.getDataSources().getSources().get(0);
    ds.setDriverClassName(source.getDriver());
    ds.setUsername(source.getUser());
    ds.setPassword(source.getPassword());
    ds.setUrl(source.getConnection());

    // prepara os dados
    Connection conn = ds.getConnection();

    conn.createStatement().execute("truncate table test");
    conn.createStatement().execute("truncate table j$test");

    // Carrega os dados de origem
    PreparedStatement ps = conn.prepareStatement("insert into test (key1,key2,data) values (?,?,?)");
    for (int i = 0; i < TEST_SIZE; i++) {
        if ((i % 100) == 0) {
            ps.executeBatch();
        }
        ps.setInt(1, i);
        ps.setInt(2, i);
        ps.setInt(3, (int) Math.random() * 500);
        ps.addBatch();
    }
    ps.executeBatch();
    ps.close();

    app = new App(config);
    app.start();

    Assert.assertEquals(config.getHandlers().iterator().next().getStrategy(), JournalStrategy.DELETE);

    // Popula as tabelas de journal
    ps = conn.prepareStatement("insert into j$test (key1,key2) values (?,?)");
    for (int i = 0; i < TEST_SIZE; i++) {
        if ((i % 500) == 0) {
            ps.executeBatch();
        }
        ps.setInt(1, i);
        ps.setInt(2, i);
        ps.addBatch();
    }
    ps.executeBatch();
    ps.close();

    while (true) {
        TimeUnit.MILLISECONDS.sleep(500);

        ResultSet rs = conn.createStatement().executeQuery("select count(*) from j$test");
        if (rs.next()) {
            long count = rs.getLong(1);
            System.out.println("remaining journal rows: " + count);
            rs.close();
            if (count == 0L)
                break;
        }
    }
    conn.close();
    ds.close();
}

From source file:com.emc.vipr.sync.filter.TrackingFilter.java

@Override
public void parseCustomOptions(CommandLine line) {
    if (!line.hasOption(DB_URL_OPT))
        throw new ConfigurationException("Must provide a database to use the tracking filter");

    if (line.hasOption(TABLE_OPT))
        tableName = line.getOptionValue(TABLE_OPT);

    createTable = line.hasOption(CREATE_TABLE_OPT);
    processAllObjects = line.hasOption(REPROCESS_OPT);

    if (line.hasOption(META_OPT))
        metaTags = Arrays.asList(line.getOptionValue(META_OPT).split(","));

    // Initialize a DB connection pool
    BasicDataSource ds = new BasicDataSource();
    ds.setUrl(line.getOptionValue(DB_URL_OPT));
    if (line.hasOption(DB_DRIVER_OPT))
        ds.setDriverClassName(line.getOptionValue(DB_DRIVER_OPT));
    ds.setUsername(line.getOptionValue(DB_USER_OPT));
    ds.setPassword(line.getOptionValue(DB_PASSWORD_OPT));
    ds.setMaxTotal(200);/*w  w  w  .j a  v  a 2 s .  c om*/
    ds.setMaxOpenPreparedStatements(180);
    dataSource = ds;
}

From source file:at.rocworks.oa4j.logger.dbs.NoSQLJDBC.java

private void initStorage(BasicDataSource dataSource, int threads) {
    JDebug.out.info("jdbc init storage...");

    dataSource.setDriverClassName(driver);
    dataSource.setUrl(this.url);
    dataSource.setMaxTotal(threads);// ww  w  .j  a v a  2 s  .  co m
    dataSource.setUsername(username);
    dataSource.setPassword(password);

    JDebug.out.info("jdbc get connection...");

    // open at least one connection to prevent delay on writing/reading
    Connection conn;
    try {
        conn = dataSource.getConnection();
        conn.close();
    } catch (SQLException ex) {
        JDebug.StackTrace(Level.SEVERE, ex);
    }

    JDebug.out.info("jdbc init storage...done");
}

From source file:com.dsf.dbxtract.cdc.AppJournalWindowTest.java

/**
 * Rigourous Test :-)/*from w w  w . ja va  2  s  . c  om*/
 * 
 * @throws Exception
 *             in case of any error
 */
@Test(dependsOnMethods = "setUp", timeOut = 120000)
public void testAppWithJournalWindow() throws Exception {

    final Config config = new Config(configFile);

    BasicDataSource ds = new BasicDataSource();
    Source source = config.getDataSources().getSources().get(0);
    ds.setDriverClassName(source.getDriver());
    ds.setUsername(source.getUser());
    ds.setPassword(source.getPassword());
    ds.setUrl(source.getConnection());

    // prepara os dados
    Connection conn = ds.getConnection();

    conn.createStatement().execute("truncate table test");
    conn.createStatement().execute("truncate table j$test");

    // Carrega os dados de origem
    PreparedStatement ps = conn.prepareStatement("insert into test (key1,key2,data) values (?,?,?)");
    for (int i = 0; i < TEST_SIZE; i++) {
        if ((i % 100) == 0) {
            ps.executeBatch();
        }
        ps.setInt(1, i);
        ps.setInt(2, i);
        ps.setInt(3, (int) Math.random() * 500);
        ps.addBatch();
    }
    ps.executeBatch();
    ps.close();

    // Popula as tabelas de journal
    ps = conn.prepareStatement("insert into j$test (key1,key2) values (?,?)");
    for (int i = 0; i < TEST_SIZE; i++) {
        if ((i % 500) == 0) {
            ps.executeBatch();
        }
        ps.setInt(1, i);
        ps.setInt(2, i);
        ps.addBatch();
    }
    ps.executeBatch();
    ps.close();

    Long maxWindowId = 0L;
    ResultSet rs = conn.createStatement().executeQuery("select max(window_id) from j$test");
    if (rs.next()) {
        maxWindowId = rs.getLong(1);
        System.out.println("maximum window_id loaded: " + maxWindowId);
    }
    rs.close();
    conn.close();
    ds.close();

    // Clear any previous test
    String zkKey = "/dbxtract/cdc/" + source.getName() + "/J$TEST/lastWindowId";
    if (client.checkExists().forPath(zkKey) != null)
        client.delete().forPath(zkKey);

    // starts monitor
    Monitor.getInstance(config);

    // start app
    app = new App(config);
    System.out.println(config.toString());
    app.start();

    Assert.assertEquals(config.getHandlers().iterator().next().getStrategy(), JournalStrategy.WINDOW);

    while (true) {
        TimeUnit.MILLISECONDS.sleep(500);

        try {
            Long lastWindowId = Long.parseLong(new String(client.getData().forPath(zkKey)));
            System.out.println("lastWindowId = " + lastWindowId);
            if (maxWindowId.longValue() == lastWindowId.longValue()) {
                System.out.println("expected window_id reached");
                break;
            }

        } catch (NoNodeException nne) {
            System.out.println("ZooKeeper - no node exception :: " + zkKey);
        }
    }
}