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

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

Introduction

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

Prototype

BasicDataSource

Source Link

Usage

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

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

From source file:net.gcolin.simplerepo.search.SearchController.java

public SearchController(ConfigurationManager configManager) throws IOException {
    this.configManager = configManager;
    File plugins = new File(configManager.getRoot(), "plugins");
    plugins.mkdirs();/*from  w  ww. j ava 2 s  . com*/
    System.setProperty("derby.system.home", plugins.getAbsolutePath());
    BasicDataSource s = new BasicDataSource();
    s.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    s.setUrl("jdbc:derby:search" + (new File(plugins, "search").exists() ? "" : ";create=true"));
    s.setUsername("su");
    s.setPassword("");
    s.setMaxTotal(10);
    s.setMinIdle(0);
    s.setDefaultAutoCommit(true);
    datasource = s;

    Set<String> allTables = new HashSet<>();
    Connection connection = null;

    try {
        try {
            connection = datasource.getConnection();
            connection.setAutoCommit(false);
            DatabaseMetaData dbmeta = connection.getMetaData();
            try (ResultSet rs = dbmeta.getTables(null, null, null, new String[] { "TABLE" })) {
                while (rs.next()) {
                    allTables.add(rs.getString("TABLE_NAME").toLowerCase());
                }
            }

            if (!allTables.contains("artifact")) {
                QueryRunner run = new QueryRunner();
                run.update(connection,
                        "CREATE TABLE artifactindex(artifact bigint NOT NULL, version bigint NOT NULL)");
                run.update(connection, "INSERT INTO artifactindex (artifact,version) VALUES (?,?)", 1L, 1L);
                run.update(connection,
                        "CREATE TABLE artifact(id bigint NOT NULL,groupId character varying(120), artifactId character varying(120),CONSTRAINT artifact_pkey PRIMARY KEY (id))");
                run.update(connection,
                        "CREATE TABLE artifactversion(artifact_id bigint NOT NULL,id bigint NOT NULL,"
                                + "version character varying(100)," + "reponame character varying(30),"
                                + "CONSTRAINT artifactversion_pkey PRIMARY KEY (id),"
                                + "CONSTRAINT fk_artifactversion_artifact_id FOREIGN KEY (artifact_id) REFERENCES artifact (id) )");
                run.update(connection,
                        "CREATE TABLE artifacttype(version_id bigint NOT NULL,packaging character varying(20) NOT NULL,classifier character varying(30),"
                                + "CONSTRAINT artifacttype_pkey PRIMARY KEY (version_id,packaging,classifier),"
                                + "CONSTRAINT fk_artifacttype_version FOREIGN KEY (version_id) REFERENCES artifactversion (id))");
                run.update(connection, "CREATE INDEX artifactindex ON artifact(groupId,artifactId)");
                run.update(connection, "CREATE INDEX artifactgroupindex ON artifact(groupId)");
                run.update(connection, "CREATE INDEX artifactversionindex ON artifactversion(version)");
            }
            connection.commit();
        } catch (SQLException ex) {
            connection.rollback();
            throw ex;
        } finally {
            DbUtils.close(connection);
        }
    } catch (SQLException ex) {
        throw new IOException(ex);
    }
}

From source file:de.cimt.talendcomp.connectionpool.BasicConnectionPool.java

/**
 * Creates the data sources and initialize the pool
 * @throws Exception/*  w w w .j  a  va  2  s . c  o m*/
 * @throws Exception, UniversalConnectionPoolException
 */
public void initializePool() throws Exception {
    if (this.driver == null) {
        throw new IllegalStateException("Please call method loadDriver before setup datasource");
    }
    if (this.connectionUrl == null) {
        throw new IllegalStateException("Please use method setConnectionString before setup datasource");
    }
    // use org.apache.commons.dbcp2.BasicDataSource
    this.dataSource = new BasicDataSource();
    this.dataSource.setUsername(this.user);
    this.dataSource.setPassword(this.pass);
    this.dataSource.setUrl(this.connectionUrl);
    this.dataSource.setTestOnBorrow(this.testOnBorrow);
    this.dataSource.setTestWhileIdle(true);
    this.dataSource.setMinEvictableIdleTimeMillis(this.timeIdleConnectionIsChecked);
    this.dataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenChecks);
    this.dataSource.setInitialSize(this.initialSize);
    this.dataSource.setMaxTotal(this.maxTotal);
    if (enableJMX) {
        this.dataSource.setJmxName(buildJmxName());
    }
    //this.dataSource.setMaxIdle(this.maxIdle);
    if (this.maxWaitForConnection == 0) {
        this.maxWaitForConnection = -1;
    }
    this.dataSource.setMaxWaitMillis(this.maxWaitForConnection);
    this.dataSource.setNumTestsPerEvictionRun(this.numConnectionsPerCheck);
    this.dataSource.setValidationQuery(this.validationQuery);
    if (initSQL != null && initSQL.isEmpty() == false) {
        this.dataSource.setConnectionInitSqls(this.initSQL);
    }
    this.dataSource.setDefaultAutoCommit(autoCommit);
    this.dataSource.setLifo(false);
    this.dataSource.setLogAbandoned(isDebug());
    this.dataSource.setLogExpiredConnections(isDebug());
    if (connectionPropertiesStr != null) {
        this.dataSource.setConnectionProperties(connectionPropertiesStr);
    }
    // create our first connection to detect connection problems right here
    try {
        Connection testConn = dataSource.getConnection();
        if (testConn == null) {
            throw new Exception("No initial data source available");
        } else if (isDebug()) {
            debug("Initial check connection pool: number active: " + dataSource.getNumActive() + "number idle: "
                    + dataSource.getNumIdle());
            testConn.close();
        }
    } catch (Exception e) {
        String message = "Test pool failed. URL=" + this.connectionUrl + " USER=" + this.user
                + ". Error message=" + e.getMessage();
        throw new Exception(message, e);
    }
}

From source file:edu.emory.cci.aiw.i2b2etl.ConfigurationFactory.java

private static BasicDataSource newBasicDataSource(String url) {
    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName(DRIVER_CLASS_NAME);
    bds.setUrl(url);// w w w.ja va 2s  .  co  m
    bds.setMinIdle(MIN_IDLE);
    bds.setMaxIdle(MAX_IDLE);
    bds.setMaxTotal(MAX_TOTAL);
    return bds;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java

@BeforeClass
public static void setupDatabase() throws Exception {
    InputStream inputStream = MMXTopicTagsResourceTest.class.getResourceAsStream("/test.properties");

    Properties testProperties = new Properties();
    testProperties.load(inputStream);//from  ww  w .  ja va  2 s.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;

    ds = new BasicDataSource();
    ds.setDriverClassName(driver);
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setUrl(url);

}

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  ww w  .j a  v  a2 s. co m
        Connection connection = basicDataSource.getConnection();
        assertNotNull(connection);
    } catch (SQLException e) {
        // As expected when using DBCP 1.4
    }
}

From source file:dgw.mt940.db.util.DGWBasicDataSource.java

public static DataSource setupDataSource(String connectURI, String driver, String userName, String password,
        String removeAbandoned, String initSize, String mxSize) {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driver);/*  ww w . jav  a  2s.  c o  m*/
    ds.setUrl(connectURI);
    ds.setUsername(userName);
    ds.setPassword(password);
    ds.setUrl(connectURI);
    ds.setAbandonedUsageTracking(Boolean.getBoolean(removeAbandoned));
    ds.setInitialSize(Integer.parseInt(initSize));
    ds.setMaxIdle(Integer.parseInt(mxSize));
    return ds;
}

From source file:com.joseflavio.iperoxo.IpeRoxo.java

/**
 * Inicia a {@link DataSource} e a {@link EntityManagerFactory}.
 *//*from  ww w .  jav a 2s.c  om*/
private static void executarFonteDeDados() throws IOException, NamingException {

    if (Boolean.parseBoolean(getPropriedade("DataSource.Enable"))) {
        log.info(getMensagem(null, "Log.Iniciando.DataSource"));
    } else {
        return;
    }

    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

    dataSource = new BasicDataSource();
    dataSource.setDriverClassName(getPropriedade("DataSource.Driver"));
    dataSource.setUrl(getPropriedade("DataSource.URL"));
    dataSource.setUsername(getPropriedade("DataSource.Username"));
    dataSource.setPassword(getPropriedade("DataSource.Password"));
    dataSource.setInitialSize(Integer.parseInt(getPropriedade("DataSource.InitialSize")));
    dataSource.setMaxTotal(Integer.parseInt(getPropriedade("DataSource.MaxTotal")));
    dataSource.setMinIdle(Integer.parseInt(getPropriedade("DataSource.MinIdle")));
    dataSource.setMaxIdle(Integer.parseInt(getPropriedade("DataSource.MaxIdle")));
    dataSource.setTestOnCreate(Boolean.parseBoolean(getPropriedade("DataSource.TestOnCreate")));
    dataSource.setTestWhileIdle(Boolean.parseBoolean(getPropriedade("DataSource.TestWhileIdle")));
    dataSource.setTestOnBorrow(Boolean.parseBoolean(getPropriedade("DataSource.TestOnBorrow")));
    dataSource.setTestOnReturn(Boolean.parseBoolean(getPropriedade("DataSource.TestOnReturn")));

    Context contexto = new InitialContext();
    try {
        contexto.bind("FONTE", dataSource);
    } finally {
        contexto.close();
    }

    while (true) {
        try (Connection con = getConnection()) {
            break;
        } catch (Exception e) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException f) {
            }
        }
    }

    if (Boolean.parseBoolean(getPropriedade("DataSource.JPA.Enable"))) {
        log.info(getMensagem(null, "Log.Iniciando.JPA"));
    } else {
        return;
    }

    emf = Persistence.createEntityManagerFactory("JPA");

    try {
        emf.createEntityManager().close();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

}

From source file:com.microsoft.sqlserver.jdbc.connection.PoolingTest.java

/**
 * test connection pool with Apache DBCP
 * //w  w  w  . jav a 2  s  .  c o m
 * @throws SQLException
 */
@Test
public void testApacheDBCP() throws SQLException {
    BasicDataSource ds = new BasicDataSource();
    ds.setUrl(connectionString);

    try {
        connect(ds);
    } finally {
        ds.close();
    }
}

From source file:com.uber.stream.kafka.chaperone.collector.reporter.DbAuditReporter.java

private DbAuditReporter(int queueSize, long timeBucketIntervalInSec, int reportFreqMsgCount,
        int reportFreqIntervalSec, boolean combineMetricsAmongHosts, String dbUser, String dbPass, String dbUrl,
        String dataTableName, String offsetTableName, int dbRetentionInHr, boolean enableRemoveOldRecord) {
    super(queueSize, timeBucketIntervalInSec, reportFreqMsgCount, reportFreqIntervalSec,
            combineMetricsAmongHosts);/*from  w  w  w.ja v a2s .  co m*/

    ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUsername(dbUser);
    ds.setPassword(dbPass);
    ds.setUrl(dbUrl);

    REMOVED_RECORDS_COUNTER = Metrics.getRegistry().meter(getType() + ".auditReporter.removedRecordsNumber");
    INSERTED_RECORDS_COUNTER = Metrics.getRegistry().meter(getType() + ".auditReporter.insertedRecordsNumber");
    UPDATED_RECORDS_COUNTER = Metrics.getRegistry().meter(getType() + ".auditReporter.updatedRecordsNumber");
    FAILED_TO_REMOVE_COUNTER = Metrics.getRegistry().meter(getType() + ".auditReporter.failedToRemoveNumber");
    DB_REPORT_LATENCY_TIMER = Metrics.getRegistry().timer(getType() + ".auditReporter.dbReportLatencyMs");

    Metrics.getRegistry().register(getType() + ".auditReporter.latestTSSeenLastInsert", new Gauge<Long>() {
        @Override
        public Long getValue() {
            long ret = latestTSSeenLastInsert;
            latestTSSeenLastInsert = 0;
            return ret;
        }
    });
    Metrics.getRegistry().register(getType() + ".auditReporter.earliestTSSeenLastInsert", new Gauge<Long>() {
        @Override
        public Long getValue() {
            long ret = earliestTSSeenLastInsert;
            earliestTSSeenLastInsert = System.currentTimeMillis();
            return ret;
        }
    });

    cronExecutor = Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder().setNameFormat(getType() + "-cron-executor-%d").build());

    auditDbRetentionMs = TimeUnit.HOURS.toMillis(dbRetentionInHr);
    this.dataTableName = dataTableName;
    this.offsetTableName = offsetTableName;
    this.enableRemoveOldRecord = enableRemoveOldRecord;

    logger.info("Try to create dataTable={} and offsetTable={}", dataTableName, offsetTableName);
    maybeCreateTable(CREATE_DATA_TABLE_SQL, dataTableName);
    maybeCreateTable(CREATE_OFFSET_TABLE_SQL, offsetTableName);
}