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

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

Introduction

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

Prototype

public synchronized void setUsername(String username) 

Source Link

Document

Sets the #username .

Note: this method currently has no effect once the pool has been initialized.

Usage

From source file:com.googlesource.gerrit.plugins.ci.server.schema.CiDataSourceProvider.java

private DataSource open(Context context, CiDataSourceType dst) {
    //ConfigSection dbs = new ConfigSection(cfg, "database");
    String driver = config.getString("driver");
    if (Strings.isNullOrEmpty(driver)) {
        driver = dst.getDriver();/*from   www. ja  v  a 2  s.c  om*/
    }

    String url = config.getString("dbUrl");
    if (Strings.isNullOrEmpty(url)) {
        url = dst.getUrl();
    }

    String username = config.getString("username");
    String password = config.getString("password");
    String interceptor = config.getString("dataSourceInterceptorClass");

    boolean usePool;
    if (context == Context.SINGLE_USER) {
        usePool = false;
    } else {
        usePool = config.getBoolean("connectionpool", dst.usePool());
    }

    if (usePool) {
        final BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        if (username != null && !username.isEmpty()) {
            ds.setUsername(username);
        }
        if (password != null && !password.isEmpty()) {
            ds.setPassword(password);
        }
        ds.setMaxActive(config.getInt("poollimit", DEFAULT_POOL_LIMIT));
        ds.setMinIdle(config.getInt("poolminidle", 4));
        ds.setMaxIdle(config.getInt("poolmaxidle", 4));
        String valueString = config.getString("poolmaxwait");
        if (Strings.isNullOrEmpty(valueString)) {
            ds.setMaxWait(MILLISECONDS.convert(30, SECONDS));
        } else {
            ds.setMaxWait(ConfigUtil.getTimeUnit(valueString, MILLISECONDS.convert(30, SECONDS), MILLISECONDS));
        }
        ds.setInitialSize(ds.getMinIdle());
        exportPoolMetrics(ds);
        return intercept(interceptor, ds);
    } else {
        // Don't use the connection pool.
        //
        try {
            Properties p = new Properties();
            p.setProperty("driver", driver);
            p.setProperty("url", url);
            if (username != null) {
                p.setProperty("user", username);
            }
            if (password != null) {
                p.setProperty("password", password);
            }
            return intercept(interceptor, new SimpleDataSource(p));
        } catch (SQLException se) {
            throw new ProvisionException("Database unavailable", se);
        }
    }
}

From source file:fr.cnes.sitools.datasource.jdbc.business.SitoolsSQLDataSourceFactory.java

/**
 * Setup a dataSource for "users". Usage is for all users for consultation functions.
 * //from  w w  w  .  j  a v a 2  s  . co m
 * @param dataSource
 *          the DataSource to update
 * @return SitoolsDataSource the new DataSource
 */
public SitoolsSQLDataSource setupDataSourceForUsers(JDBCDataSource dataSource) {
    String key = dataSource.getId();
    SitoolsSQLDataSource foundDatasource = dataSources.get(key);
    if (foundDatasource == null) {

        BasicDataSource ds = new BasicDataSource();
        // OSGi
        ds.setDriverClassLoader(getClass().getClassLoader());
        ds.setDriverClassName(dataSource.getDriverClass());
        ds.setUsername(dataSource.getUserLogin());
        ds.setPassword(dataSource.getUserPassword());
        ds.setUrl(dataSource.getUrl());
        ds.setMaxActive(dataSource.getMaxActive());
        ds.setInitialSize(dataSource.getInitialSize());
        ds.setDefaultReadOnly(true);
        // test that the connection is alive on each request. If not It will be dropped from the pool and another
        // connection will be created
        ds.setTestOnBorrow(true);
        ds.setValidationQuery("SELECT 1");
        if ((dataSource.getSchemaOnConnection() != null) && !dataSource.getSchemaOnConnection().equals("")) {
            ds.setDefaultCatalog(dataSource.getSchemaOnConnection());
        }
        foundDatasource = new SitoolsSQLDataSource(dataSource, ds, dataSource.getSchemaOnConnection());
        dataSources.put(key, foundDatasource);
    }
    return foundDatasource;
}

From source file:cn.newgxu.lab.core.config.SpringBeans.java

@Bean(destroyMethod = "close")
public DataSource dataSource() {
    Properties props = new Properties();
    InputStream in = null;/* w w w.j a va  2  s .  co  m*/
    try {
        in = this.getClass().getResourceAsStream("/config/dataSource.properties");
        props.load(in);
    } catch (IOException e) {
        L.error("????", e);
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            L.error("wtf!", e);
        }
    }
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(props.getProperty("db.driver"));
    dataSource.setUrl(props.getProperty("db.url"));
    dataSource.setUsername(props.getProperty("db.username"));
    dataSource.setPassword(props.getProperty("db.password"));
    dataSource.setDefaultAutoCommit(false);
    return dataSource;
}

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  www.  jav  a  2  s .  c o m*/
        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:com.dangdang.ddframe.job.cloud.executor.TaskExecutor.java

@Override
public void registered(final ExecutorDriver executorDriver, final Protos.ExecutorInfo executorInfo,
        final Protos.FrameworkInfo frameworkInfo, final Protos.SlaveInfo slaveInfo) {
    if (!executorInfo.getData().isEmpty()) {
        Map<String, String> data = SerializationUtils.deserialize(executorInfo.getData().toByteArray());
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(data.get("event_trace_rdb_driver"));
        dataSource.setUrl(data.get("event_trace_rdb_url"));
        dataSource.setPassword(data.get("event_trace_rdb_password"));
        dataSource.setUsername(data.get("event_trace_rdb_username"));
        jobEventBus = new JobEventBus(new JobEventRdbConfiguration(dataSource));
    }//  w w  w  .  j a v a 2s .c  om
}

From source file:com.openteach.diamond.repository.client.impl.database.DataSourceFactory.java

/**
 * //from w ww  .  java 2s  . c o  m
 * @return
 */
public DataSource newInstance() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDefaultAutoCommit(true);
    dataSource.setDriverClassName(certificate.getDriverClassName());
    dataSource.setMaxActive(certificate.getMaxActive());
    dataSource.setMaxIdle(certificate.getMaxIdle());
    dataSource.setMaxWait(certificate.getMaxWait());
    dataSource.setMinIdle(certificate.getMinIdle());
    dataSource.setUsername(certificate.getUsername());
    dataSource.setPassword(certificate.getPassword());
    dataSource.setUrl(certificate.getUrl());
    return dataSource;
}

From source file:gobblin.runtime.MysqlDatasetStateStoreTest.java

@BeforeClass
public void setUp() throws Exception {
    testMetastoreDatabase = TestMetastoreDatabaseFactory.get();
    String jdbcUrl = testMetastoreDatabase.getJdbcUrl();
    ConfigBuilder configBuilder = ConfigBuilder.create();
    BasicDataSource mySqlDs = new BasicDataSource();

    mySqlDs.setDriverClassName(ConfigurationKeys.DEFAULT_STATE_STORE_DB_JDBC_DRIVER);
    mySqlDs.setDefaultAutoCommit(false);
    mySqlDs.setUrl(jdbcUrl);/* w  ww . ja  v  a2s. co  m*/
    mySqlDs.setUsername(TEST_USER);
    mySqlDs.setPassword(TEST_PASSWORD);

    dbJobStateStore = new MysqlStateStore<>(mySqlDs, TEST_STATE_STORE, false, JobState.class);

    configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_DB_URL_KEY, jdbcUrl);
    configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_DB_USER_KEY, TEST_USER);
    configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY, TEST_PASSWORD);

    ClassAliasResolver<DatasetStateStore.Factory> resolver = new ClassAliasResolver<>(
            DatasetStateStore.Factory.class);

    DatasetStateStore.Factory stateStoreFactory = resolver.resolveClass("mysql").newInstance();
    dbDatasetStateStore = stateStoreFactory.createStateStore(configBuilder.build());

    // clear data that may have been left behind by a prior test run
    dbJobStateStore.delete(TEST_JOB_NAME);
    dbDatasetStateStore.delete(TEST_JOB_NAME);
}

From source file:binky.reportrunner.service.impl.DatasourceServiceImpl.java

private DataSource getDs(RunnerDataSource runnerDs)
        throws SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException,
        PropertyVetoException, NamingException, EncryptionException {

    final String jndiDataSource = runnerDs.getJndiName();

    if (StringUtils.isBlank(jndiDataSource)) {
        EncryptionUtil enc = new EncryptionUtil();
        logger.info("using dbcp pooled connection for: " + runnerDs.getDataSourceName());

        String jdbcUser = runnerDs.getUsername();
        if (StringUtils.isBlank(runnerDs.getPassword()))
            throw new SecurityException("password is empty");
        String jdbcPassword = enc.decrpyt(secureKey, runnerDs.getPassword());

        String jdbcUrl = runnerDs.getJdbcUrl();
        String databaseDriver = runnerDs.getJdbcClass();

        Class.forName(databaseDriver).newInstance();

        BasicDataSource ds1 = new BasicDataSource();
        ds1.setDriverClassName(databaseDriver);
        ds1.setUrl(jdbcUrl);/*from w ww.  j  a v a  2s. c o m*/
        ds1.setUsername(jdbcUser);
        ds1.setPassword(jdbcPassword);
        ds1.setInitialSize(runnerDs.getInitialPoolSize());
        ds1.setMaxActive(runnerDs.getMaxPoolSize());

        ds1.setRemoveAbandoned(true);
        ds1.setRemoveAbandonedTimeout(600);

        // do not want anything updating anything
        ds1.setDefaultReadOnly(true);

        ds1.setLogAbandoned(true);
        ds1.setTestOnBorrow(true);
        ds1.setTestOnReturn(true);
        ds1.setTestWhileIdle(true);

        // does this work across all RBMS? - no it doesn't
        //ds1.setValidationQuery("select 1");
        //ds1.setValidationQueryTimeout(300);

        return ds1;
    } else {
        logger.info(
                "getting datasource from JNDI url: " + jndiDataSource + " for " + runnerDs.getDataSourceName());
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup("java:/comp/env/" + jndiDataSource);
        return ds;
    }
}

From source file:com.atypon.wayf.guice.WayfGuiceModule.java

@Provides
@Singleton//from   ww  w .  ja  v a2 s .c o m
public NamedParameterJdbcTemplate getJdbcTemplate(@Named("jdbc.driver") String driver,
        @Named("jdbc.username") String username, @Named("jdbc.password") String password,
        @Named("jdbc.url") String url, @Named("jdbc.maxActive") Integer maxActive,
        @Named("jdbc.maxIdle") Integer maxIdle, @Named("jdbc.initialSize") Integer initialSize,
        @Named("jdbc.validationQuery") String validationQuery) {
    BasicDataSource dataSource = new BasicDataSource();

    dataSource.setDriverClassName(driver);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setUrl(url);
    dataSource.setMaxActive(maxActive);
    dataSource.setMaxIdle(maxIdle);
    dataSource.setInitialSize(initialSize);
    dataSource.setValidationQuery(validationQuery);

    return new NamedParameterJdbcTemplate(dataSource);
}

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

private DataSource getDatasource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverName);/*from w  w  w .  j av a  2s. c o m*/
    ds.setUrl(getHiveJdbcUrlWithDefaultDBName());
    ds.setUsername(configuration.getHiveUsername());
    ds.setPassword(configuration.getHivePassword());
    return ds;
}