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

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

Introduction

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

Prototype

public synchronized void setUrl(String url) 

Source Link

Document

Sets the #url .

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 ww  . j a v  a  2 s  .  c  om*/
 *
 * @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.dangdang.ddframe.job.example.config.JobEventConfig.java

@Bean
public JobEventConfiguration jobEventConfiguration(@Value("${jobEventConfig.url}") final String url,
        @Value("${jobEventConfig.driverClassName}") final String driverClassName,
        @Value("${jobEventConfig.username}") final String username,
        @Value("${jobEventConfig.password}") final String password) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl(url);
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUsername(username);//ww w . j av  a  2s  .com
    dataSource.setPassword(password);
    return new JobEventRdbConfiguration(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
 *//* w ww  . j  a v  a  2 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.kerjapraktek.dataalumni.SpringConfiguration.java

@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:hsqldb:mem:test");
    dataSource.setUsername("sa");
    dataSource.setPassword("");
    return dataSource;
}

From source file:edu.infsci2560.DatabaseConfig.java

@Bean
public BasicDataSource dataSource() throws URISyntaxException {
    URI dbUri = new URI(System.getenv("DATABASE_URL"));

    String username = dbUri.getUserInfo().split(":")[0];
    String password = dbUri.getUserInfo().split(":")[1];
    String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath()
            + "?sslmode=require";

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setUrl(dbUrl);
    basicDataSource.setUsername(username);
    basicDataSource.setPassword(password);

    return basicDataSource;
}

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.  ja v  a 2  s.  c  o  m
        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.thinkbiganalytics.jira.JiraSpringTestConfig.java

@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:mysql://localhost:3306/pipeline_db");
    dataSource.setUsername("root");
    dataSource.setDriverClassName("org.mariadb.jdbc.Driver");
    //dataSource.setPassword("password");
    return dataSource;
}

From source file:de.dominikschadow.javasecurity.spring.SecurityConfig.java

@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:hsqldb:mem:hashing");
    dataSource.setUsername("hashing");
    dataSource.setPassword("hashing");
    return dataSource;
}

From source file:gobblin.metastore.MysqlStateStore.java

/**
 * creates a new {@link BasicDataSource}
 * @param config the properties used for datasource instantiation
 * @return//ww w.  j a  v  a 2s . c  o  m
 */
public static BasicDataSource newDataSource(Config config) {
    BasicDataSource basicDataSource = new BasicDataSource();
    PasswordManager passwordManager = PasswordManager.getInstance(ConfigUtils.configToProperties(config));

    basicDataSource
            .setDriverClassName(ConfigUtils.getString(config, ConfigurationKeys.STATE_STORE_DB_JDBC_DRIVER_KEY,
                    ConfigurationKeys.DEFAULT_STATE_STORE_DB_JDBC_DRIVER));
    // MySQL server can timeout a connection so need to validate connections before use
    basicDataSource.setValidationQuery("select 1");
    basicDataSource.setTestOnBorrow(true);
    basicDataSource.setDefaultAutoCommit(false);
    basicDataSource.setTimeBetweenEvictionRunsMillis(60000);
    basicDataSource.setUrl(config.getString(ConfigurationKeys.STATE_STORE_DB_URL_KEY));
    basicDataSource.setUsername(
            passwordManager.readPassword(config.getString(ConfigurationKeys.STATE_STORE_DB_USER_KEY)));
    basicDataSource.setPassword(
            passwordManager.readPassword(config.getString(ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY)));
    basicDataSource.setMinEvictableIdleTimeMillis(
            ConfigUtils.getLong(config, ConfigurationKeys.STATE_STORE_DB_CONN_MIN_EVICTABLE_IDLE_TIME_KEY,
                    ConfigurationKeys.DEFAULT_STATE_STORE_DB_CONN_MIN_EVICTABLE_IDLE_TIME));

    return basicDataSource;
}

From source file:herddb.jdbc.CommonsDBCPTest.java

@Test
public void test() throws Exception {
    try (Server server = new Server(new ServerConfiguration(folder.newFolder().toPath()))) {
        server.start();/*from   w  w w  . j a  va2  s . c o  m*/
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUrl("jdbc:herddb:server:localhost:7000?");
        dataSource.setDriverClassName(Driver.class.getName());
        try (Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery("SELECT * FROM SYSTABLES")) {
            int count = 0;
            while (rs.next()) {
                System.out.println("table: " + rs.getString(1));
                count++;
            }
            assertTrue(count > 0);
        }
        dataSource.close();

    }
}