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

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

Introduction

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

Prototype

public Connection getConnection() throws SQLException 

Source Link

Document

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

Usage

From source file:com.uber.hoodie.hive.HoodieHiveClient.java

private void createHiveConnection() {
    if (connection == null) {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(driverName);
        ds.setUrl(getHiveJdbcUrlWithDefaultDBName());
        ds.setUsername(syncConfig.hiveUser);
        ds.setPassword(syncConfig.hivePass);
        LOG.info("Getting Hive Connection from Datasource " + ds);
        try {/*w  ww  .  ja v  a  2  s .c om*/
            this.connection = ds.getConnection();
        } catch (SQLException e) {
            throw new HoodieHiveSyncException(
                    "Cannot create hive connection " + getHiveJdbcUrlWithDefaultDBName(), e);
        }
    }
}

From source file:com.alibaba.druid.DBCPTest.java

public void test_max() throws Exception {
    Class.forName("com.alibaba.druid.mock.MockDriver");

    final BasicDataSource dataSource = new BasicDataSource();
    //        final DruidDataSource dataSource = new DruidDataSource();
    dataSource.setInitialSize(3);/*w w  w .ja  v a  2s . c  om*/
    dataSource.setMaxActive(20);
    dataSource.setMaxIdle(20);
    dataSource.setDriverClassName("com.alibaba.druid.mock.MockDriver");
    dataSource.setUrl("jdbc:mock:xxx");

    final int THREAD_COUNT = 200;
    final CountDownLatch endLatch = new CountDownLatch(THREAD_COUNT);
    final CountDownLatch startLatch = new CountDownLatch(1);
    Thread[] threads = new Thread[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; ++i) {
        threads[i] = new Thread() {

            public void run() {
                try {
                    startLatch.await();
                    for (int i = 0; i < 1000; ++i) {
                        Connection conn = dataSource.getConnection();
                        Thread.sleep(1);
                        conn.close();
                    }
                } catch (Exception e) {
                } finally {
                    endLatch.countDown();
                }
            }
        };
        threads[i].start();
    }

    startLatch.countDown();

    endLatch.await();

    //        System.out.println(dataSource.getNumIdle());
    System.out.println(MockDriver.instance.getConnections().size());
    System.out.println(MockDriver.instance.getConnectionCloseCount());
}

From source file:com.seajas.search.utilities.logging.SearchLogger.java

/**
 * Default constructor.//from  w w  w  .  ja  va 2s .c  o  m
 * 
 * @param name
 * @param level
 * @param dataSource
 * @param loggingDAO
 */
public SearchLogger(final String name, final String level, final BasicDataSource dataSource,
        final LoggingDAO loggingDAO) {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

    // Create the actual logger

    Logger logger = (Logger) LoggerFactory.getLogger(name);

    logger.setLevel(Level.toLevel(level));
    logger.setAdditive(true);

    // Create the logging appender

    AppenderBase<ILoggingEvent> appender = new AppenderBase<ILoggingEvent>() {
        @Override
        protected void append(final ILoggingEvent event) {
            Connection connection = null;

            PreparedStatement statement = null;

            try {
                connection = dataSource.getConnection();

                statement = connection.prepareStatement(JDBC_INSERT);

                statement.setString(1, event.getLevel().toString());
                statement.setString(2, event.getFormattedMessage());
                statement.setDate(3, new Date(event.getTimeStamp()));

                statement.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (statement != null)
                        statement.close();
                    if (connection != null)
                        connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    appender.setContext(loggerContext);

    appender.start();

    // Make this the definitive logger

    logger.addAppender(appender);

    this.logger = logger;
}

From source file:edu.ucsf.vitro.opensocial.OpenSocialSmokeTests.java

/**
 * Check that we can connect to the database, and query one of the Shindig
 * tables./* w ww .j  a  v  a2s.c  om*/
 */
private void checkDatabaseTables() {
    BasicDataSource dataSource = null;
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;
    try {
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName(getProperty(PROPERTY_DB_DRIVER));
        dataSource.setUrl(getProperty(PROPERTY_DB_JDBC_URL));
        dataSource.setUsername(getProperty(PROPERTY_DB_USERNAME));
        dataSource.setPassword(getProperty(PROPERTY_DB_PASSWORD));

        conn = dataSource.getConnection();
        stmt = conn.createStatement();
        rset = stmt.executeQuery("select * from orng_apps");
    } catch (NoSuchPropertyException e) {
        warnings.add(new Warning(e.getMessage()));
    } catch (SQLException e) {
        if (e.getMessage().contains("doesn't exist")) {
            warnings.add(new Warning("The Shindig tables don't exist "
                    + "in the database. Was shindig_orng_tables.sql " + "run to set them up?", e));
        } else {
            warnings.add(new Warning("Can't access the Shindig database tables", e));
        }
    } finally {
        try {
            if (rset != null) {
                rset.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * //from  w w  w .j av  a 2 s  .  c  o m
 *
 * @return time taken
 * @throws SQLException
 */
private long singleDBCP() throws SQLException {
    // Start DBCP

    BasicDataSource cpds = new BasicDataSource();
    cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver");
    cpds.setUrl(url);
    cpds.setUsername(username);
    cpds.setPassword(password);
    cpds.setMaxIdle(-1);
    cpds.setMinIdle(-1);
    cpds.setMaxOpenPreparedStatements(max_statement);
    cpds.setInitialSize(pool_size);
    cpds.setMaxActive(pool_size);
    cpds.getConnection(); // call to initialize possible lazy structures etc 

    long start = System.currentTimeMillis();
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
        Connection conn = cpds.getConnection();
        conn.close();
    }
    long end = (System.currentTimeMillis() - start);
    //      System.out.println("DBCP Single thread benchmark: "+end);

    cpds.close();
    return end;

}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * Benchmarks PreparedStatement functionality (single thread) 
 * @return result/*from   www  .j  a v  a 2 s .  c om*/
 * 
 * @throws PropertyVetoException
 * @throws SQLException
 */
private long testPreparedStatementSingleThreadDBCP() throws PropertyVetoException, SQLException {
    BasicDataSource cpds = new BasicDataSource();
    cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver");
    cpds.setUrl(url);
    cpds.setUsername(username);
    cpds.setPassword(password);
    cpds.setMaxIdle(-1);
    cpds.setMinIdle(-1);
    cpds.setPoolPreparedStatements(true);
    cpds.setMaxOpenPreparedStatements(30);
    cpds.setInitialSize(pool_size);
    cpds.setMaxActive(pool_size);
    Connection conn = cpds.getConnection();

    long start = System.currentTimeMillis();
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
        Statement st = conn.prepareStatement(TEST_QUERY);
        st.close();
    }
    conn.close();

    long end = (System.currentTimeMillis() - start);
    System.out.println("DBCP PreparedStatement Single thread benchmark: " + end);
    results.add("DBCP, " + end);
    // dispose of pool
    cpds.close();
    return end;
}

From source file:fi.ni.IFC_ClassModel.java

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

    BufferedWriter out = null;/* ww w  .  j av  a2  s.c  om*/
    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:org.apache.drill.exec.store.http.InsertTestData.java

public static DataSource createDataSource(String driver, String url, String userName, String password) {

    BasicDataSource source = new BasicDataSource();
    source.setDriverClassName(driver);/*from   w  w w. j  av a  2s. co m*/
    source.setUrl(url);

    if (userName != null) {
        source.setUsername(userName);
    }

    if (password != null) {
        source.setPassword(password);
    }
    source.setInitialSize(1);
    source.setPoolPreparedStatements(true);
    try {
        // initial a connection
        source.getConnection();
    } catch (SQLException sqlE) {

        logger.error("db connection error: ", sqlE);
    }
    return source;

}

From source file:org.apache.drill.exec.store.http.util.DBUtil.java

public static DataSource createDataSource(String driver, String url, String userName, String password) {

    BasicDataSource source = new BasicDataSource();
    source.setDriverClassName(driver);/*from w  ww.  ja v a 2s . c  o m*/
    source.setUrl(url);

    if (userName != null) {
        source.setUsername(userName);
    }

    if (password != null) {
        source.setPassword(password);
    }

    source.setPoolPreparedStatements(true);
    source.setInitialSize(1);
    try {
        // initial a connection
        Connection conn = source.getConnection();
        conn.close();
    } catch (SQLException sqlE) {

        logger.error("db connection error: ", sqlE);
    }
    return source;

}

From source file:org.apache.drill.exec.store.jdbc.TestJdbcPlugin.java

@BeforeClass
public static void setupDefaultTestCluster() throws Exception {
    System.setProperty("derby.drda.startNetworkServer", "true");
    server = new NetworkServerControl(InetAddress.getByName("localhost"), 20000, "admin", "admin");
    java.io.PrintWriter consoleWriter = new java.io.PrintWriter(System.out, true);
    server.start(consoleWriter);//from  w  w w. ja v a  2s  .c  o m

    BasicDataSource source = new BasicDataSource();
    source.setUrl("jdbc:derby://localhost:20000/memory:testDB;create=true");
    source.setDriverClassName("org.apache.derby.jdbc.ClientDriver");

    final String insertValues1 = "INSERT INTO person VALUES (1, 'Smith', null, '{number:\"123 Main\"}','mtrx', "
            + "'xy', 333.333, 444.444, 555.00, TIME('15:09:02'), DATE('1994-02-23'), TIMESTAMP('1962-09-23 03:23:34.234'),"
            + " 666.66, 1, -1, false)";
    final String insertValues2 = "INSERT INTO person (PersonId) VALUES (null)";
    try (Connection c = source.getConnection()) {
        c.createStatement()
                .execute("CREATE TABLE person\n" + "(\n" + "PersonID int,\n" + "LastName varchar(255),\n"
                        + "FirstName varchar(255),\n" + "Address varchar(255),\n" + "City varchar(255),\n"
                        + "Code char(2),\n" + "dbl double,\n" + "flt float,\n" + "rel real,\n" + "tm time,\n"
                        + "dt date,\n" + "tms timestamp,\n" + "num numeric(10,2), \n" + "sm smallint,\n"
                        + "bi bigint,\n" + "bool boolean\n" +

                        ")");

        c.createStatement().execute(insertValues1);
        c.createStatement().execute(insertValues2);
        c.createStatement().execute(insertValues1);
    }

    BaseTestQuery.setupDefaultTestCluster();
}