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:gr.abiss.calipso.config.DataSourceFactoryBean.java

public Object getObject() throws Exception {
    if (StringUtils.hasText(dataSourceJndiName)) {
        logger.info("JNDI datasource requested, looking up datasource from JNDI name: '" + dataSourceJndiName
                + "'");
        JndiObjectFactoryBean factoryBean = new JndiObjectFactoryBean();
        factoryBean.setJndiName(dataSourceJndiName);
        // "java:comp/env/" will be prefixed if the JNDI name doesn't already have it
        factoryBean.setResourceRef(true);
        // this step actually does the JNDI lookup
        try {/*w ww.j  a  v a 2s  .c  o  m*/
            factoryBean.afterPropertiesSet();
        } catch (Exception e) {
            logger.error("datasource init from JNDI failed : " + e);
            logger.error("aborting application startup");
            throw new RuntimeException(e);
        }
        dataSource = (DataSource) factoryBean.getObject();
    } else if (url.startsWith("jdbc:hsqldb:file")) {
        logger.info("embedded HSQLDB mode detected, switching on spring single connection data source");
        SingleConnectionDataSource ds = new SingleConnectionDataSource();
        ds.setUrl(url);
        ds.setDriverClassName(driverClassName);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setSuppressClose(true);
        dataSource = ds;
    } else {
        logger.info(
                "Not using embedded HSQLDB or JNDI datasource, switching on Apache DBCP data source connection pooling");
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(url);
        ds.setDriverClassName(driverClassName);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setValidationQuery(validationQuery);
        ds.setTestOnBorrow(false);
        ds.setTestWhileIdle(true);
        ds.setTimeBetweenEvictionRunsMillis(600000);
        dataSource = ds;
    }
    return dataSource;
}

From source file:eu.celarcloud.celar_ms.ServerPack.Database.MySQL.DBHandlerWithConnPool.java

public void dbConnect() {
    try {/*from ww w  .  ja v  a2s  . c om*/
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://" + host + "/" + database);
        dataSource.setUsername(user);
        dataSource.setPassword(pass);
        dataSource.setMaxActive(CONN_NUM);
        //dataSource.setMinIdle(CONN_NUM/2);
        dataSource.setMinIdle(CONN_NUM);
        dataSource.setInitialSize(CONN_NUM);

        //           System.out.println("Creating a connection...");
        this.server.writeToLog(Level.INFO, "MySQL DBHandler>> creating a connection...");

        //connected, but does database exist?
        conn = dataSource.getConnection();
        resultSet = conn.getMetaData().getCatalogs();
        boolean found = false;
        while (resultSet.next()) {
            String databaseName = resultSet.getString(1);
            if (databaseName.equals(database)) {
                //                 System.out.println("Database exists...");
                this.server.writeToLog(Level.INFO, "MySQL DBHandler>> Connected to JCatascopia DB...");
                found = true;
            }
        }
        if (!found)
            //             System.out.println("Database doesn't exist...");
            this.server.writeToLog(Level.INFO, "DBHandler>> database doesn't exist...");
        this.resultSet.close();
    } catch (SQLException e) {
        this.server.writeToLog(Level.SEVERE, e);
    } catch (Exception e) {
        this.server.writeToLog(Level.SEVERE, e);
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            this.server.writeToLog(Level.SEVERE, e);
        }
    }
}

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 a v  a2 s .co  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:cn.cuizuoli.gotour.config.DataSourceConfig.java

@Bean
public DataSource userDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(env.getRequiredProperty("user.jdbc.driverClassName"));
    dataSource.setUrl(env.getRequiredProperty("user.jdbc.url"));
    dataSource.setUsername(env.getRequiredProperty("user.jdbc.username"));
    dataSource.setPassword(env.getRequiredProperty("user.jdbc.password"));
    dataSource.setInitialSize(env.getRequiredProperty("jdbc.initialSize", Integer.class));
    dataSource.setMaxActive(env.getRequiredProperty("jdbc.maxActive", Integer.class));
    dataSource.setMaxIdle(env.getRequiredProperty("jdbc.maxIdle", Integer.class));
    dataSource.setMinIdle(env.getRequiredProperty("jdbc.minIdle", Integer.class));
    dataSource.setDefaultAutoCommit(env.getRequiredProperty("jdbc.defaultAutoCommit", Boolean.class));
    dataSource.setPoolPreparedStatements(env.getRequiredProperty("jdbc.poolPreparedStatements", Boolean.class));
    dataSource.setValidationQuery(env.getRequiredProperty("jdbc.validationQuery"));
    dataSource.setTestOnBorrow(env.getRequiredProperty("jdbc.testOnBorrow", Boolean.class));
    dataSource.setTestOnReturn(env.getRequiredProperty("jdbc.testOnReturn", Boolean.class));
    dataSource.setTestWhileIdle(env.getRequiredProperty("jdbc.testWhileIdle", Boolean.class));
    dataSource.setTimeBetweenEvictionRunsMillis(
            env.getRequiredProperty("jdbc.timeBetweenEvictionRunsMillis", Long.class));
    dataSource.setNumTestsPerEvictionRun(env.getRequiredProperty("jdbc.numTestsPerEvictionRun", Integer.class));
    dataSource.setMinEvictableIdleTimeMillis(
            env.getRequiredProperty("jdbc.minEvictableIdleTimeMillis", Long.class));
    return dataSource;
}

From source file:edu.ncsa.uiuc.rdfrepo.testing.USeekMSailFac.java

public static IndexingSail getIndexingSail(String dburl, String dbuser, String password,
        String capturepredicate, RepositorySail sail) throws SailException {
    //set tup the postgis datasource for indexer

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.postgresql.Driver");
    dataSource.setUrl(dburl);/*from   w w w  .  j  ava2s  .c o m*/
    dataSource.setUsername(dbuser);
    dataSource.setPassword(password);
    PostgisIndexerSettings indexerSettings = new PostgisIndexerSettings();
    indexerSettings.setDataSource(dataSource);

    String patternString = "?observation <http://purl.oclc.org/NET/ssnx/ssn#observationResultTime> ?time."
            + "?time  <http://www.w3.org/2006/time#inXSDDateTime> ?timevalue. "
            + "?loc <http://www.opengis.net/rdf#hasWKT> ?coord. "
            + "?sensor <http://www.loa-cnr.it/ontologies/DUL.owl#hasLocation> ?loc."
            + "?observation <http://purl.oclc.org/NET/ssnx/ssn#observedBy> ?sensor. ";

    //        String patternString =
    //            "?geometry <http://www.opengis.net/rdf#hasWKT> ?wkt.";

    sail.initialize();
    indexerSettings.setMatchSatatments(createPatternFromString(patternString, sail));
    indexerSettings.setDataSource(dataSource);

    //a matcher decides which object should be indexed by its associated predicate, we can use "http://www.opengis.net/rdf#hasWKT"
    PostgisIndexMatcher matcher = new PostgisIndexMatcher();
    matcher.setPredicate(capturepredicate);

    //create a IndexingSail from the basic sail and the indexer
    indexerSettings.setMatchers(Arrays.asList(new PostgisIndexMatcher[] { matcher }));
    return null;

    //        PartitionDef p = new P
    //        IndexingSail indexingSail = new IndexingSail(sail, indexerSettings);
    //
    //        indexingSail.initialize();
    //        return indexingSail;
}

From source file:com.metamx.druid.db.DbConnector.java

private DataSource getDatasource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUsername(config.getDatabaseUser());
    dataSource.setPassword(config.getDatabasePassword());
    dataSource.setUrl(config.getDatabaseConnectURI());

    if (config.useValidationQuery()) {
        dataSource.setValidationQuery(config.getValidationQuery());
        dataSource.setTestOnBorrow(true);
    }// w w  w .  ja v  a2s  .c  om

    return dataSource;
}

From source file:fr.gouv.diplomatie.applitutoriel.integration.conf.DataSourceConf.java

@Bean
public DataSource dataSource() {
    final BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);/*from w  w w . j  av a 2 s .c o m*/
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setValidationQuery(validationQuery);
    dataSource.setMaxActive(maxActive);
    dataSource.setMaxIdle(maxIdle);
    dataSource.setMaxWait(maxWait);
    dataSource.setTestOnBorrow(testOnBorrow);
    dataSource.setTestWhileIdle(testWhileIdle);
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    dataSource.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    dataSource.setRemoveAbandoned(removeAbandoned);
    dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
    dataSource.setLogAbandoned(logAbandoned);
    return dataSource;
}

From source file:com.cws.esolutions.core.listeners.CoreServiceInitializer.java

/**
 * Initializes the core service in a standalone mode - used for applications outside of a container or when
 * run as a standalone jar.//  www.  j ava  2s . c om
 *
 * @param configFile - The service configuration file to utilize
 * @param logConfig - The logging configuration file to utilize
 * @param loadSecurity - Flag to start security
 * @param startConnections - Flag to start connections
 * @throws CoreServiceException @{link com.cws.esolutions.core.exception.CoreServiceException}
 * if an exception occurs during initialization
 */
public static void initializeService(final String configFile, final String logConfig,
        final boolean loadSecurity, final boolean startConnections) throws CoreServiceException {
    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfig secConfig = null;
    CoreConfigurationData configData = null;
    SecurityConfigurationData secConfigData = null;

    if (loadSecurity) {
        secConfigData = SecurityServiceBean.getInstance().getConfigData();
        secConfig = secConfigData.getSecurityConfig();
    }

    final String serviceConfig = (StringUtils.isBlank(configFile)) ? System.getProperty("coreConfigFile")
            : configFile;
    final String loggingConfig = (StringUtils.isBlank(logConfig)) ? System.getProperty("coreLogConfig")
            : logConfig;

    try {
        try {
            DOMConfigurator.configure(Loader.getResource(loggingConfig));
        } catch (NullPointerException npx) {
            try {
                DOMConfigurator.configure(FileUtils.getFile(loggingConfig).toURI().toURL());
            } catch (NullPointerException npx1) {
                System.err.println("Unable to load logging configuration. No logging enabled!");
                System.err.println("");
                npx1.printStackTrace();
            }
        }

        xmlURL = CoreServiceInitializer.class.getClassLoader().getResource(serviceConfig);

        if (xmlURL == null) {
            // try loading from the filesystem
            xmlURL = FileUtils.getFile(configFile).toURI().toURL();
        }

        context = JAXBContext.newInstance(CoreConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL);

        CoreServiceInitializer.appBean.setConfigData(configData);

        if (startConnections) {
            Map<String, DataSource> dsMap = CoreServiceInitializer.appBean.getDataSources();

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

            if (dsMap == null) {
                dsMap = new HashMap<String, DataSource>();
            }

            for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                if (!(dsMap.containsKey(mgr.getDsName()))) {
                    StringBuilder sBuilder = new StringBuilder()
                            .append("connectTimeout=" + mgr.getConnectTimeout() + ";")
                            .append("socketTimeout=" + mgr.getConnectTimeout() + ";")
                            .append("autoReconnect=" + mgr.getAutoReconnect() + ";")
                            .append("zeroDateTimeBehavior=convertToNull");

                    if (DEBUG) {
                        DEBUGGER.debug("StringBuilder: {}", sBuilder);
                    }

                    BasicDataSource dataSource = new BasicDataSource();
                    dataSource.setDriverClassName(mgr.getDriver());
                    dataSource.setUrl(mgr.getDataSource());
                    dataSource.setUsername(mgr.getDsUser());
                    dataSource.setConnectionProperties(sBuilder.toString());
                    dataSource.setPassword(PasswordUtils.decryptText(mgr.getDsPass(), mgr.getSalt(),
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            configData.getAppConfig().getEncoding()));
                    if (DEBUG) {
                        DEBUGGER.debug("BasicDataSource: {}", dataSource);
                    }

                    dsMap.put(mgr.getDsName(), dataSource);
                }
            }

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

            CoreServiceInitializer.appBean.setDataSources(dsMap);
        }
    } catch (JAXBException jx) {
        jx.printStackTrace();
        throw new CoreServiceException(jx.getMessage(), jx);
    } catch (MalformedURLException mux) {
        mux.printStackTrace();
        throw new CoreServiceException(mux.getMessage(), mux);
    }
}

From source file:de.langmi.spring.batch.examples.readers.jdbc.JdbcPagingItemReaderTests.java

/**
 * Setup Datasource and create table for test.
 *
 * @throws Exception //from   w w  w  .  j av a 2 s . c o m
 */
@Before
public void setUp() throws Exception {
    // DataSource Setup, apache commons 
    dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
    dataSource.setUrl("jdbc:hsqldb:mem:testdb");
    dataSource.setUsername("sa");
    dataSource.setPassword("");

    // drop table if exists
    Connection conn = dataSource.getConnection();
    Statement st = conn.createStatement();
    st.execute(DROP_TEST_TABLE);
    conn.commit();
    st.close();
    conn.close();

    // create table
    conn = dataSource.getConnection();
    st = conn.createStatement();
    st.execute(CREATE_TEST_TABLE);
    conn.commit();
    st.close();
    conn.close();

    // fill with values
    conn = dataSource.getConnection();
    // prevent auto commit for batching
    conn.setAutoCommit(false);
    PreparedStatement ps = conn.prepareStatement(INSERT);
    // fill with values
    for (int i = 0; i < EXPECTED_COUNT; i++) {
        ps.setString(1, String.valueOf(i));
        ps.addBatch();
    }
    ps.executeBatch();
    conn.commit();
    ps.close();
    conn.close();
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceInitializer.java

/**
 * Initializes the security service in a standalone mode - used for applications outside of a container or when
 * run as a standalone jar.//from w w w .j  a  va2 s  . co  m
 *
 * @param configFile - The security configuration file to utilize
 * @param logConfig - The logging configuration file to utilize
 * @param startConnections - Configure, load and start repository connections
 * @throws SecurityServiceException @{link com.cws.esolutions.security.exception.SecurityServiceException}
 * if an exception occurs during initialization
 */
public static void initializeService(final String configFile, final String logConfig,
        final boolean startConnections) throws SecurityServiceException {
    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ClassLoader classLoader = SecurityServiceInitializer.class.getClassLoader();
    final String serviceConfig = (StringUtils.isBlank(configFile)) ? System.getProperty("configFileFile")
            : configFile;
    final String loggingConfig = (StringUtils.isBlank(logConfig)) ? System.getProperty("secLogConfig")
            : logConfig;

    try {
        try {
            DOMConfigurator.configure(Loader.getResource(loggingConfig));
        } catch (NullPointerException npx) {
            try {
                DOMConfigurator.configure(FileUtils.getFile(loggingConfig).toURI().toURL());
            } catch (NullPointerException npx1) {
                System.err.println("Unable to load logging configuration. No logging enabled!");
                System.err.println("");
                npx1.printStackTrace();
            }
        }

        xmlURL = classLoader.getResource(serviceConfig);

        if (xmlURL == null) {
            // try loading from the filesystem
            xmlURL = FileUtils.getFile(serviceConfig).toURI().toURL();
        }

        context = JAXBContext.newInstance(SecurityConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

        SecurityServiceInitializer.svcBean.setConfigData(configData);

        if (startConnections) {
            DAOInitializer.configureAndCreateAuthConnection(
                    new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                    false, SecurityServiceInitializer.svcBean);

            Map<String, DataSource> dsMap = SecurityServiceInitializer.svcBean.getDataSources();

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

            if (configData.getResourceConfig() != null) {
                if (dsMap == null) {
                    dsMap = new HashMap<String, DataSource>();
                }

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    if (!(dsMap.containsKey(mgr.getDsName()))) {
                        StringBuilder sBuilder = new StringBuilder()
                                .append("connectTimeout=" + mgr.getConnectTimeout() + ";")
                                .append("socketTimeout=" + mgr.getConnectTimeout() + ";")
                                .append("autoReconnect=" + mgr.getAutoReconnect() + ";")
                                .append("zeroDateTimeBehavior=convertToNull");

                        if (DEBUG) {
                            DEBUGGER.debug("StringBuilder: {}", sBuilder);
                        }

                        BasicDataSource dataSource = new BasicDataSource();
                        dataSource.setDriverClassName(mgr.getDriver());
                        dataSource.setUrl(mgr.getDataSource());
                        dataSource.setUsername(mgr.getDsUser());
                        dataSource.setConnectionProperties(sBuilder.toString());
                        dataSource.setPassword(PasswordUtils.decryptText(mgr.getDsPass(), mgr.getDsSalt(),
                                configData.getSecurityConfig().getSecretAlgorithm(),
                                configData.getSecurityConfig().getIterations(),
                                configData.getSecurityConfig().getKeyBits(),
                                configData.getSecurityConfig().getEncryptionAlgorithm(),
                                configData.getSecurityConfig().getEncryptionInstance(),
                                configData.getSystemConfig().getEncoding()));

                        if (DEBUG) {
                            DEBUGGER.debug("BasicDataSource: {}", dataSource);
                        }

                        dsMap.put(mgr.getDsName(), dataSource);
                    }
                }

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

                SecurityServiceInitializer.svcBean.setDataSources(dsMap);
            }
        }
    } catch (JAXBException jx) {
        jx.printStackTrace();
        throw new SecurityServiceException(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        fnfx.printStackTrace();
        throw new SecurityServiceException(fnfx.getMessage(), fnfx);
    } catch (MalformedURLException mux) {
        mux.printStackTrace();
        throw new SecurityServiceException(mux.getMessage(), mux);
    } catch (SecurityException sx) {
        sx.printStackTrace();
        throw new SecurityServiceException(sx.getMessage(), sx);
    }
}