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

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

Introduction

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

Prototype

BasicDataSource

Source Link

Usage

From source file:io.apiman.gateway.engine.policies.BasicAuthenticationPolicyTest.java

/**
 * Creates an in-memory datasource./*from w  w w .  j  av a 2 s. com*/
 * @throws SQLException
 */
private static BasicDataSource createInMemoryDatasource() throws SQLException {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(Driver.class.getName());
    ds.setUsername("sa"); //$NON-NLS-1$
    ds.setPassword(""); //$NON-NLS-1$
    ds.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"); //$NON-NLS-1$
    Connection connection = ds.getConnection();
    connection.prepareStatement(
            "CREATE TABLE users ( username varchar(255) NOT NULL, password varchar(255) NOT NULL, PRIMARY KEY (username) )")
            .executeUpdate();
    connection.prepareStatement(
            "INSERT INTO users (username, password) VALUES ('bwayne', 'ae2efd698aefdf366736a4eda1bc5241f9fbfec7')")
            .executeUpdate();
    connection.prepareStatement(
            "INSERT INTO users (username, password) VALUES ('ckent', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')")
            .executeUpdate();
    connection.close();
    return ds;
}

From source file:com.amazon.carbonado.repo.jdbc.TestH2.java

private RepositoryBuilder jdbcBuilder(boolean isMaster) throws RepositoryException {
    JDBCRepositoryBuilder builder = new JDBCRepositoryBuilder();
    builder.setName("jdbc");
    builder.setAutoVersioningEnabled(true, null);
    builder.setMaster(isMaster);/*from  w w w. j av  a 2  s  .  c om*/
    BasicDataSource ds = new BasicDataSource();
    builder.setDataSource(ds);

    builder.setSchemaResolver(new H2SchemaResolver());

    File dir = new File(TestUtilities.makeTestDirectory("jdbc"), "/h2");
    String url = "jdbc:h2:" + dir.getPath();
    ds.setDriverClassName("org.h2.Driver");
    ds.setUrl(url);
    ds.setUsername("sa");
    ds.setPassword("");

    return builder;
}

From source file:com.thinkbiganalytics.nifi.v2.thrift.RefreshableDataSource.java

private DataSource create() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setDriverClassLoader(driverClassLoader);
    dataSource.setUrl(url);/*from   w  w w .  ja va2s.co m*/
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}

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
 *//*from   w w w .jav  a2  s. c o  m*/
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.norconex.collector.http.db.impl.derby.DerbyCrawlURLDatabase.java

private DataSource createDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    ds.setUrl("jdbc:derby:" + dbDir + ";create=true");
    ds.setDefaultAutoCommit(true);/*from  ww w .  j av a2  s  . c o  m*/
    return ds;
}

From source file:com.mirth.connect.connectors.jdbc.JdbcConnector.java

private void setupDataSource(String address, String driver, String username, String password) {
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(driver);
    basicDataSource.setUsername(username);
    basicDataSource.setPassword(password);
    basicDataSource.setUrl(address);/*from  w w w  .j a v  a 2  s.co m*/
    dataSource = basicDataSource;
}

From source file:com.uber.hoodie.utilities.HiveIncrementalPuller.java

private DataSource getDatasource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverName);/*from  ww  w.ja v  a  2 s.  c  o  m*/
    ds.setUrl(config.hiveJDBCUrl);
    ds.setUsername(config.hiveUsername);
    ds.setPassword(config.hivePassword);
    return ds;
}

From source file:com.aurel.track.dbase.DatabaseHandler.java

private static void checkForDatabase() {
    try {/*  ww w. j  a  va2  s  .co  m*/
        BasicDataSource ds = new BasicDataSource();
        ds.setUsername(user);
        ds.setPassword(password);
        ds.setDriverClassName(getJdbcDriver());
        ds.setUrl(getJdbcUrl());
        testConnection();
        // createDatabaseInt(ds, fileNameSchema);
        System.out.println("Can access database");
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:fr.dyade.aaa.util.MySqlDBRepository.java

private Connection getConnection() throws SQLException {
    ds = new BasicDataSource();
    ds.setDriverClassName(driver);//w w w.  j a v a2  s .  c o m
    ds.setUsername(user);
    ds.setPassword(pass);
    ds.setUrl(connurl);

    return ds.getConnection();
}

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 {/*  ww  w  .j  a v  a  2s . co  m*/
            this.connection = ds.getConnection();
        } catch (SQLException e) {
            throw new HoodieHiveSyncException(
                    "Cannot create hive connection " + getHiveJdbcUrlWithDefaultDBName(), e);
        }
    }
}