Example usage for org.apache.commons.dbcp.managed BasicManagedDataSource setTransactionManager

List of usage examples for org.apache.commons.dbcp.managed BasicManagedDataSource setTransactionManager

Introduction

In this page you can find the example usage for org.apache.commons.dbcp.managed BasicManagedDataSource setTransactionManager.

Prototype

public void setTransactionManager(TransactionManager transactionManager) 

Source Link

Document

Sets the required transaction manager property.

Usage

From source file:datasource.TransactionalDataSourceProvider.java

@Override
BasicManagedDataSource getDataSource() {
    BasicManagedDataSource ds = new BasicManagedDataSource();
    ds.setTransactionManager(transactionManager);
    return ds;/*from  w  ww .  j  a  va  2 s  .  co m*/
}

From source file:com.eurodyn.qlack2.util.datasource.generic.Configurator.java

public void refresh() {
    try {// www .j a v  a2  s .c o m
        Object registeredDs;

        // Configure the database driver.
        Object dbDriver = Class.forName(getDriverClass()).newInstance();
        // To configure the driver in a generic way, we use the
        // driverParametersMapping.
        String[] params = getDriverParametersMapping().split(",");
        for (String param : params) {
            param = param.trim();
            String paramKey = param.trim().split("-")[0];
            String paramValue = param.trim().split("-")[1];
            String property = BeanUtils.getProperty(this, paramValue);
            BeanUtils.setProperty(dbDriver, paramKey, property);
        }

        if (datasourceType.equals("javax.sql.XADataSource")) {
            BasicManagedDataSource managedDs = new BasicManagedDataSource();
            managedDs.setTransactionManager(transactionManager);
            managedDs.setXaDataSourceInstance((XADataSource) dbDriver);
            managedDs.setInitialSize(initialSize);
            managedDs.setMaxActive(maxActive);
            managedDs.setMaxIdle(maxIdle);
            managedDs.setMinIdle(minIdle);
            managedDs.setMaxWait(maxWait);
            managedDs.setValidationQuery(validationQuery);
            managedDs.setTestOnBorrow(testOnBorrow);
            managedDs.setRemoveAbandoned(removeAbandoned);
            managedDs.setRemoveAbandonedTimeout(removeAbandonedTimeout);
            registeredDs = managedDs;
        } else {
            registeredDs = dbDriver;
        }

        // If the service is already registered it should be unregistered first.
        for (ServiceRegistration<?> registration : serviceRegistrations) {
            registration.unregister();
        }

        // Expose datasources using the driver configured above.
        // This bundle accepts multiple jndi names as a comma-separated list so we
        // expose as many services as the provided jndi names.
        String[] jndiNames = jndiName.split(",");
        for (String name : jndiNames) {
            Dictionary<String, String> registrationProperties = new Hashtable<String, String>();
            registrationProperties.put("osgi.jndi.service.name", name);
            ServiceRegistration<?> registration = context.registerService(DataSource.class.getName(),
                    registeredDs, registrationProperties);
            serviceRegistrations.add(registration);
            LOGGER.log(Level.CONFIG, "Registered Datasource for {0} under {1}.",
                    new String[] { getDriverClass(), name });
        }
    } catch (ClassNotFoundException e) {
        LOGGER.log(Level.SEVERE, MessageFormat.format("Could not find database driver {0}.", getDriverClass()),
                e);
    } catch (InvocationTargetException | InstantiationException | IllegalAccessException
            | NoSuchMethodException e) {
        LOGGER.log(Level.SEVERE,
                MessageFormat.format("Could not instantiate database driver {0}.", getDriverClass()), e);
    }
}

From source file:org.apache.ignite.cache.hibernate.HibernateL2CacheTransactionalSelfTest.java

/** {@inheritDoc} */
@Nullable//w w w . j  av  a  2s  .c o m
@Override
protected StandardServiceRegistryBuilder registryBuilder() {
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

    DatasourceConnectionProviderImpl connProvider = new DatasourceConnectionProviderImpl();

    BasicManagedDataSource dataSrc = new BasicManagedDataSource(); // JTA-aware data source.

    dataSrc.setTransactionManager(jotm.getTransactionManager());

    dataSrc.setDefaultAutoCommit(false);

    JdbcDataSource h2DataSrc = new JdbcDataSource();

    h2DataSrc.setURL(CONNECTION_URL);

    dataSrc.setXaDataSourceInstance(h2DataSrc);

    connProvider.setDataSource(dataSrc);

    connProvider.configure(Collections.emptyMap());

    builder.addService(ConnectionProvider.class, connProvider);

    builder.addService(JtaPlatform.class, new TestJtaPlatform());

    builder.applySetting(Environment.TRANSACTION_COORDINATOR_STRATEGY,
            JtaTransactionCoordinatorBuilderImpl.class.getName());

    return builder;
}

From source file:org.gridgain.grid.cache.hibernate.GridHibernateL2CacheTransactionalSelfTest.java

/** {@inheritDoc} */
@Nullable/*ww w .j a va2s.co  m*/
@Override
protected ServiceRegistryBuilder registryBuilder() {
    ServiceRegistryBuilder builder = new ServiceRegistryBuilder();

    DatasourceConnectionProviderImpl connProvider = new DatasourceConnectionProviderImpl();

    BasicManagedDataSource dataSrc = new BasicManagedDataSource(); // JTA-aware data source.

    dataSrc.setTransactionManager(jotm.getTransactionManager());

    dataSrc.setDefaultAutoCommit(false);

    JdbcDataSource h2DataSrc = new JdbcDataSource();

    h2DataSrc.setURL(CONNECTION_URL);

    dataSrc.setXaDataSourceInstance(h2DataSrc);

    connProvider.setDataSource(dataSrc);

    connProvider.configure(Collections.emptyMap());

    builder.addService(ConnectionProvider.class, connProvider);

    builder.addService(JtaPlatform.class, new TestJtaPlatform());

    builder.addService(TransactionFactory.class, new JtaTransactionFactory());

    return builder;
}

From source file:org.nuxeo.runtime.datasource.DataSourceFactory.java

@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> env) throws Exception {
    Reference ref = (Reference) obj;
    if (!DataSource.class.getName().equals(ref.getClassName())) {
        return null;
    }/*from w w w . j  av a 2s  .  c  om*/

    TransactionManager transactionManager;
    try {
        transactionManager = TransactionHelper.lookupTransactionManager();
    } catch (NamingException e) {
        transactionManager = null;
    }

    boolean xa = ref.get(BasicManagedDataSourceFactory.PROP_XADATASOURCE) != null;
    log.info(String.format("Creating pooled %s datasource: %s/%s", xa ? "XA" : "non-XA",
            nameCtx.getNameInNamespace(), name));

    if (xa && transactionManager == null) {
        throw new RuntimeException(
                "Cannot configure XA datasource " + name + " without an available transaction manager");
    }

    // extract properties from Reference
    Map<String, String> properties = new HashMap<String, String>();
    Enumeration<RefAddr> refAddrs = ref.getAll();
    while (refAddrs.hasMoreElements()) {
        RefAddr ra = refAddrs.nextElement();
        String key = ra.getType();
        String value = ra.getContent().toString();
        if (key.startsWith(DataSourceDescriptor.PROP_PREFIX)) {
            key = key.substring(DataSourceDescriptor.PROP_PREFIX.length());
            properties.put(key, value);
        }
    }

    DataSource ds;
    if (!xa) {
        // fetch url from properties
        for (Entry<String, String> en : properties.entrySet()) {
            // often misspelled, thus the ignore case
            if (URL_LOWER.equalsIgnoreCase(en.getKey())) {
                ref.add(new StringRefAddr(URL_LOWER, en.getValue()));
            }
        }
        ObjectFactory factory = new BasicDataSourceFactory();
        ds = (DataSource) factory.getObjectInstance(ref, name, nameCtx, env);
        BasicDataSource bds = (BasicDataSource) ds;

        // set properties
        for (Entry<String, String> en : properties.entrySet()) {
            String key = en.getKey();
            if (URL_LOWER.equalsIgnoreCase(key)) {
                continue;
            }
            bds.addConnectionProperty(key, en.getValue());
        }
    } else {
        ObjectFactory factory = new BasicManagedDataSourceFactory();
        ds = (DataSource) factory.getObjectInstance(obj, name, nameCtx, env);
        if (ds == null) {
            return null;
        }
        BasicManagedDataSource bmds = (BasicManagedDataSource) ds;

        // set transaction manager
        bmds.setTransactionManager(transactionManager);

        // set properties
        XADataSource xaDataSource = bmds.getXaDataSourceInstance();
        if (xaDataSource == null) {
            return null;
        }
        for (Entry<String, String> en : properties.entrySet()) {
            String key = en.getKey();
            // proper JavaBean convention for initial cap
            if (Character.isLowerCase(key.charAt(1))) {
                key = Character.toLowerCase(key.charAt(0)) + key.substring(1);
            }
            String value = en.getValue();
            boolean ok = false;
            try {
                BeanUtils.setProperty(xaDataSource, key, value);
                ok = true;
            } catch (Exception e) {
                if (URL_LOWER.equals(key)) {
                    // commonly misspelled
                    try {
                        BeanUtils.setProperty(xaDataSource, URL_UPPER, value);
                        ok = true;
                    } catch (Exception ee) {
                        // log error below
                    }
                }
            }
            if (!ok) {
                log.error(String.format("Cannot set %s = %s on %s", key, value,
                        xaDataSource.getClass().getName()));
            }
        }
    }
    return ds;
}

From source file:org.obiba.opal.core.runtime.jdbc.DataSourceFactoryBean.java

@Override
public DataSource getObject() {
    log.debug("Configure DataSource for {}", url);
    BasicManagedDataSource dataSource = new BasicManagedDataSource();
    dataSource.setTransactionManager(jtaTransactionManager);
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(url);//ww  w  .j a v  a2 s. c om
    setConnectionProperties(dataSource);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setInitialSize(MIN_POOL_SIZE);
    dataSource.setMaxActive(MAX_POOL_SIZE);
    dataSource.setMaxIdle(MAX_IDLE);
    dataSource.setTestOnBorrow(true);
    dataSource.setTestWhileIdle(false);
    dataSource.setTestOnReturn(false);
    dataSource.setDefaultAutoCommit(false);
    dataSource.setValidationQuery(guessValidationQuery());
    return dataSource;
}