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.alibaba.druid.pool.DBCPTest.java

public void test_dbcp() throws Exception {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(MockDriver.class.getName());
    dataSource.setUrl("jdbc:mock:xxx");
    dataSource.setMaxOpenPreparedStatements(100);
    dataSource.setPoolPreparedStatements(true);

    final String sql = "selelct 1";
    {/*from  w ww  .j a va2s .c  o m*/
        Connection conn = dataSource.getConnection();
        CallableStatement stmt = conn.prepareCall(sql);
        stmt.close();
        conn.close();
    }
    {
        Connection conn = dataSource.getConnection();
        CallableStatement stmt = conn.prepareCall(sql);
        stmt.close();
        conn.close();
    }
}

From source file:eu.udig.catalog.teradata.TeradataLookUpSchemaRunnable.java

private void loadTableDescriptors() throws SQLException, DataSourceException {

    TeradataDataStoreFactory factory = TeradataServiceExtension.getFactory();
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put(DBTYPE.key, (Serializable) DBTYPE.sample);
    params.put(HOST.key, host);//from  ww  w  . j a va2 s.c o m
    params.put(PORT.key, port);
    params.put(USER.key, username);
    params.put(PASSWD.key, password);
    params.put(DATABASE.key, database);

    BasicDataSource dataSource = null;
    Connection connection = null;
    try {
        dataSource = factory.createDataSource(params);
        connection = dataSource.getConnection();

        Statement statement = connection.createStatement();

        if (!hasWritableTable("SYSSPATIAL.spatial_ref_sys", "SRID", statement)) { //$NON-NLS-1$
            error = "The 'srid' table is either missing or not accessible; the Teradata datastore cannot work without the srid table.  Please talk to your database administrator.";
            return;
        }

        // Pair is schema, table name
        List<Pair<String, String>> tableNames = new ArrayList<Pair<String, String>>();

        ResultSet resultSet = statement.executeQuery(
                "SELECT F_TABLE_NAME,f_geometry_column FROM SYSSPATIAL.GEOMETRY_COLUMNS ORDER BY F_TABLE_NAME;");
        while (resultSet.next()) {
            String schema = database; //$NON-NLS-1$
            String table = resultSet.getString(1); //$NON-NLS-1$
            if (hasWritableTable(database + "." + table, resultSet.getString(2), statement)) { //$NON-NLS-1$
                tableNames.add(Pair.create(schema, table));
            }
        }
        if (tableNames.size() > 0) {
            Collection<TableDescriptor> results = lookupGeometryColumn(tableNames, connection);
            tables.addAll(results);
        }
        statement.close();
    } catch (SQLException e) {
        error = "An error occurred when querying the database about the data it contains. Please talk to the administrator: "
                + e.getMessage();
    } catch (IOException io) {
        error = "An error occurred when querying the database about the data it contains. Please talk to the administrator: "
                + io.getMessage();
    } finally {
        if (connection != null) {
            connection.close();
        }
        if (dataSource != null) {
            dataSource.close();
        }
    }
}

From source file:net.refractions.udig.catalog.internal.postgis.ui.PostgisLookUpSchemaRunnable.java

private void loadTableDescriptors() throws SQLException, DataSourceException {

    PostgisNGDataStoreFactory factory = PostgisServiceExtension2.getFactory();
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put(DBTYPE.key, (Serializable) DBTYPE.sample);
    params.put(HOST.key, host);//w  ww.  java  2  s . com
    params.put(PORT.key, port);
    params.put(USER.key, username);
    params.put(PASSWD.key, password);
    params.put(DATABASE.key, database);

    BasicDataSource dataSource = null;
    Connection connection = null;
    try {
        dataSource = factory.createDataSource(params);
        connection = dataSource.getConnection();

        Statement statement = connection.createStatement();

        if (!hasWritableTable("geometry_columns", "f_geometry_column", statement)) { //$NON-NLS-1$
            error = "Database is not a Postgis Database.\nThe 'geometry_columns' table is either missing or not accessible";
            return;
        }
        if (!hasWritableTable("spatial_ref_sys", "srid", statement)) { //$NON-NLS-1$
            error = "Database is not a Postgis Database.\nThe 'srid' table is either missing or not accessible";
            return;
        }

        // Pair is schema, table name
        List<Pair<String, String>> tableNames = new ArrayList<Pair<String, String>>();

        ResultSet resultSet = statement
                .executeQuery("SELECT schemaname, tablename FROM pg_tables ORDER BY schemaname, tablename;");
        while (resultSet.next()) {
            String schema = resultSet.getString("schemaname"); //$NON-NLS-1$
            String table = resultSet.getString("tablename"); //$NON-NLS-1$
            tableNames.add(Pair.create(schema, table));
        }
        Collection<TableDescriptor> results = lookupGeometryColumn(tableNames, connection);
        tables.addAll(results);
        statement.close();
    } catch (SQLException e) {
        error = "An error occurred when querying the database about the data it contains. Please talk to the administrator: "
                + e.getMessage();
    } catch (IOException io) {
        error = "An error occurred when querying the database about the data it contains. Please talk to the administrator: "
                + io.getMessage();
    } finally {
        if (connection != null) {
            connection.close();
        }
        if (dataSource != null) {
            dataSource.close();
        }
    }
}

From source file:gestores.PoolDeConexiones.java

protected void pedirConexion() throws Exception {
    if (conexion == null) {
        try {/*from   w  w  w. j  a v  a  2  s . com*/
            BasicDataSource basicDataSource = new BasicDataSource();
            basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            basicDataSource.setUrl("jdbc:mysql://localhost:3306/osg");
            basicDataSource.setUsername("root");
            basicDataSource.setPassword("root");
            basicDataSource.setMaxActive(20);
            basicDataSource.setMaxIdle(2);
            conexion = basicDataSource.getConnection();
            conexion.setAutoCommit(false);
        } catch (SQLException e) {
            throw new Exception(e.getMessage());
        }
    }
}

From source file:com.pinterest.deployservice.db.DatabaseUtil.java

/**
 * Create a MySQL datasource./*from w w  w  .j  a v  a2 s. com*/
 *
 * @param url             the url of the DB.
 * @param user            the user name to connect to MySQL as.
 * @param passwd          the password for the corresponding MySQL user.
 * @param poolSize        the connection pool size string, in the format of
 *                        initialSize:maxActive:maxIdle:minIdle.
 * @param maxWaitInMillis the max wait time in milliseconds to get a connection from the pool.
 * @return a BasicDataSource for the target MySQL instance.
 */
public static BasicDataSource createDataSource(String driverClassName, String url, String user, String passwd,
        String poolSize, int maxWaitInMillis) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(passwd);
    dataSource.setDefaultAutoCommit(true);
    dataSource.setDefaultReadOnly(false);

    // poolSize parsing, the poolsize string passed in the following format
    // initialSize:maxActive:maxIdle:minIdle
    String[] sizeStrs = poolSize.split(":");
    dataSource.setInitialSize(Integer.parseInt(sizeStrs[0]));
    dataSource.setMaxActive(Integer.parseInt(sizeStrs[1]));
    dataSource.setMaxIdle(Integer.parseInt(sizeStrs[2]));
    dataSource.setMinIdle(Integer.parseInt(sizeStrs[3]));

    dataSource.setValidationQuery("SELECT 1");
    dataSource.setTestOnBorrow(true);
    dataSource.setTestOnReturn(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setMinEvictableIdleTimeMillis(5 * 60 * 1000);
    dataSource.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000);
    // dataSource.setNumTestsPerEvictionRun(3);
    // max wait in milliseconds for a connection.
    dataSource.setMaxWait(maxWaitInMillis);

    // force connection pool initialization.
    Connection conn = null;
    try {
        // Here not getting the connection from ThreadLocal no need to worry about that.
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        LOG.error(String.format("Failed to get a db connection when creating DataSource, url = %s", url), e);
    } finally {
        DbUtils.closeQuietly(conn);
    }
    return dataSource;
}

From source file:com.pinterest.pinlater.backends.mysql.MySQLDataSources.java

private static DataSource createDataSource(String host, int port, String user, String passwd, int poolSize,
        int maxWaitMillis, int socketTimeoutMillis) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource//from  w  w  w  .  j  a  v a2s  . co m
            .setUrl(String.format(
                    "jdbc:mysql://%s:%d?" + "connectTimeout=5000&" + "socketTimeout=%d&"
                            + "enableQueryTimeouts=false&" + "cachePrepStmts=true&" + "characterEncoding=UTF-8",
                    host, port, socketTimeoutMillis));
    dataSource.setUsername(user);
    dataSource.setPassword(passwd);
    dataSource.setDefaultAutoCommit(true);
    dataSource.setInitialSize(poolSize);
    dataSource.setMaxActive(poolSize);
    dataSource.setMaxIdle(poolSize);
    // deal with idle connection eviction
    dataSource.setValidationQuery("SELECT 1 FROM DUAL");
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setMinEvictableIdleTimeMillis(5 * 60 * 1000);
    dataSource.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000);
    dataSource.setNumTestsPerEvictionRun(poolSize);
    // max wait in milliseconds for a connection.
    dataSource.setMaxWait(maxWaitMillis);
    // force connection pool initialization.
    Connection conn = null;
    try {
        // Here not getting the connection from ThreadLocal no need to worry about that.
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        LOG.error(String.format(
                "Failed to get a mysql connection when creating DataSource, " + "host: %s, port: %d", host,
                port), e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }
    return dataSource;
}

From source file:com.pinterest.deployservice.db.DBDAOTest.java

@BeforeClass
public static void setUpClass() throws Exception {
    try {//from   ww w. j  a  v  a 2  s.c om
        // making sure we do not have anything running
        ServerLauncherSocketFactory.shutdown(new File(DEFAULT_BASE_DIR), null);
    } catch (Exception e) {
        // ignore
    }
    BasicDataSource DATASOURCE = DatabaseUtil.createMXJDataSource(DEFAULT_DB_NAME, DEFAULT_BASE_DIR,
            DEFAULT_PORT);
    Connection conn = DATASOURCE.getConnection();
    ScriptRunner runner = new ScriptRunner(conn, false, true);
    runner.runScript(
            new BufferedReader(new InputStreamReader(DBDAOTest.class.getResourceAsStream("/sql/cleanup.sql"))));
    runner.runScript(
            new BufferedReader(new InputStreamReader(DBDAOTest.class.getResourceAsStream("/sql/deploy.sql"))));
    buildDAO = new DBBuildDAOImpl(DATASOURCE);
    agentDAO = new DBAgentDAOImpl(DATASOURCE);
    agentErrorDAO = new DBAgentErrorDAOImpl(DATASOURCE);
    dataDAO = new DBDataDAOImpl(DATASOURCE);
    deployDAO = new DBDeployDAOImpl(DATASOURCE);
    environDAO = new DBEnvironDAOImpl(DATASOURCE);
    promoteDAO = new DBPromoteDAOImpl(DATASOURCE);
    hostDAO = new DBHostDAOImpl(DATASOURCE);
    groupDAO = new DBGroupDAOImpl(DATASOURCE);
    ratingDAO = new DBRatingsDAOImpl(DATASOURCE);
    groupInfoDAO = new DBGroupInfoDAOImpl(DATASOURCE);
    alarmDAO = new DBAlarmDAOImpl(DATASOURCE);
    userRolesDAO = new DBUserRolesDAOImpl(DATASOURCE);
    groupRolesDAO = new DBGroupRolesDAOImpl(DATASOURCE);
    tokenRolesDAO = new DBTokenRolesDAOImpl(DATASOURCE);
    imageDAO = new DBImageDAOImpl(DATASOURCE);
    healthCheckDAO = new DBHealthCheckDAOImpl(DATASOURCE);
    healthCheckErrorDAO = new DBHealthCheckErrorDAOImpl(DATASOURCE);
    configHistoryDAO = new DBConfigHistoryDAOImpl(DATASOURCE);
    newInstanceReportDAO = new DBNewInstanceReportDAOImpl(DATASOURCE);
    asgLifecycleEventDAO = new DBAsgLifecycleEventDAOImpl(DATASOURCE);
    managingGroupDAO = new DBManaginGroupDAOImpl(DATASOURCE);
    clusterDAO = new DBClusterDAOImpl(DATASOURCE);
    baseImageDAO = new DBBaseImageDAOImpl(DATASOURCE);
    hostTypeDAO = new DBHostTypeDAOImpl(DATASOURCE);
    securityZoneDAO = new DBSecurityZoneDAOImpl(DATASOURCE);
    placementDAO = new DBPlacementDAOImpl(DATASOURCE);
}

From source file:com.alibaba.druid.pool.dbcp.Test0.java

public void test_idle() throws Exception {
    MockDriver driver = MockDriver.instance;

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:mock:xxx");
    dataSource.setDriverClassName("com.alibaba.druid.mock.MockDriver");
    dataSource.setInitialSize(0);/*w  w  w. ja  va  2s . c  om*/
    dataSource.setMaxActive(4);
    dataSource.setMaxIdle(4);
    dataSource.setMinIdle(1);
    dataSource.setMinEvictableIdleTimeMillis(5000 * 1);
    dataSource.setTimeBetweenEvictionRunsMillis(10);
    dataSource.setTestWhileIdle(false);
    dataSource.setTestOnBorrow(false);
    dataSource.setValidationQuery("SELECT 1");

    {
        Connection conn = dataSource.getConnection();

        // Assert.assertEquals(dataSource.getInitialSize(), driver.getConnections().size());
        System.out.println("raw size : " + driver.getConnections().size());

        conn.close();
        System.out.println("raw size : " + driver.getConnections().size());
    }

    {
        Connection conn = dataSource.getConnection();

        // Assert.assertEquals(dataSource.getInitialSize(), driver.getConnections().size());
        System.out.println("raw size : " + driver.getConnections().size());

        conn.close();
        System.out.println("raw size : " + driver.getConnections().size());
    }

    dataSource.close();
}

From source file:eu.peppol.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   w  w w .  j  av  a  2 s . c om*/
        Connection connection = basicDataSource.getConnection();
        assertNotNull(connection);
        fail("Wuhu! They have finally fixed the bug in DBCP; ignoring the classloader. Consider changing the code!");
    } catch (SQLException e) {
        // As expected when using DBCP 1.4
    }
}

From source file:net.jetrix.DataSourceManager.java

/**
 * Configure a datasource.//from  w w  w .  j a  v  a  2 s . c  om
 *
 * @param config      the configuration of the datasource
 * @param environment the environment of the datasource
 */
public void setDataSource(DataSourceConfig config, String environment) {
    try {
        Class.forName(config.getDriver());
    } catch (ClassNotFoundException e) {
        log.warning("Unable to find the database driver (" + config.getDriver()
                + "), put the related jar in the lib directory");
        return;
    }

    try {
        // close the previous datasource if necessary
        if (datasources.containsKey(environment)) {
            BasicDataSource datasource = (BasicDataSource) datasources.get(environment);
            datasource.close();
        }

        BasicDataSource datasource = new BasicDataSource();
        datasource.setDefaultAutoCommit(false);

        datasource.setDriverClassName(config.getDriver());
        datasource.setUrl(config.getUrl());
        datasource.setUsername(config.getUsername());
        datasource.setPassword(config.getPassword());
        datasource.setMinIdle(config.getMinIdle() != 0 ? config.getMinIdle() : DEFAULT_MIN_IDLE);
        datasource.setMaxActive(config.getMaxActive() != 0 ? config.getMaxActive() : DEFAULT_MAX_ACTIVE);

        // attempts to open the connection
        datasource.getConnection().close();

        datasources.put(environment, datasource);
    } catch (Exception e) {
        log.log(Level.SEVERE, "Unable to configure the datasource '" + environment + "'", e);
    }
}