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

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

Introduction

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

Prototype

public synchronized void setDriverClassName(String driverClassName) 

Source Link

Document

Sets the jdbc driver class name.

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

Usage

From source file:net.sf.taverna.t2.provenance.api.ProvenanceAccess.java

/**
 * Initialises a named JNDI DataSource if not already set up externally.
 * The DataSource is named jdbc/taverna//from  w  w w.j av a  2  s. c o  m
 *
 * @param driverClassName - the classname for the driver to be used.
 * @param jdbcUrl - the jdbc connection url
 * @param username - the username, if required (otherwise null)
 * @param password - the password, if required (oteherwise null)
 * @param minIdle - if the driver supports multiple connections, then the minumum number of idle connections in the pool
 * @param maxIdle - if the driver supports multiple connections, then the maximum number of idle connections in the pool
 * @param maxActive - if the driver supports multiple connections, then the minumum number of connections in the pool
 */
public static void initDataSource(String driverClassName, String jdbcUrl, String username, String password,
        int minIdle, int maxIdle, int maxActive) {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory");
    System.setProperty("org.osjava.sj.jndi.shared", "true");

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setMaxIdle(maxIdle);
    ds.setDefaultAutoCommit(true);
    if (username != null) {
        ds.setUsername(username);
    }
    if (password != null) {
        ds.setPassword(password);
    }

    ds.setUrl(jdbcUrl);

    InitialContext context;
    try {
        context = new InitialContext();
        context.rebind("jdbc/taverna", ds);
    } catch (NamingException ex) {
        logger.error("Problem rebinding the jdbc context: " + ex);
    }

}

From source file:com.alfaariss.oa.util.database.jdbc.DataSourceFactory.java

private static DataSource createByConfiguration(IConfigurationManager configurationManager, Element eConfig)
        throws DatabaseException {
    BasicDataSource ds = null;
    try {//from  w  w  w.  j a  va 2 s .  com
        ds = new BasicDataSource();

        String sDriver = configurationManager.getParam(eConfig, "driver");
        if (sDriver == null) {
            _logger.warn("No 'driver' item found in configuration");
            throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
        }
        ds.setDriverClassName(sDriver);

        String sURL = configurationManager.getParam(eConfig, "url");
        if (sURL == null) {
            _logger.warn("No 'url' item found in configuration");
            throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
        }
        ds.setUrl(sURL);

        String sUser = configurationManager.getParam(eConfig, "username");
        if (sUser == null) {
            _logger.warn("No 'username' item found in configuration");
            throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
        }
        ds.setUsername(sUser);

        String sPassword = configurationManager.getParam(eConfig, "password");
        if (sPassword == null) {
            _logger.warn("No 'password' item found in configuration");
            throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
        }
        ds.setPassword(sPassword);

        addOptionalSettings(configurationManager, eConfig, ds);
    } catch (DatabaseException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not initialize object", e);
        throw new DatabaseException(SystemErrors.ERROR_INTERNAL);
    }
    return ds;
}

From source file:com.alibaba.cobar.manager.qa.modle.CobarFactory.java

public static CobarAdapter getCobarAdapter(String cobarNodeName) throws IOException {
    CobarAdapter cAdapter = new CobarAdapter();
    Properties prop = new Properties();
    prop.load(CobarFactory.class.getClassLoader().getResourceAsStream("cobarNode.properties"));
    BasicDataSource ds = new BasicDataSource();
    String user = prop.getProperty(cobarNodeName + ".user").trim();
    String password = prop.getProperty(cobarNodeName + ".password").trim();
    String ip = prop.getProperty(cobarNodeName + ".ip").trim();
    int managerPort = Integer.parseInt(prop.getProperty(cobarNodeName + ".manager.port").trim());
    int maxActive = -1;
    int minIdle = 0;
    long timeBetweenEvictionRunsMillis = 10 * 60 * 1000;
    int numTestsPerEvictionRun = Integer.MAX_VALUE;
    long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
    ds.setUsername(user);//w w  w .  j av  a  2 s . c  o m
    ds.setPassword(password);
    ds.setUrl(new StringBuilder().append("jdbc:mysql://").append(ip).append(":").append(managerPort).append("/")
            .toString());
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    ds.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

    cAdapter.setDataSource(ds);
    return cAdapter;
}

From source file:com.cws.esolutions.security.utils.DAOInitializer.java

/**
 * @param properties - The <code>AuthRepo</code> object containing connection information
 * @param isContainer - A <code>boolean</code> flag indicating if this is in a container
 * @param bean - The {@link com.cws.esolutions.security.SecurityServiceBean} <code>SecurityServiceBean</code> that holds the connection
 * @throws SecurityServiceException {@link com.cws.esolutions.security.exception.SecurityServiceException}
 * if an exception occurs opening the connection
 *///ww  w.j av  a  2 s. c  om
public synchronized static void configureAndCreateAuthConnection(final InputStream properties,
        final boolean isContainer, final SecurityServiceBean bean) throws SecurityServiceException {
    String methodName = DAOInitializer.CNAME
            + "#configureAndCreateAuthConnection(final String properties, final boolean isContainer, final SecurityServiceBean bean) throws SecurityServiceException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("InputStream: {}", properties);
        DEBUGGER.debug("isContainer: {}", isContainer);
        DEBUGGER.debug("SecurityServiceBean: {}", bean);
    }

    try {
        Properties connProps = new Properties();
        connProps.load(properties);

        if (DEBUG) {
            DEBUGGER.debug("Properties: {}", connProps);
        }

        AuthRepositoryType repoType = AuthRepositoryType
                .valueOf(connProps.getProperty(DAOInitializer.REPO_TYPE));
        RepositoryConnectionType connType = RepositoryConnectionType
                .valueOf(connProps.getProperty(DAOInitializer.CONN_TYPE));

        if (DEBUG) {
            DEBUGGER.debug("AuthRepositoryType: {}", repoType);
            DEBUGGER.debug("RepositoryConnectionType: {}", connType);
        }

        switch (repoType) {
        case LDAP:
            SSLUtil sslUtil = null;
            LDAPConnection ldapConn = null;
            LDAPConnectionPool connPool = null;
            LDAPConnectionOptions connOpts = new LDAPConnectionOptions();

            connOpts.setAutoReconnect(true);
            connOpts.setAbandonOnTimeout(true);
            connOpts.setBindWithDNRequiresPassword(true);
            connOpts.setConnectTimeoutMillis(
                    Integer.parseInt(connProps.getProperty(DAOInitializer.CONN_TIMEOUT)));
            connOpts.setResponseTimeoutMillis(
                    Integer.parseInt(connProps.getProperty(DAOInitializer.READ_TIMEOUT)));

            if (DEBUG) {
                DEBUGGER.debug("LDAPConnectionOptions: {}", connOpts);
            }

            switch (connType) {
            case CONNECTION_TYPE_INSECURE:
                ldapConn = new LDAPConnection(connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT)));

                if (DEBUG) {
                    DEBUGGER.debug("LDAPConnection: {}", ldapConn);
                }

                if (!(ldapConn.isConnected())) {
                    throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
                }

                connPool = new LDAPConnectionPool(ldapConn,
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)));

                break;
            case CONNECTION_TYPE_SSL:
                sslUtil = new SSLUtil(new TrustStoreTrustManager(
                        connProps.getProperty(DAOInitializer.TRUST_FILE),
                        PasswordUtils
                                .decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS),
                                        connProps.getProperty(DAOInitializer.TRUST_SALT),
                                        secConfig.getSecretAlgorithm(), secConfig.getIterations(),
                                        secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                                        secConfig.getEncryptionInstance(), systemConfig.getEncoding())
                                .toCharArray(),
                        connProps.getProperty(DAOInitializer.TRUST_TYPE), true));

                if (DEBUG) {
                    DEBUGGER.debug("SSLUtil: {}", sslUtil);
                }

                SSLSocketFactory sslSocketFactory = sslUtil.createSSLSocketFactory();

                if (DEBUG) {
                    DEBUGGER.debug("SSLSocketFactory: {}", sslSocketFactory);
                }

                ldapConn = new LDAPConnection(sslSocketFactory, connOpts,
                        connProps.getProperty(DAOInitializer.REPOSITORY_HOST),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT)));

                if (DEBUG) {
                    DEBUGGER.debug("LDAPConnection: {}", ldapConn);
                }

                if (!(ldapConn.isConnected())) {
                    throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
                }

                connPool = new LDAPConnectionPool(ldapConn,
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)));

                break;
            case CONNECTION_TYPE_TLS:
                ldapConn = new LDAPConnection(connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT)));

                if (DEBUG) {
                    DEBUGGER.debug("LDAPConnection: {}", ldapConn);
                }

                if (!(ldapConn.isConnected())) {
                    throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
                }

                sslUtil = new SSLUtil(new TrustStoreTrustManager(
                        connProps.getProperty(DAOInitializer.TRUST_FILE),
                        PasswordUtils
                                .decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS),
                                        connProps.getProperty(DAOInitializer.TRUST_SALT),
                                        secConfig.getSecretAlgorithm(), secConfig.getIterations(),
                                        secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                                        secConfig.getEncryptionInstance(), systemConfig.getEncoding())
                                .toCharArray(),
                        connProps.getProperty(DAOInitializer.TRUST_TYPE), true));

                if (DEBUG) {
                    DEBUGGER.debug("SSLUtil: {}", sslUtil);
                }

                SSLContext sslContext = sslUtil.createSSLContext();

                if (DEBUG) {
                    DEBUGGER.debug("SSLContext: {}", sslContext);
                }

                StartTLSExtendedRequest startTLS = new StartTLSExtendedRequest(sslContext);

                if (DEBUG) {
                    DEBUGGER.debug("StartTLSExtendedRequest: {}", startTLS);
                }

                ExtendedResult extendedResult = ldapConn.processExtendedOperation(startTLS);

                if (DEBUG) {
                    DEBUGGER.debug("ExtendedResult: {}", extendedResult);
                }

                BindRequest bindRequest = new SimpleBindRequest(
                        connProps.getProperty(DAOInitializer.REPOSITORY_USER),
                        PasswordUtils.decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS),
                                connProps.getProperty(DAOInitializer.TRUST_SALT),
                                secConfig.getSecretAlgorithm(), secConfig.getIterations(),
                                secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                                secConfig.getEncryptionInstance(), systemConfig.getEncoding()));

                if (DEBUG) {
                    DEBUGGER.debug("BindRequest: {}", bindRequest);
                }

                BindResult bindResult = ldapConn.bind(bindRequest);

                if (DEBUG) {
                    DEBUGGER.debug("BindResult: {}", bindResult);
                }

                StartTLSPostConnectProcessor tlsProcessor = new StartTLSPostConnectProcessor(sslContext);

                if (DEBUG) {
                    DEBUGGER.debug("StartTLSPostConnectProcessor: {}", tlsProcessor);
                }

                connPool = new LDAPConnectionPool(ldapConn,
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)),
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)), tlsProcessor);

                break;
            }

            if (DEBUG) {
                DEBUGGER.debug("LDAPConnectionPool: {}", connPool);
            }

            if ((connPool == null) || (connPool.isClosed())) {
                throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection");
            }

            bean.setAuthDataSource(connPool);
            break;
        case SQL:
            // the isContainer only matters here
            if (isContainer) {
                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup(DAOInitializer.DS_CONTEXT);

                bean.setAuthDataSource(envContext.lookup(DAOInitializer.REPOSITORY_HOST));
            } else {
                BasicDataSource dataSource = new BasicDataSource();
                dataSource.setInitialSize(
                        Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)));
                dataSource
                        .setMaxActive(Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)));
                dataSource.setDriverClassName(connProps.getProperty(DAOInitializer.CONN_DRIVER));
                dataSource.setUrl(connProps.getProperty(DAOInitializer.REPOSITORY_HOST));
                dataSource.setUsername(connProps.getProperty(DAOInitializer.REPOSITORY_USER));
                dataSource.setPassword(PasswordUtils.decryptText(
                        connProps.getProperty(DAOInitializer.REPOSITORY_PASS),
                        connProps.getProperty(DAOInitializer.REPOSITORY_SALT), secConfig.getSecretAlgorithm(),
                        secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(),
                        secConfig.getEncryptionInstance(), systemConfig.getEncoding()));

                bean.setAuthDataSource(dataSource);
            }

            break;
        case NONE:
            return;
        default:
            throw new SecurityServiceException("Unhandled ResourceType");
        }
    } catch (LDAPException lx) {
        throw new SecurityServiceException(lx.getMessage(), lx);
    } catch (GeneralSecurityException gsx) {
        throw new SecurityServiceException(gsx.getMessage(), gsx);
    } catch (NamingException nx) {
        throw new SecurityServiceException(nx.getMessage(), nx);
    } catch (FileNotFoundException fnfx) {
        throw new SecurityServiceException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new SecurityServiceException(iox.getMessage(), iox);
    }
}

From source file:com.abixen.platform.common.configuration.AbstractPlatformDataSourceConfiguration.java

@Bean(destroyMethod = "close")
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(platformJdbcConfiguration.getDriverClassName());
    dataSource.setUrl(platformJdbcConfiguration.getDatabaseUrl());
    dataSource.setUsername(platformJdbcConfiguration.getUsername());
    dataSource.setPassword(platformJdbcConfiguration.getPassword());
    return dataSource;
}

From source file:com.spankr.tutorial.ConnectionDAO.java

/**
 * Git me mah datasource!/*from   ww w  . jav  a 2s.  c om*/
 * 
 * @return datasource pointing at the DEV version of partsearch
 */
public DataSource getDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
    ds.setUrl("jdbc:hsqldb:mem:sampleDB");
    ds.setUsername("SA");
    ds.setPassword("");
    ds.setInitialSize(2);
    ds.setMaxActive(20);
    return ds;
}

From source file:br.com.shopcarpet.test.db.TestConnectDataBase.java

private DataSource getConnection() {
    final BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost/carpet");
    ds.setUsername("carpet");
    ds.setPassword("carpet123");
    return ds;//  w  w w .  j  av a 2 s .c  o m
}

From source file:general.conexion.Pool.java

public void inicializarDataSource() {
    BasicDataSource basic = new BasicDataSource();
    basic.setDriverClassName(driver);
    basic.setUsername(usuario);//w  ww .j  a v  a2  s .c  o m
    basic.setPassword(contrasena);
    basic.setUrl(url);
    basic.setMaxActive(5);
    this.dataSource = basic;
}

From source file:com.apress.prospringintegration.batch.JdbcConfiguration.java

@Bean(destroyMethod = "close")
public BasicDataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);/*from   ww w  . j  a v  a  2s.  com*/
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}

From source file:com.mycompany.geocoordinate.config.DataConfig.java

@Bean
public DataSource getDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/Mybatis");
    dataSource.setUsername("root");
    dataSource.setPassword("");

    return dataSource;

}