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.magnet.mmx.util.DatabaseExport.java

public static void main(String[] args) throws Exception {
    InputStream inputStream = DeviceDAOImplTest.class.getResourceAsStream("/test.properties");

    Properties testProperties = new Properties();
    testProperties.load(inputStream);/*w  w w .j  a  v a  2s.co m*/

    String host = testProperties.getProperty("db.host");
    String port = testProperties.getProperty("db.port");
    String user = testProperties.getProperty("db.user");
    String password = testProperties.getProperty("db.password");
    String driver = testProperties.getProperty("db.driver");
    String schema = testProperties.getProperty("db.schema");

    String url = "jdbc:mysql://" + host + ":" + port + "/" + schema;

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driver);
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setUrl(url);
    TreeMap<String, String> map = new TreeMap<String, String>();
    map.put("mmxTag", "SELECT * FROM mmxTag ");
    doWork(ds.getConnection(), map);
}

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

public static int update(String query, H2Database h2Database) {
    BasicDataSource source = h2Database.createDataSource();
    Connection con = null;//from  w  ww  . j  av a 2  s  .co  m
    Statement stmt = null;
    try {
        con = source.getConnection();
        stmt = con.createStatement();
        return stmt.executeUpdate(query);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            assert stmt != null;
            stmt.close();
            con.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

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

public static void assertColumnType(BasicDataSource dataSource, String tableName, String columnName,
        String expected) throws SQLException {
    Connection connection = dataSource.getConnection();
    try {//from   w  w w  .  j a va 2 s.  c  o  m
        ResultSet set = connection.getMetaData().getColumns(null, null, null, null);
        while (set.next()) {
            if (set.getString("TABLE_NAME").equalsIgnoreCase(tableName)
                    && set.getString("COLUMN_NAME").equalsIgnoreCase(columnName)) {
                String typeName = set.getString("TYPE_NAME");
                int typeWidth = set.getInt("COLUMN_SIZE");
                String type = typeName + "(" + typeWidth + ")";
                assertThat("Expected " + columnName + " to be " + expected + " type but was " + type, type,
                        is(expected));
                return;
            }
        }
        Assert.fail("Column " + columnName + " does not exist");
    } finally {
        try {
            connection.close();
        } catch (Exception ignored) {
        }
    }
}

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

public static Object[][] query(String query, H2Database h2Database) {
    BasicDataSource source = h2Database.createDataSource();
    Connection con = null;//from   www  .ja v  a  2 s.  c om
    Statement stmt = null;
    ResultSet rs = null;
    try {
        con = source.getConnection();
        stmt = con.createStatement();
        rs = stmt.executeQuery(query);
        int columnCount = rs.getMetaData().getColumnCount();
        List<Object[]> objects = new ArrayList<>();
        while (rs.next()) {
            Object[] values = new Object[columnCount];
            for (int i = 0; i < values.length; i++) {
                values[i] = rs.getObject(i + 1);
            }
            objects.add(values);
        }
        return objects.toArray(new Object[0][0]);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            assert stmt != null;
            stmt.close();
            con.close();
            assert rs != null;
            rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.linuxrouter.netcool.session.QueryUtils.java

public Boolean executeUpdate(String dbName, String sql) {
    Long start = System.currentTimeMillis();
    try {//from  w w w. java 2  s.  c  o  m
        //connection caching...
        Connection con = null;
        if (connectionMap.get(dbName) == null) {
            BasicDataSource ds = DbUtils.getSimpleDataSourceByName(dbName);
            con = ds.getConnection();
            connectionMap.put(dbName, con);
        } else {
            con = connectionMap.get(dbName);

        }
        Statement st = con.createStatement();
        st.executeUpdate(sql);
        st.close();
    } catch (SQLException ex) {
        logger.error("Erro ao executar query:", ex);
        return false;
    }
    Long end = System.currentTimeMillis();
    return true;
}

From source file:com.linuxrouter.netcool.session.QueryUtils.java

public ArrayList<HashMap<String, Object>> executeQuery(String dbName, String sql) {
    Long start = System.currentTimeMillis();
    ArrayList<HashMap<String, Object>> result = new ArrayList<>();
    HashMap<Integer, String> colTypes = new HashMap<Integer, String>();
    HashMap<Integer, String> colNames = new HashMap<Integer, String>();
    try {/*w  ww. ja  va  2  s .c o m*/
        //connection caching...
        Connection con = null;
        if (connectionMap.get(dbName) == null) {
            BasicDataSource ds = DbUtils.getSimpleDataSourceByName(dbName);
            con = ds.getConnection();
            connectionMap.put(dbName, con);
        } else {
            con = connectionMap.get(dbName);

        }

        Statement st = con.createStatement();

        ResultSet rs = st.executeQuery(sql);
        ResultSetMetaData metaData = rs.getMetaData();
        int colCount = metaData.getColumnCount();
        for (int i = 1; i <= colCount; i++) {
            colTypes.put(i, metaData.getColumnTypeName(i));
            colNames.put(i, metaData.getColumnLabel(i));
        }
        while (rs.next()) {
            HashMap<String, Object> dado = new HashMap<>();
            for (int i = 1; i <= colCount; i++) {
                dado.put(colNames.get(i), rs.getObject(i));

            }
            result.add(dado);
        }
        rs.close();
        st.close();
        //con.close();
        Long end = System.currentTimeMillis();
        //logger.debug("Query on external DB took: " + (end - start) + "ms");
    } catch (SQLException ex) {
        logger.error("Erro ao executar query:", ex);
    }
    return result;
}

From source file:com.searchcode.app.config.DatabaseConfig.java

public Connection getConnection() throws SQLException {
    BasicDataSource ds = new BasicDataSource(); // pooling data source

    ds.setDriverClassName("org.hsqldb.jdbcDriver");
    ds.setUsername("sa");
    ds.setPassword("");
    ds.setUrl("jdbc:hsqldb:file:searchcode;shutdown=true");

    return ds.getConnection();
}

From source file:com.thoughtworks.go.server.service.BackupServiceH2IntegrationTest.java

@Test
@RunIf(value = DatabaseChecker.class, arguments = { DatabaseChecker.H2 })
public void shouldPerformDbBackupProperly() throws SQLException, IOException {
    Pipeline expectedPipeline = saveAPipeline();

    ServerBackup serverBackup = backupService.startBackup(admin);
    assertThat(serverBackup.isSuccessful(), is(true));
    assertThat(serverBackup.getMessage(), is("Backup was generated successfully."));

    String location = temporaryFolder.newFolder().getAbsolutePath();

    Restore.execute(dbZip(), location, "cruise", false);

    BasicDataSource source = constructTestDataSource(new File(location));
    ResultSet resultSet = source.getConnection()
            .prepareStatement("select * from pipelines where id = " + expectedPipeline.getId()).executeQuery();
    int size = 0;
    while (resultSet.next()) {
        assertThat(resultSet.getString("name"), is(expectedPipeline.getName()));
        size++;//  w  ww.j a  v  a2  s . c  om
    }
    assertThat(size, is(1));
}

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

@Test
void shouldUpgradeDatabase() throws SQLException {
    h2Database.shutdown();//from   ww w .  j  a v  a  2  s . c om
    h2Database.startDatabase();
    BasicDataSource dataSource = h2Database.createDataSource();
    h2Database.upgrade();
    h2Database.startDatabase();

    dataSource = h2Database.createDataSource();
    Connection connection = dataSource.getConnection();
    ResultSet set = connection.getMetaData().getTables(null, null, null, null);

    assertThat(set.next(), is(true));
}

From source file:cz.muni.fi.pv168.AgentManagerImplTest.java

@Before
public void setUp() throws Exception {
    BasicDataSource bds = new BasicDataSource();
    bds.setUrl("jdbc:derby:memory:AgentManagerTest;create=true");
    this.dataSource = bds;
    //create new empty table before every test
    try (Connection conn = bds.getConnection()) {
        conn.prepareStatement("CREATE TABLE agent (" + "id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,"
                + "name VARCHAR(255)," + "born DATE)").executeUpdate();
    }/*from w w  w  . ja  v a2s  .  c o  m*/
    manager = new AgentManagerImpl(bds);
}