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

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

Introduction

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

Prototype

@Override
public Connection getConnection() throws SQLException 

Source Link

Document

Create (if necessary) and return a connection to the database.

Usage

From source file:com.thoughtworks.go.server.database.H2DatabaseTest.java

@Test
void shouldBackupDatabase() throws Exception {
    File destDir = new File(".");
    SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);
    Database database = new H2Database(systemEnvironment);
    Database spy = spy(database);/* w ww  .j  a  v a  2s  .  c  o  m*/
    BasicDataSource dataSource = mock(BasicDataSource.class);
    Connection connection = mock(Connection.class);
    Statement statement = mock(Statement.class);
    doReturn(dataSource).when(spy).createDataSource();
    when(dataSource.getConnection()).thenReturn(connection);
    when(connection.createStatement()).thenReturn(statement);
    when(statement.execute(anyString())).thenReturn(true);

    spy.backup(destDir);

    verify(statement).execute(anyString());
}

From source file:com.thoughtworks.go.server.database.H2DatabaseTest.java

@Test
void shouldThrowUpWhenBackupFails() throws Exception {
    File destDir = new File(".");
    SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);
    Database database = new H2Database(systemEnvironment);
    Database spy = spy(database);//from   w  w  w  .  j a v  a  2 s . c  om
    BasicDataSource dataSource = mock(BasicDataSource.class);
    Connection connection = mock(Connection.class);
    Statement statement = mock(Statement.class);
    doReturn(dataSource).when(spy).createDataSource();
    when(dataSource.getConnection()).thenReturn(connection);
    when(connection.createStatement()).thenReturn(statement);
    when(statement.execute(anyString())).thenThrow(new SQLException("i failed"));

    try {
        spy.backup(destDir);
    } catch (RuntimeException e) {
        assertThat(e.getMessage(), is("i failed"));
    }

    verify(statement).execute(anyString());
}

From source file:GuestManagerImplTest.java

@Before
public void setUp() throws SQLException {
    BasicDataSource bds = new BasicDataSource();
    bds.setUrl("jdbc:derby:memory:GuestManagerTest;create=true");
    this.dataSource = bds;
    //create new empty table before every test
    try (Connection conn = bds.getConnection()) {
        conn.prepareStatement("CREATE TABLE GUEST (" + "ID INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,"
                + "NAME VARCHAR(50)," + "CREDITCARD VARCHAR(50))").executeUpdate();
    }/* w w w . j  av a2  s. c o  m*/
    manager = new GuestManagerImpl(bds);
}

From source file:HotelManagerImplTest.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  . jav  a  2 s . c o 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);
    hotelManager = new HotelManagerImpl(bds);

}

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

/**
 * Rigourous Test :-)/*w w w . j a va 2s  . c o 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:de.innovationgate.webgate.api.jdbc.pool.DBCPReplicationConnectionProvider.java

public Connection getConnection() throws SQLException {

    SQLException connectionException = null;

    Connection master = null;/*w w  w .  jav a  2  s  .c  o m*/

    if (_masterFailure == null || (System.currentTimeMillis() - RETRY_DELAY) >= _masterFailure.getTime()) {
        try {
            // master 
            master = _masterDS.getConnection();
        } catch (SQLException e) {
            log.warn("Unable to establish a connection to master database on '" + _jdbcUrls[0] + "'.");
            connectionException = e;
            _masterFailure = new Date();
        }
    }

    // if slave urls given - randomize one
    Connection slave = null;
    if (_slaveDSList.size() > 0) {
        int slaveIdx = new Random().nextInt(_slaveDSList.size());
        BasicDataSource slaveDS = (BasicDataSource) _slaveDSList.get(slaveIdx);

        Date failureDate = (Date) _slaveFailures.get(slaveDS);

        if (failureDate == null || (System.currentTimeMillis() - RETRY_DELAY) >= failureDate.getTime()) {
            try {
                slave = slaveDS.getConnection();
            } catch (SQLException e) {
                log.warn("Unable to establish a connection to database on '" + _jdbcUrls[slaveIdx + 1] + "'.");
                connectionException = e;
                // set slave failure timestamp
                _slaveFailures.put(slaveDS, new Date());
            }
        }
    }

    if (master == null && slave == null) {
        throw connectionException;
    }

    return new DBCPReplicationConnection(master, slave);
}

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

private void setupDBCP2basic() throws SQLException {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(dbDriver);/*from  ww  w.j  a v  a2  s .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: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 ww w. ja  v 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.AppJournalWindowTest.java

/**
 * Rigourous Test :-)//  w w w. j  a  v a2s  . 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);
        }
    }
}

From source file:dragonrental.backend.DbConfig.java

public DataSource dataSource() {

    Properties conf = new Properties();
    BasicDataSource ds = new BasicDataSource();
    try {//from   w w  w  . j  a  va2  s  .  com
        conf.load(DbConfig.class.getResourceAsStream("/Properties.properties"));
    } catch (IOException ex) {
        //log.error("Loading properties has failed!");
    }

    ds.setUrl(conf.getProperty("db.url"));
    ds.setDriverClassName(conf.getProperty("db.driver"));
    ds.setUsername(conf.getProperty("db.user"));
    ds.setPassword(conf.getProperty("db.password"));

    DatabaseMetaData metaData;
    ResultSet tables;
    try (Connection connection = ds.getConnection()) {
        metaData = connection.getMetaData();
        tables = metaData.getTables(null, null, "%", new String[] { "TABLE" });

        //checks wheter there is any tables (will not create new tables if it finds ANY table)
        if (!tables.next()) {
            new ResourceDatabasePopulator(new ClassPathResource("schema-javadb.sql"),
                    new ClassPathResource("test-data.sql")).execute(ds);
        }
    } catch (SQLException ex) {
        System.out.println("SQL Ex when checking for tables");
        System.out.println(ex.getMessage());
    }

    return ds;
}