Example usage for org.apache.commons.dbcp2 BasicDataSourceFactory createDataSource

List of usage examples for org.apache.commons.dbcp2 BasicDataSourceFactory createDataSource

Introduction

In this page you can find the example usage for org.apache.commons.dbcp2 BasicDataSourceFactory createDataSource.

Prototype

public static BasicDataSource createDataSource(Properties properties) throws Exception 

Source Link

Document

Creates and configures a BasicDataSource instance based on the given properties.

Usage

From source file:DAO.MYSQL.SingletonPoolConnectionMYSQL.java

private void crearPool() throws MyException {
    try {//from   w  ww .j  ava  2s.  c  o m
        Properties propiedades = new Properties();
        propiedades.load(new FileInputStream("C:/datasource_config_MYSQL.properties"));
        bds = BasicDataSourceFactory.createDataSource(propiedades);
    } catch (Exception e) {
        throw new MyException("Error al crear conexion de MYSQL.", e);
    }
}

From source file:DAO.SQLServer.SingletonPoolConnectionSQLServer.java

private void crearPool() throws MyException {
    try {//  www .j  a  va2 s .co m
        Properties propiedades = new Properties();
        propiedades.load(new FileInputStream("C:/datasource_config_SQLServer.properties"));
        bds = BasicDataSourceFactory.createDataSource(propiedades);
    } catch (Exception e) {
        throw new MyException("Error al crear conexion de SQLServer.", e);
    }
}

From source file:jp.co.golorp.emarf.sql.DataSources.java

/**
 * ?/*from   w  w  w. j  a  v  a2s.  c o m*/
 *
 * @return DataSource
 */
public static DataSource get() {

    if (ds != null) {
        return ds;
    }

    /*
     * JNDI??
     */

    String name = BUNDLE.getString(DATA_SOURCE_NAME);
    try {
        Context context = new InitialContext();
        ds = (DataSource) context.lookup(name);
        return ds;
    } catch (NamingException e) {
        LOG.warn(e.getMessage());
    }

    /*
     * DBCP??
     */

    Properties properties = new Properties();
    Enumeration<String> keys = BUNDLE.getKeys();
    while (keys.hasMoreElements()) {
        String key = keys.nextElement();
        String value = BUNDLE.getString(key);
        properties.put(key, value);
        // if (value.contains("mysql")) {
        // DataSources.isMySQL = true;
        // } else if (value.contains("oracle")) {
        // DataSources.isOracle = true;
        // }
    }

    try {
        ds = BasicDataSourceFactory.createDataSource(properties);
        return ds;
    } catch (Exception e) {
        throw new SystemError(e);
    }
}

From source file:kenh.xscript.database.elements.Datasource.java

public void process(@Attribute(ATTRIBUTE_VARIABLE) String var) throws UnsupportedScriptException {
    var = StringUtils.trimToEmpty(var);

    if (StringUtils.isBlank(var)) {
        UnsupportedScriptException ex = new UnsupportedScriptException(this, "Variable name is empty.");
        throw ex;
    }/*from   w  w  w  .j  ava2 s .co m*/

    Properties properties = new Properties();

    this.invokeChildren();
    Vector<Element> children = this.getChildren();

    for (Element child : children) {
        if (child instanceof Param) {
            Param c = (Param) child;
            String name = c.getName();
            Object value = Param.getParsedValue(c);
            if (c.isLink()) {
                String linkName = c.getLinkName();
                if (!properties.containsKey(linkName))
                    new UnsupportedScriptException(this,
                            "Could not find the parameter to link. [" + name + ", " + linkName + "]");
                value = properties.get(linkName);
            }

            properties.put(name, value);
        }
    }

    try {
        DataSource datasource = BasicDataSourceFactory.createDataSource(properties);
        this.saveVariable(var, datasource, null);

    } catch (Exception e) {
        throw new UnsupportedScriptException(this, e);
    }
}

From source file:com.ebizarts.jspwiki.providers.jdbcprovider.DBCPConnectionProvider.java

public void initialize(WikiEngine engine, final Properties config) throws NoRequiredPropertyException {
    log.debug("Initializing DBCPConnectionProvider");

    Properties connectionProperties = parseAdditionalProperties(config, DRIVER_PROP_PREFIX);

    Properties dbcpProps = parseAdditionalProperties(config, PREFIX);
    dbcpProps.put("driverClassName", TextUtil.getRequiredProperty(config, PREFIX + ".driverClassName"));
    dbcpProps.put("url", TextUtil.getRequiredProperty(config, PREFIX + ".url"));
    dbcpProps.put("username", TextUtil.getRequiredProperty(config, PREFIX + ".username"));
    dbcpProps.put("password", TextUtil.getRequiredProperty(config, PREFIX + ".password"));
    dbcpProps.put("connectionProperties", stringifyProps(connectionProperties, ";"));
    log.debug("driver: " + dbcpProps.getProperty("user") + ", url: " + dbcpProps.getProperty("url")
            + ", username: " + dbcpProps.getProperty("user"));

    try {/*from ww  w  .  ja  v  a  2s  .  com*/
        ds = BasicDataSourceFactory.createDataSource(dbcpProps);
    } catch (Exception e) {
        throw new NoRequiredPropertyException(e.getMessage(), null);
    }

}

From source file:com.amalto.core.storage.DBCPConnectionProvider.java

@Override
public void configure(Map props) {
    try {//from   w ww .  ja v  a 2 s .c o m
        if (log.isDebugEnabled()) {
            log.debug("Configure DBCPConnectionProvider");
        }
        // DBCP properties used to create the BasicDataSource
        Properties dbcpProperties = new Properties();
        // DriverClass & url
        String jdbcDriverClass = (String) props.get(Environment.DRIVER);
        String jdbcUrl = (String) props.get(Environment.URL);
        dbcpProperties.put("driverClassName", jdbcDriverClass);
        dbcpProperties.put("url", jdbcUrl);
        // Username / password
        String username = (String) props.get(Environment.USER);
        String password = (String) props.get(Environment.PASS);
        dbcpProperties.put("username", username);
        dbcpProperties.put("password", password);
        // Isolation level
        String isolationLevel = (String) props.get(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            dbcpProperties.put("defaultTransactionIsolation", isolationLevel);
        }
        // Turn off autocommit
        dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE));
        // Pool size
        String poolSize = (String) props.get(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0) && (Integer.parseInt(poolSize) > 0)) {
            dbcpProperties.put("maxActive", poolSize);
        }
        // Copy all DBCP properties removing the prefix
        for (Object o : props.entrySet()) {
            Map.Entry entry = (Map.Entry) o;
            String key = (String) entry.getKey();
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = (String) entry.getValue();
                dbcpProperties.put(property, value);
            }
        }
        // Some debug info
        if (log.isDebugEnabled()) {
            StringWriter sw = new StringWriter();
            dbcpProperties.list(new PrintWriter(sw, true));
            log.debug(sw.toString());
        }
        // Let the factory create the pool
        ds = BasicDataSourceFactory.createDataSource(dbcpProperties);
        // The BasicDataSource has lazy initialization borrowing a connection will start the DataSource and make
        // sure it is configured correctly.
        Connection conn = ds.getConnection();
        conn.close();
        // Log pool statistics before continuing.
        logStatistics();
    } catch (Exception e) {
        String message = "Could not create a DBCP pool";
        log.error(message, e);
        if (ds != null) {
            try {
                ds.close();
            } catch (Exception e2) {
                log.debug("Unable to close DBCP after failed initialization.", e);
            }
            ds = null;
        }
        throw new HibernateException(message, e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Configure DBCPConnectionProvider complete");
    }
}

From source file:de.innovationgate.webgate.api.jdbc.pool.DBCPConnectionProvider.java

public void configure(Map propsMap) throws HibernateException {
    try {/*from w ww  . j  a v a 2  s .  c o  m*/
        log.debug("Configure DBCPConnectionProvider");
        Properties props = new Properties();
        props.putAll(propsMap);

        String jdbcUrl = (String) props.getProperty(Environment.URL);

        // DBCP properties used to create the BasicDataSource
        Properties dbcpProperties = new Properties();

        // DriverClass & url
        String jdbcDriverClass = props.getProperty(Environment.DRIVER);

        // Try to determine driver by jdbc-URL
        if (jdbcDriverClass == null) {
            Driver driver = DriverManager.getDriver(jdbcUrl);
            if (driver != null) {
                jdbcDriverClass = driver.getClass().getName();
            } else {
                throw new HibernateException("Driver class not available");
            }
        }

        dbcpProperties.put("driverClassName", jdbcDriverClass);
        dbcpProperties.put("url", jdbcUrl);

        // Username / password
        String username = props.getProperty(Environment.USER);
        if (username != null) {
            dbcpProperties.put("username", username);
        }

        String password = props.getProperty(Environment.PASS);
        if (password != null) {
            dbcpProperties.put("password", password);
        }

        // Isolation level
        String isolationLevel = props.getProperty(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            dbcpProperties.put("defaultTransactionIsolation", isolationLevel);
        }

        // Turn off autocommit (unless autocommit property is set) 
        String autocommit = props.getProperty(AUTOCOMMIT);
        if ((autocommit != null) && (autocommit.trim().length() > 0)) {
            dbcpProperties.put("defaultAutoCommit", autocommit);
        } else {
            dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE));
        }

        // Pool size
        String poolSize = props.getProperty(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0) && (Integer.parseInt(poolSize) > 0)) {
            dbcpProperties.put("maxActive", poolSize);
        }

        // Copy all "driver" properties into "connectionProperties"
        Properties driverProps = ConnectionProviderInitiator.getConnectionProperties(props);
        if (driverProps.size() > 0) {
            StringBuffer connectionProperties = new StringBuffer();
            for (Iterator iter = driverProps.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = driverProps.getProperty(key);
                connectionProperties.append(key).append('=').append(value);
                if (iter.hasNext()) {
                    connectionProperties.append(';');
                }
            }
            dbcpProperties.put("connectionProperties", connectionProperties.toString());
        }

        // Copy all DBCP properties removing the prefix
        for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
            String key = String.valueOf(iter.next());
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = props.getProperty(key);
                dbcpProperties.put(property, value);
            }
        }

        // Backward-compatibility
        if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
            dbcpProperties.put("poolPreparedStatements", String.valueOf(Boolean.TRUE));
            dbcpProperties.put("maxOpenPreparedStatements", props.getProperty(DBCP_PS_MAXACTIVE));
        }
        if (props.getProperty(DBCP_MAXACTIVE) != null) {
            dbcpProperties.put("maxTotal", props.getProperty(DBCP_MAXACTIVE));
        }
        if (props.getProperty(DBCP_MAXWAIT) != null) {
            dbcpProperties.put("maxWaitMillis", props.getProperty(DBCP_MAXWAIT));
        }

        // Some debug info
        if (log.isDebugEnabled()) {
            log.debug("Creating a DBCP BasicDataSource with the following DBCP factory properties:");
            StringWriter sw = new StringWriter();
            dbcpProperties.list(new PrintWriter(sw, true));
            log.debug(sw.toString());
        }

        String dbKey = (String) props.get("hibernate.dbcp.dbkey");
        String databaseServerId = (String) props.get("hibernate.dbcp.dbserver.id");

        // Enable DBCP2 JMX monitoring information
        if (dbKey != null) {
            dbcpProperties.put("jmxName",
                    JMX_DBCP2_DBPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(dbKey));
        } else if (databaseServerId != null) {
            String entityTitle = props.getProperty("hibernate.dbcp.dbserver.title");
            dbcpProperties.put("jmxName",
                    JMX_DBCP2_SERVERPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(entityTitle));
        }

        // Let the factory create the pool
        _ds = BasicDataSourceFactory.createDataSource(dbcpProperties);
        _ds.setLogExpiredConnections(false);

        // The BasicDataSource has lazy initialization
        // borrowing a connection will start the DataSource
        // and make sure it is configured correctly.
        Connection conn = _ds.getConnection();
        conn.close();

        // Create Legacy JMX monitoring information, provided by WGA
        if ("true".equals(props.getProperty("hibernate.dbcp.legacyJMX"))) {
            try {
                if (dbKey != null) {
                    _entityKey = dbKey;
                    _entityTitle = dbKey;
                    _jmxManager = new JmxManager(new DBCPPoolInformation(this),
                            new ObjectName(JMX_DBPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(dbKey)));
                } else if (databaseServerId != null) {
                    _server = true;
                    _entityKey = databaseServerId;
                    _entityTitle = (String) props.get("hibernate.dbcp.dbserver.title");
                    _jmxManager = new JmxManager(new DBCPPoolInformation(this), new ObjectName(
                            JMX_SERVERPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(_entityTitle)));
                }
            } catch (Throwable e) {
                log.error("Error enabling JMX metrics for connection pool", e);
            }
        }

    } catch (Exception e) {
        String message = "Could not create a DBCP pool";
        if (_ds != null) {
            try {
                _ds.close();
            } catch (Exception e2) {
                // ignore
            }
            _ds = null;
        }
        throw new HibernateException(message, e);
    }
    log.debug("Configure DBCPConnectionProvider complete");

}

From source file:org.apache.cayenne.configuration.server.DBCPDataSourceFactory.java

@Override
public DataSource getDataSource(DataNodeDescriptor nodeDescriptor) throws Exception {

    String location = nodeDescriptor.getParameters();
    if (location == null) {
        logger.debug("No explicit DBCP2 config location, will use default location: " + DBCP2_PROPERTIES);
        location = DBCP2_PROPERTIES;/* w  ww  .  j  a  v  a 2s .  c o m*/
    }

    Resource baseConfiguration = nodeDescriptor.getConfigurationSource();
    if (baseConfiguration == null) {
        throw new CayenneRuntimeException("Null 'configurationSource' for nodeDescriptor '%s'",
                nodeDescriptor.getName());
    }

    Resource dbcp2Configuration = baseConfiguration.getRelativeResource(location);
    if (dbcp2Configuration == null) {
        throw new CayenneRuntimeException("Missing DBCP2 configuration '%s' for nodeDescriptor '%s'", location,
                nodeDescriptor.getName());
    }

    Properties properties = getProperties(dbcp2Configuration);
    if (logger.isDebugEnabled()) {
        logger.debug("DBCP2 Properties: " + properties);
    }

    return BasicDataSourceFactory.createDataSource(properties);
}

From source file:org.ofbiz.core.entity.transaction.DBCPConnectionFactory.java

private static BasicDataSource createDataSource(JdbcDatasourceInfo jdbcDatasource) throws Exception {
    final Properties dbcpProperties = loadDbcpProperties();

    final BasicDataSource dataSource = BasicDataSourceFactory.createDataSource(dbcpProperties);
    dataSource.setDriverClassLoader(Thread.currentThread().getContextClassLoader());
    dataSource.setDriverClassName(jdbcDatasource.getDriverClassName());
    dataSource.setUrl(jdbcDatasource.getUri());
    dataSource.setUsername(jdbcDatasource.getUsername());
    dataSource.setPassword(jdbcDatasource.getPassword());

    if (isNotEmpty(jdbcDatasource.getIsolationLevel())) {
        dataSource.setDefaultTransactionIsolation(
                TransactionIsolations.fromString(jdbcDatasource.getIsolationLevel()));
    }/*from  w w w  . j ava2s  . com*/

    if (dbcpProperties.containsKey(PROP_JMX) && Boolean.valueOf(dbcpProperties.getProperty(PROP_JMX))) {
        dataSource.setJmxName(
                ObjectName.getInstance(dbcpProperties.getProperty(PROP_MBEANNAME)).getCanonicalName());
    }

    return dataSource;
}

From source file:org.rifidi.edge.api.resources.DBResourceDescription.java

/**
 * Creates a DataSource object from the given properties
 * //ww  w. j  a  v a  2s . co m
 * @return
 * @throws CannotCreateResourceException
 */
DataSource getDataSource() throws CannotCreateResourceException {

    try {
        return BasicDataSourceFactory.createDataSource(properties);
    } catch (Exception e) {
        throw new CannotCreateResourceException(e);
    }
}