Java Examples for javax.sql.XADataSource

The following java examples will help you to understand the usage of javax.sql.XADataSource. These source code samples are taken from different open source projects.

Example 1
Project: cloudtm-data-platform-master  File: JBossTADataSourceBuilder.java View source code
public DataSource createDataSource() throws SQLException {
    TxControl.setDefaultTimeout(timeout);
    DataSourceProvider.initialize(xaDataSource);
    DataSourceProvider dsProvider = new DataSourceProvider();
    final XADataSource dataSource = dsProvider.getDataSource(dsProvider.getDataSourceName());
    XADataSourceWrapper dsw = new XADataSourceWrapper(dsProvider.getDataSourceName(), dataSource);
    dsw.setProperty(TransactionalDriver.dynamicClass, DataSourceProvider.class.getName());
    dsw.setProperty(TransactionalDriver.userName, user);
    dsw.setProperty(TransactionalDriver.password, password);
    return dsw;
}
Example 2
Project: spring-boot-master  File: DataSourceAutoConfiguration.java View source code
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    ConditionMessage.Builder message = ConditionMessage.forCondition("DataSourceAvailable");
    if (hasBean(context, DataSource.class) || hasBean(context, XADataSource.class)) {
        return ConditionOutcome.match(message.foundExactly("existing data source bean"));
    }
    if (anyMatches(context, metadata, this.pooledCondition, this.embeddedCondition)) {
        return ConditionOutcome.match(message.foundExactly("existing auto-configured data source bean"));
    }
    return ConditionOutcome.noMatch(message.didNotFind("any existing data source bean").atAll());
}
Example 3
Project: glassfish-master  File: DataSourceDefinitionDeployer.java View source code
public String getResType() {
    String type = ConnectorConstants.JAVAX_SQL_DATASOURCE;
    try {
        Class clz = Thread.currentThread().getContextClassLoader().loadClass(desc.getClassName());
        if (javax.sql.XADataSource.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVAX_SQL_XA_DATASOURCE;
        } else if (javax.sql.ConnectionPoolDataSource.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVAX_SQL_CONNECTION_POOL_DATASOURCE;
        } else if (javax.sql.DataSource.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVAX_SQL_DATASOURCE;
        } else if (java.sql.Driver.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVA_SQL_DRIVER;
        }
    } catch (ClassNotFoundException e) {
        if (_logger.isLoggable(Level.FINEST)) {
            _logger.log(Level.FINEST, "Unable to load class [ " + desc.getClassName() + " ] to " + "determine its res-type, defaulting to [" + ConnectorConstants.JAVAX_SQL_DATASOURCE + "]");
        }
    }
    return type;
}
Example 4
Project: AIM-master  File: JDBCScope.java View source code
@Override
protected void init() {
    // java.sql entities
    addMethod("java.sql.Statement", "execute(java.lang.String)");
    addMethod("java.sql.Statement", "execute(java.lang.String,int)");
    addMethod("java.sql.Statement", "execute(java.lang.String,int[])");
    addMethod("java.sql.Statement", "execute(java.lang.String,java.lang.String[])");
    addMethod("java.sql.Statement", "executeBatch()");
    addMethod("java.sql.Statement", "executeQuery(java.lang.String)");
    addMethod("java.sql.Statement", "executeUpdate(java.lang.String)");
    addMethod("java.sql.Statement", "executeUpdate(java.lang.String,int)");
    addMethod("java.sql.Statement", "executeUpdate(java.lang.String,int[])");
    addMethod("java.sql.Statement", "executeUpdate(java.lang.String,java.lang.String[])");
    addMethod("java.sql.Statement", "getResultSet()");
    addMethod("java.sql.Statement", "getGeneratedKeys()");
    addMethod("java.sql.PreparedStatement", "execute()");
    addMethod("java.sql.PreparedStatement", "executeQuery()");
    addMethod("java.sql.PreparedStatement", "executeUpdate()");
    addMethod("java.sql.Driver", "connect()");
    addMethod("java.sql.DriverManager", "getConnection(java.lang.String)");
    addMethod("java.sql.DriverManager", "getConnection(java.lang.String,java.util.Properties)");
    addMethod("java.sql.DriverManager", "getConnection(java.lang.String,java.lang.String,java.lang.String)");
    addMethod("java.sql.DriverManager", "getDriver(java.lang.String)");
    addMethod("java.sql.DriverManager", "getDrivers()");
    addMethod("java.sql.Connection", "commit()");
    addMethod("java.sql.Connection", "close()");
    addMethod("java.sql.Connection", "prepareStatement(java.lang.String)");
    addMethod("java.sql.Connection", "prepareStatement(java.lang.String,int)");
    addMethod("java.sql.Connection", "prepareStatement(java.lang.String,int[])");
    addMethod("java.sql.Connection", "prepareStatement(java.lang.String,int,int)");
    addMethod("java.sql.Connection", "prepareStatement(java.lang.String,int,int,int)");
    addMethod("java.sql.Connection", "prepareStatement(java.lang.String,java.lang.String[])");
    // javax.sql entities
    addMethod("javax.sql.ConnectionPoolDataSource", "getPooledConnection()");
    addMethod("javax.sql.ConnectionPoolDataSource", "getPooledConnection(java.lang.String,java.lang.String)");
    addMethod("javax.sql.DataSource", "getConnection()");
    addMethod("javax.sql.DataSource", "getConnection(java.lang.String,java.lang.String)");
    addMethod("javax.sql.PooledConnection", "getConnection()");
    addMethod("javax.sql.PooledConnection", "close()");
    addMethod("javax.sql.XADataSource", "getXAConnection()");
    addMethod("javax.sql.XADataSource", "getXAConnection(java.lang.String,java.lang.String)");
}
Example 5
Project: brainslug-master  File: TestDataSourceConfiguration.java View source code
private XADataSource createMySQLDatasource() {
    System.out.println("URL: " + getJdbcUrl());
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
    mysqlXADataSource.setURL(getJdbcUrl() + "?pinGlobalTxToPhysicalConnection=true");
    mysqlXADataSource.setUser(getDbUser());
    mysqlXADataSource.setPassword(getDbPassword());
    return mysqlXADataSource;
}
Example 6
Project: bundles-master  File: JDBCManagedTest.java View source code
/**
	 * Check if we can create a H2 DataSource through the JDBC bundle.
	 * 
	 * @throws InterruptedException
	 * @throws IOException
	 * @throws SQLException
	 */
public void testH2() throws InterruptedException, IOException, SQLException {
    // Make sure no DataSource service yet exists
    assertNull(xtds.getService());
    //
    // Create a configuration that will create a H2 DataSource
    //
    Hashtable<String, String> props = new Hashtable<String, String>();
    props.put("url", H2_URL);
    props.put("dataSourceFactory.target", "(" + DataSourceFactory.OSGI_JDBC_DRIVER_CLASS + "=org.h2.Driver)");
    Configuration c = cm.createFactoryConfiguration(XA_DATA_SOURCE_FACTORY, null);
    c.update(props);
    try {
        XADataSource service = xtds.waitForService(20000);
        assertEquals(1, xtds.size());
        assertNotNull(service);
        Connection connection = service.getXAConnection().getConnection();
        assertNotNull(connection);
        DatabaseMetaData metaData = connection.getMetaData();
        assertNotNull(metaData);
        assertEquals(metaData.getURL(), H2_URL);
        assertEquals(metaData.getDatabaseProductName(), "H2");
        Statement statement = connection.createStatement();
        statement.execute("create table blub;");
        connection.close();
    } finally {
        c.delete();
    }
    checkGone();
}
Example 7
Project: hibernate-search-master  File: JBossTADataSourceBuilder.java View source code
public DataSource createDataSource() throws SQLException {
    TxControl.setDefaultTimeout(timeout);
    DataSourceProvider.initialize(xaDataSource);
    DataSourceProvider dsProvider = new DataSourceProvider();
    final XADataSource dataSource = dsProvider.getDataSource(dsProvider.getDataSourceName());
    XADataSourceWrapper dsw = new XADataSourceWrapper(dsProvider.getDataSourceName(), dataSource);
    dsw.setProperty(TransactionalDriver.dynamicClass, DataSourceProvider.class.getName());
    dsw.setProperty(TransactionalDriver.userName, user);
    dsw.setProperty(TransactionalDriver.password, password);
    return dsw;
}
Example 8
Project: org.ops4j.pax.jdbc-master  File: DataSourceRegistrationTest.java View source code
@SuppressWarnings("resource")
@Test
public void testPublishedXADS() throws ConfigurationException, InvalidSyntaxException, SQLException {
    IMocksControl c = EasyMock.createControl();
    BundleContext context = c.createMock(BundleContext.class);
    final DataSourceFactory dsf = c.createMock(DataSourceFactory.class);
    // Expect that a ConnectionPoolDataSource is created using the DataSourceFactory
    XADataSource xads = c.createMock(XADataSource.class);
    expect(dsf.createXADataSource(anyObject(Properties.class))).andReturn(xads);
    // Expect DataSource is registered as a service
    ServiceRegistration dsSreg = c.createMock(ServiceRegistration.class);
    expect(context.registerService(eq(XADataSource.class.getName()), eq(xads), anyObject(Dictionary.class))).andReturn(dsSreg);
    // create and publish the datasource
    c.replay();
    Dictionary<String, String> properties = new Hashtable<String, String>();
    properties.put(DataSourceRegistration.JNDI_SERVICE_NAME, "test");
    properties.put(DataSourceRegistration.DATASOURCE_TYPE, XADataSource.class.getSimpleName());
    new DataSourceRegistration(context, dsf, properties, properties, null);
    c.verify();
}
Example 9
Project: osgi.enroute-master  File: JDBCManagedTest.java View source code
/**
	 * Check if we can create a H2 DataSource through the JDBC bundle.
	 * 
	 * @throws InterruptedException
	 * @throws IOException
	 * @throws SQLException
	 */
public void testH2() throws InterruptedException, IOException, SQLException {
    // Make sure no DataSource service yet exists
    assertNull(xtds.getService());
    //
    // Create a configuration that will create a H2 DataSource
    //
    Hashtable<String, String> props = new Hashtable<String, String>();
    props.put("url", H2_URL);
    props.put("dataSourceFactory.target", "(" + DataSourceFactory.OSGI_JDBC_DRIVER_CLASS + "=org.h2.Driver)");
    Configuration c = cm.createFactoryConfiguration(XA_DATA_SOURCE_FACTORY, null);
    c.update(props);
    try {
        XADataSource service = xtds.waitForService(20000);
        assertEquals(1, xtds.size());
        assertNotNull(service);
        Connection connection = service.getXAConnection().getConnection();
        assertNotNull(connection);
        DatabaseMetaData metaData = connection.getMetaData();
        assertNotNull(metaData);
        assertEquals(metaData.getURL(), H2_URL);
        assertEquals(metaData.getDatabaseProductName(), "H2");
        Statement statement = connection.createStatement();
        statement.execute("create table blub;");
        connection.close();
    } finally {
        c.delete();
    }
    checkGone();
}
Example 10
Project: transactions-essentials-master  File: AtomikosDataSourceBean.java View source code
protected com.atomikos.datasource.pool.ConnectionFactory doInit() throws Exception {
    if (xaDataSource == null) {
        if (xaDataSourceClassName == null)
            throwAtomikosSQLException("Property 'xaDataSourceClassName' cannot be null");
        if (xaProperties == null)
            throwAtomikosSQLException("Property 'xaProperties' cannot be null");
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.logInfo(this + ": initializing with [" + " xaDataSourceClassName=" + xaDataSourceClassName + "," + " uniqueResourceName=" + getUniqueResourceName() + "," + " maxPoolSize=" + getMaxPoolSize() + "," + " minPoolSize=" + getMinPoolSize() + "," + " borrowConnectionTimeout=" + getBorrowConnectionTimeout() + "," + " maxIdleTime=" + getMaxIdleTime() + "," + " reapTimeout=" + getReapTimeout() + "," + " maintenanceInterval=" + getMaintenanceInterval() + "," + " testQuery=" + getTestQuery() + "," + " xaProperties=" + printXaProperties() + "," + " loginTimeout=" + getLoginTimeout() + "," + " maxLifetime=" + getMaxLifetime() + "]");
    if (xaDataSource == null) {
        try {
            Class<XADataSource> xadsClass = ClassLoadingHelper.loadClass(getXaDataSourceClassName());
            xaDataSource = xadsClass.newInstance();
        } catch (ClassNotFoundException nf) {
            AtomikosSQLException.throwAtomikosSQLException("The class '" + getXaDataSourceClassName() + "' specified by property 'xaDataSourceClassName' could not be found in the classpath. Please make sure the spelling is correct, and that the required jar(s) are in the classpath.", nf);
        } catch (ClassCastException cce) {
            AtomikosSQLException.throwAtomikosSQLException("The class '" + getXaDataSourceClassName() + "' specified by property 'xaDataSourceClassName' does not implement the required interface javax.jdbc.XADataSource. Please make sure the spelling is correct, and check your JDBC driver vendor's documentation.");
        }
        xaDataSource.setLoginTimeout(getLoginTimeout());
        xaDataSource.setLogWriter(getLogWriter());
        PropertyUtils.setProperties(xaDataSource, xaProperties);
    }
    JdbcTransactionalResource tr = new JdbcTransactionalResource(getUniqueResourceName(), xaDataSource);
    com.atomikos.datasource.pool.ConnectionFactory cf = new com.atomikos.jdbc.AtomikosXAConnectionFactory(xaDataSource, tr, this);
    Configuration.addResource(tr);
    EventPublisher.publish(new XAResourceDetectedEvent(xaDataSourceClassName, xaProperties, XAResourceDetectedEvent.ResourceType.JDBC));
    return cf;
}
Example 11
Project: arquillian-container-glassfish-master  File: AsAdminCommandTestCase.java View source code
@Test
public void shouldBeAbleToIssueAsAdminCommand() throws Exception {
    Assert.assertNotNull("Verify that the asadmin CommandRunner resource is available", commandRunner);
    CommandResult result = commandRunner.run("create-jdbc-connection-pool", "--datasourceclassname=org.apache.derby.jdbc.EmbeddedXADataSource", "--restype=javax.sql.XADataSource", "--property=portNumber=1527:password=APP:user=APP" + ":serverName=localhost:databaseName=my_database" + ":connectionAttributes=create\\=true", "my_derby_pool");
    Assert.assertEquals("Verify 'create-jdbc-connection-pool' asadmin command", ExitStatus.SUCCESS, result.getExitStatus());
    result = commandRunner.run("create-jdbc-resource", "--connectionpoolid", "my_derby_pool", "jdbc/my_database");
    Assert.assertEquals("Verify 'create-jdbc-resource' asadmin command", ExitStatus.SUCCESS, result.getExitStatus());
    result = commandRunner.run("ping-connection-pool", "my_derby_pool");
    Assert.assertEquals("Verify asadmin command 'ping-connection-pool'", ExitStatus.SUCCESS, result.getExitStatus());
    Context ctx = new InitialContext();
    DataSource myDatabase = (DataSource) ctx.lookup("jdbc/my_database");
    Assert.assertNotNull(myDatabase);
}
Example 12
Project: glassfish-main-master  File: DataSourceDefinitionDeployer.java View source code
public String getResType() {
    String type = ConnectorConstants.JAVAX_SQL_DATASOURCE;
    try {
        Class clz = Thread.currentThread().getContextClassLoader().loadClass(desc.getClassName());
        if (javax.sql.XADataSource.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVAX_SQL_XA_DATASOURCE;
        } else if (javax.sql.ConnectionPoolDataSource.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVAX_SQL_CONNECTION_POOL_DATASOURCE;
        } else if (javax.sql.DataSource.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVAX_SQL_DATASOURCE;
        } else if (java.sql.Driver.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVA_SQL_DRIVER;
        }
    } catch (ClassNotFoundException e) {
        if (_logger.isLoggable(Level.FINEST)) {
            _logger.log(Level.FINEST, "Unable to load class [ " + desc.getClassName() + " ] to " + "determine its res-type, defaulting to [" + ConnectorConstants.JAVAX_SQL_DATASOURCE + "]");
        }
    }
    return type;
}
Example 13
Project: ha-jdbc-master  File: XAResourceInvocationHandler.java View source code
/**
	 * @see net.sf.hajdbc.sql.AbstractInvocationHandler#getInvocationStrategy(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
	 */
@Override
protected InvocationStrategy getInvocationStrategy(XAResource resource, Method method, Object... parameters) throws XAException {
    if (driverReadMethodSet.contains(method)) {
        return InvocationStrategies.INVOKE_ON_ANY;
    }
    if (databaseWriteMethodSet.contains(method)) {
        return InvocationStrategies.INVOKE_ON_ALL;
    }
    boolean start = method.equals(startMethod);
    boolean end = endTransactionMethodSet.contains(method);
    if (start || end || intraTransactionMethodSet.contains(method)) {
        final InvocationStrategy strategy = end ? InvocationStrategies.END_TRANSACTION_INVOKE_ON_ALL : InvocationStrategies.TRANSACTION_INVOKE_ON_ALL;
        Xid xid = (Xid) parameters[0];
        DatabaseCluster<XADataSource, XADataSourceDatabase> cluster = this.getProxyFactory().getDatabaseCluster();
        if (start) {
            final Lock lock = cluster.getLockManager().readLock(null);
            // Lock may already exist if we're resuming a suspended transaction
            if (lockMap.putIfAbsent(xid, lock) == null) {
                return new InvocationStrategy() {

                    @Override
                    public <Z, D extends Database<Z>, T, R, E extends Exception> SortedMap<D, R> invoke(ProxyFactory<Z, D, T, E> proxy, Invoker<Z, D, T, R, E> invoker) throws E {
                        lock.lock();
                        try {
                            return strategy.invoke(proxy, invoker);
                        } catch (Exception e) {
                            lock.unlock();
                            throw proxy.getExceptionFactory().createException(e);
                        }
                    }
                };
            }
        }
        Durability.Phase phase = phaseRegistry.get(method);
        if (phase != null) {
            final InvocationStrategy durabilityStrategy = cluster.getDurability().getInvocationStrategy(strategy, phase, xid);
            if (endTransactionMethodSet.contains(method)) {
                final Lock lock = lockMap.remove(xid);
                return new InvocationStrategy() {

                    @Override
                    public <Z, D extends Database<Z>, T, R, E extends Exception> SortedMap<D, R> invoke(ProxyFactory<Z, D, T, E> proxy, Invoker<Z, D, T, R, E> invoker) throws E {
                        try {
                            return durabilityStrategy.invoke(proxy, invoker);
                        } finally {
                            if (lock != null) {
                                lock.unlock();
                            }
                        }
                    }
                };
            }
            return durabilityStrategy;
        }
        return strategy;
    }
    return super.getInvocationStrategy(resource, method, parameters);
}
Example 14
Project: karaf-master  File: JdbcServiceImpl.java View source code
private ServiceReference<?> lookupDataSource(String name) {
    ServiceReference<?>[] references;
    try {
        references = bundleContext.getServiceReferences((String) null, "(&(|(" + Constants.OBJECTCLASS + "=" + DataSource.class.getName() + ")" + "(" + Constants.OBJECTCLASS + "=" + XADataSource.class.getName() + "))" + "(|(osgi.jndi.service.name=" + name + ")(datasource=" + name + ")(name=" + name + ")(service.id=" + name + ")))");
    } catch (InvalidSyntaxException e) {
        throw new IllegalArgumentException("Error finding datasource with name " + name, e);
    }
    if (references == null || references.length == 0) {
        throw new IllegalArgumentException("No JDBC datasource found for " + name);
    }
    if (references.length > 1) {
        Arrays.sort(references);
        if (getRank(references[references.length - 1]) == getRank(references[references.length - 2])) {
            LOGGER.warn("Multiple JDBC datasources found with the same service ranking for " + name);
        }
    }
    return references[references.length - 1];
}
Example 15
Project: Payara-master  File: DataSourceDefinitionDeployer.java View source code
@Override
public String getResType() {
    String type = ConnectorConstants.JAVAX_SQL_DATASOURCE;
    try {
        Class clz = Thread.currentThread().getContextClassLoader().loadClass(desc.getClassName());
        if (javax.sql.XADataSource.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVAX_SQL_XA_DATASOURCE;
        } else if (javax.sql.ConnectionPoolDataSource.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVAX_SQL_CONNECTION_POOL_DATASOURCE;
        } else if (javax.sql.DataSource.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVAX_SQL_DATASOURCE;
        } else if (java.sql.Driver.class.isAssignableFrom(clz)) {
            type = ConnectorConstants.JAVA_SQL_DRIVER;
        }
    } catch (ClassNotFoundException e) {
        if (_logger.isLoggable(Level.FINEST)) {
            _logger.log(Level.FINEST, "Unable to load class [ " + desc.getClassName() + " ] to " + "determine its res-type, defaulting to [" + ConnectorConstants.JAVAX_SQL_DATASOURCE + "]");
        }
    }
    return type;
}
Example 16
Project: SmallMind-master  File: PooledDataSourceFactory.java View source code
public static <D extends CommonDataSource> AbstractPooledDataSource createPooledDataSource(String poolName, DataSourceFactory<D, ? extends PooledConnection> dataSourceFactory, String validationQuery, int maxStatements, ComplexPoolConfig poolConfig, DatabaseConnection[] connections) throws SQLException, ComponentPoolException {
    if (XADataSource.class.isAssignableFrom(dataSourceFactory.getDataSourceClass())) {
        return new XAPooledDataSource((ComponentPool<XAConnection>) PooledConnectionComponentPoolFactory.<D>constructComponentPool(poolName, dataSourceFactory, validationQuery, maxStatements, poolConfig, connections));
    }
    return new PooledDataSource((ComponentPool<PooledConnection>) PooledConnectionComponentPoolFactory.<D>constructComponentPool(poolName, dataSourceFactory, validationQuery, maxStatements, poolConfig, connections));
}
Example 17
Project: tomee-master  File: DataSourceFactory.java View source code
public static CommonDataSource create(final String name, final boolean configuredManaged, final Class impl, final String definition, final Duration maxWaitTime, final Duration timeBetweenEvictionRuns, final Duration minEvictableIdleTime, final boolean useAlternativeDriver) throws IllegalAccessException, InstantiationException, IOException {
    final Properties properties = asProperties(definition);
    final Set<String> originalKeys = properties.stringPropertyNames();
    final String handler = SystemInstance.get().getOptions().get(GLOBAL_HANDLER_PROPERTY, (String) properties.remove(HANDLER_PROPERTY));
    boolean flushable = SystemInstance.get().getOptions().get(GLOBAL_FLUSH_PROPERTY, "true".equalsIgnoreCase((String) properties.remove(FLUSHABLE_PROPERTY)));
    final String forceDifferent = SystemInstance.get().getOptions().get(XA_GLOBAL_FORCE_DIFFERENT, String.class.cast(properties.remove(XA_FORCE_DIFFERENT)));
    convert(properties, maxWaitTime, "maxWaitTime", "maxWait");
    convert(properties, timeBetweenEvictionRuns, "timeBetweenEvictionRuns", "timeBetweenEvictionRunsMillis");
    convert(properties, minEvictableIdleTime, "minEvictableIdleTime", "minEvictableIdleTimeMillis");
    // these can be added and are managed by OpenEJB and not the DataSource itself
    properties.remove("Definition");
    properties.remove("JtaManaged");
    properties.remove("ServiceId");
    boolean managed = configuredManaged;
    if (properties.containsKey("transactional")) {
        managed = Boolean.parseBoolean((String) properties.remove("transactional")) || managed;
    }
    normalizeJdbcUrl(properties);
    final String jdbcUrl = properties.getProperty("JdbcUrl");
    final AlternativeDriver driver;
    if (Driver.class.isAssignableFrom(impl) && jdbcUrl != null && useAlternativeDriver) {
        try {
            driver = new AlternativeDriver((Driver) impl.newInstance(), jdbcUrl);
            driver.register();
        } catch (final SQLException e) {
            throw new IllegalStateException(e);
        }
    } else {
        driver = null;
    }
    final boolean logSql = SystemInstance.get().getOptions().get(GLOBAL_LOG_SQL_PROPERTY, "true".equalsIgnoreCase((String) properties.remove(LOG_SQL_PROPERTY)));
    final String logPackages = SystemInstance.get().getProperty(GLOBAL_LOG_SQL_PACKAGE_PROPERTY, (String) properties.remove(LOG_SQL_PACKAGE_PROPERTY));
    final DataSourceCreator creator = creator(properties.remove(DATA_SOURCE_CREATOR_PROP), logSql);
    final String resetOnError = (String) properties.remove(RESET_PROPERTY);
    // before setProperties()
    final String resetMethods = (String) properties.remove(RESET_METHODS_PROPERTY);
    boolean useContainerLoader = "true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.resources.use-container-loader", "true")) && impl.getClassLoader() == DataSourceFactory.class.getClassLoader();
    final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    if (useContainerLoader) {
        final ClassLoader containerLoader = DataSourceFactory.class.getClassLoader();
        Thread.currentThread().setContextClassLoader(containerLoader);
        try {
            useContainerLoader = basicChecksThatDataSourceCanBeCreatedFromContainerLoader(properties, containerLoader);
        } finally {
            Thread.currentThread().setContextClassLoader(oldLoader);
        }
        if (useContainerLoader) {
            Thread.currentThread().setContextClassLoader(containerLoader);
        } else {
            LOGGER.info("Can't use container loader to create datasource " + name + " so using application one");
        }
    }
    try {
        CommonDataSource ds;
        if (createDataSourceFromClass(impl)) {
            // opposed to "by driver"
            trimNotSupportedDataSourceProperties(properties);
            final ObjectRecipe recipe = new ObjectRecipe(impl);
            recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
            recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
            recipe.allow(Option.NAMED_PARAMETERS);
            recipe.allow(Option.PRIVATE_PROPERTIES);
            recipe.setAllProperties(properties);
            if (!properties.containsKey("url") && properties.containsKey("JdbcUrl")) {
                // depend on the datasource class so add all well known keys
                recipe.setProperty("url", properties.getProperty("JdbcUrl"));
            }
            CommonDataSource dataSource = (CommonDataSource) recipe.create();
            final boolean isDs = DataSource.class.isInstance(dataSource);
            if (!isDs && XADataSource.class.isInstance(dataSource) && forceDifferent != null) {
                try {
                    dataSource = CommonDataSource.class.cast(Thread.currentThread().getContextClassLoader().loadClass("true".equals(forceDifferent) ? "org.apache.openejb.resource.jdbc.xa.IsDifferentXaDataSourceWrapper" : forceDifferent).getConstructor(XADataSource.class).newInstance(dataSource));
                } catch (InvocationTargetExceptionClassNotFoundException | NoSuchMethodException |  e) {
                    throw new IllegalArgumentException(e);
                }
            }
            if (managed) {
                if (isDs && usePool(properties)) {
                    ds = creator.poolManaged(name, DataSource.class.cast(dataSource), properties);
                } else {
                    ds = creator.managed(name, dataSource);
                }
            } else {
                if (isDs && usePool(properties)) {
                    ds = creator.pool(name, DataSource.class.cast(dataSource), properties);
                } else {
                    ds = dataSource;
                }
            }
        } else {
            // by driver
            if (managed) {
                final XAResourceWrapper xaResourceWrapper = SystemInstance.get().getComponent(XAResourceWrapper.class);
                if (xaResourceWrapper != null) {
                    ds = creator.poolManagedWithRecovery(name, xaResourceWrapper, impl.getName(), properties);
                } else {
                    ds = creator.poolManaged(name, impl.getName(), properties);
                }
            } else {
                ds = creator.pool(name, impl.getName(), properties);
            }
        }
        // ds and creator are associated here, not after the proxying of the next if if active
        setCreatedWith(creator, ds);
        if (driver != null) {
            driverByDataSource.put(ds, driver);
        }
        final boolean doResetOnError = resetOnError != null && !"false".equals(resetOnError);
        if (doResetOnError || logSql || flushable) {
            // will get proxied
            ObjectRecipe objectRecipe = null;
            ResettableDataSourceHandler existingResettableHandler = null;
            FlushableDataSourceHandler flushableDataSourceHandler = null;
            if (ExecutionContext.isContextSet()) {
                final ExecutionContext context = ExecutionContext.getContext();
                final List<Recipe> stack = context.getStack();
                if (stack.size() > 0) {
                    objectRecipe = ObjectRecipe.class.cast(stack.get(0));
                    existingResettableHandler = ResettableDataSourceHandler.class.cast(objectRecipe.getProperty("resettableHandler"));
                    flushableDataSourceHandler = FlushableDataSourceHandler.class.cast(objectRecipe.getProperty("flushableHandler"));
                    final Map<String, Object> props = objectRecipe.getProperties();
                    for (final String key : originalKeys) {
                        props.remove(key);
                    }
                    // meta properties, not needed here so gain few cycles removing them
                    props.remove("properties");
                    props.remove("Definition");
                    props.remove("ServiceId");
                    props.remove("resettableHandler");
                    props.remove("flushableHandler");
                    //we create a proxy so we cant get txmgr etc in another manner or we cant extend (= break) this method
                    new ObjectRecipe(ds.getClass()) {

                        {
                            allow(Option.CASE_INSENSITIVE_PROPERTIES);
                            allow(Option.IGNORE_MISSING_PROPERTIES);
                            allow(Option.NAMED_PARAMETERS);
                            allow(Option.PRIVATE_PROPERTIES);
                            setAllProperties(props);
                        }
                    }.setProperties(ds);
                }
            }
            ds = wrapIfNeeded(handler, ds);
            if (logSql) {
                ds = makeItLogging(ds, logPackages);
            }
            final ResettableDataSourceHandler resettableDataSourceHandler;
            if (doResetOnError) {
                // needs to be done after flushable
                // ensure we reuse the same handle instance otherwise we loose state
                resettableDataSourceHandler = existingResettableHandler != null ? existingResettableHandler : new ResettableDataSourceHandler(ds, resetOnError, resetMethods);
            } else {
                resettableDataSourceHandler = null;
            }
            if (flushable || doResetOnError) {
                if (flushableDataSourceHandler == null) {
                    final FlushableDataSourceHandler.FlushConfig flushConfig;
                    // don't let it wrap the delegate again
                    properties.remove("flushable");
                    final Map<String, Object> recipeProps = new HashMap<>(objectRecipe == null ? new HashMap<String, Object>() : objectRecipe.getProperties());
                    recipeProps.remove("properties");
                    recipeProps.put("OpenEJBResourceClasspath", String.valueOf(useAlternativeDriver));
                    flushConfig = new FlushableDataSourceHandler.FlushConfig(recipeProps);
                    flushableDataSourceHandler = new FlushableDataSourceHandler(ds, flushConfig, resettableDataSourceHandler);
                } else {
                    flushableDataSourceHandler.updateDataSource(ds);
                }
                ds = makeSerializableFlushableDataSourceProxy(ds, flushableDataSourceHandler);
            }
            if (doResetOnError) {
                // needs to be done after flushable
                // ensure we reuse the same handle instance otherwise we loose state
                resettableDataSourceHandler.updateDelegate(ds);
                ds = makeSerializableFlushableDataSourceProxy(ds, resettableDataSourceHandler);
            }
        } else {
            ds = wrapIfNeeded(handler, ds);
        }
        return ds;
    } finally {
        if (useContainerLoader) {
            Thread.currentThread().setContextClassLoader(oldLoader);
        }
    }
}
Example 18
Project: aries-master  File: TxDBServlet.java View source code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    pw = response.getWriter();
    pw.write(LOGO_HEADER);
    // Get the bundle context from ServletContext attributes
    BundleContext ctx = (BundleContext) getServletContext().getAttribute(OSGI_BUNDLECONTEXT_ATTRIBUTE);
    pw.println("<html>");
    pw.println("<head>");
    pw.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"tableTemplate.css\"/>");
    pw.println("<body>");
    pw.println("<h2 align=center><p><font face=\"Tahoma\">Sample Application for JDBC usage in JTA Transactions.</font></h2>");
    pw.println("<p><p>");
    ServiceReference tmServiceRef = ctx.getServiceReference("javax.transaction.TransactionManager");
    ServiceReference derbyServiceRef = ctx.getServiceReference(DataSourceFactory.class.getName());
    if (tmServiceRef == null || derbyServiceRef == null) {
        pw.println("<font face=\"Tahoma\">TransactionManager or Derby driver are not available in the OSGI registry.</font><br>");
    } else {
        TransactionManager tm = (TransactionManager) ctx.getService(tmServiceRef);
        DataSourceFactory derbyRegistry = (DataSourceFactory) ctx.getService(derbyServiceRef);
        try {
            // Set the needed properties for the database connection
            Properties props = new Properties();
            props.put(DataSourceFactory.JDBC_URL, "jdbc:derby:txDemo");
            props.put(DataSourceFactory.JDBC_DATABASE_NAME, "txDemo");
            props.put(DataSourceFactory.JDBC_USER, "");
            props.put(DataSourceFactory.JDBC_PASSWORD, "");
            XADataSource xaDataSource = derbyRegistry.createXADataSource(props);
            pw.println("<center><form><table><tr><td align='right'>Value: </td><td align=left><input type='text' name='value' value='' size='12'/><input type='submit' name='action' value='InsertAndCommit' size='100'/></td></tr>");
            pw.println("<tr><td align='right'>Value: </td><td align=left><input type='text' name='value' value='' size='12'/><input type='submit' name='action' value='InsertAndRollback' size='100'/></center></td></tr>");
            pw.println("<tr colspan='2' align='center'><td> </td><td><input type='submit' name='action' value='cleanTable' size='100' /> <input type='submit' name='action' value='printTable' size='100'/></td><tr></table></form></center>");
            String value = request.getParameter("value");
            String action = request.getParameter("action");
            if (action != null && action.equals("InsertAndCommit")) {
                insertIntoTransaction(xaDataSource, tm, value, true);
            } else if (action != null && action.equals("InsertAndRollback")) {
                insertIntoTransaction(xaDataSource, tm, value, false);
            } else if (action != null && action.equals("cleanTable")) {
                cleanTable(xaDataSource);
            }
            printTable(xaDataSource);
        } catch (Exception e) {
            pw.println("<font face=\"Tahoma\">Unexpected exception occurred " + e.toString() + ".</font><br>");
            e.printStackTrace(pw);
        }
    }
    pw.println("</body>");
    pw.println("</html>");
    pw.flush();
}
Example 19
Project: edt-master  File: SQLJNDIDataSource.java View source code
@Override
public Connection getConnection() throws SQLException {
    if (conn == null) {
        String jndiName = connectionUrl;
        // Initial attempt is for an indirect lookup.
        if (!jndiName.startsWith("java:comp/env/")) {
            jndiName = "java:comp/env/" + jndiName;
        }
        CommonDataSource ds;
        try {
            ds = (CommonDataSource) Runtime.getRunUnit().jndiLookup(jndiName);
        } catch (Exception ex) {
            try {
                ds = (CommonDataSource) Runtime.getRunUnit().jndiLookup(connectionUrl);
            } catch (Exception ex2) {
                SQLException sqlEx = new SQLException();
                throw sqlEx.fillInMessage(Message.JNDI_LOOKUP_ERROR, jndiName, ex);
            }
        }
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        try {
            if ((user == null || user.length() == 0) && (password == null || password.length() == 0)) {
                if (ds instanceof DataSource) {
                    conn = ((DataSource) ds).getConnection();
                } else if (ds instanceof ConnectionPoolDataSource) {
                    conn = ((ConnectionPoolDataSource) ds).getPooledConnection().getConnection();
                } else if (ds instanceof XADataSource) {
                    conn = ((XADataSource) ds).getXAConnection().getConnection();
                } else {
                    SQLException sqlEx = new SQLException();
                    throw sqlEx.fillInMessage(Message.JNDI_UNKNOWN_TYPE, ds == null ? "null" : ds.getClass().getCanonicalName());
                }
            } else {
                if (ds instanceof DataSource) {
                    conn = ((DataSource) ds).getConnection(user, password);
                } else if (ds instanceof ConnectionPoolDataSource) {
                    conn = ((ConnectionPoolDataSource) ds).getPooledConnection(user, password).getConnection();
                } else if (ds instanceof XADataSource) {
                    conn = ((XADataSource) ds).getXAConnection(user, password).getConnection();
                } else {
                    SQLException sqlEx = new SQLException();
                    throw sqlEx.fillInMessage(Message.JNDI_UNKNOWN_TYPE, ds == null ? "null" : ds.getClass().getCanonicalName());
                }
            }
        } catch (java.sql.SQLException e) {
            throw SQLUtilities.makeEglException(e);
        }
    }
    return conn;
}
Example 20
Project: hsweb-framework-master  File: DynamicXaDataSourceImpl.java View source code
public XADataSource getActiveXADataSource() {
    DataSource activeDs = getActiveDataSource();
    XADataSource xaDataSource;
    if (activeDs instanceof XADataSource)
        xaDataSource = ((XADataSource) activeDs);
    else if (activeDs instanceof AtomikosDataSourceBean) {
        xaDataSource = ((AtomikosDataSourceBean) activeDs).getXaDataSource();
    } else {
        throw new UnsupportedOperationException(activeDs.getClass() + " is not XADataSource");
    }
    return xaDataSource;
}
Example 21
Project: metamorphosis-example-master  File: XATransactionProducer.java View source code
private static XADataSource getXADataSource() throws SQLException {
    final MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
    mysqlXADataSource.setUrl("jdbc:mysql://10.232.36.83:3306/metamorphosis?characterEncoding=utf8&connectTimeout=1000&autoReconnect=true");
    mysqlXADataSource.setUser("notify");
    mysqlXADataSource.setPassword("notify");
    mysqlXADataSource.setPreparedStatementCacheSize(20);
    return mysqlXADataSource;
}
Example 22
Project: Metamorphosis-master  File: XATransactionProducer.java View source code
private static XADataSource getXADataSource() throws SQLException {
    final MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
    mysqlXADataSource.setUrl("jdbc:mysql://localhost:3306/test?characterEncoding=utf8&connectTimeout=1000&autoReconnect=true");
    mysqlXADataSource.setUser("root");
    mysqlXADataSource.setPassword("");
    mysqlXADataSource.setPreparedStatementCacheSize(20);
    return mysqlXADataSource;
}
Example 23
Project: narayana-master  File: PerformanceTestCommitMarkableResource.java View source code
// @org.junit.Ignore
@Test
public void testXAResource() throws Exception {
    System.out.println("testXAResource: " + new Date());
    XADataSource dataSource = null;
    if (dbType.equals("oracle")) {
        Class clazz = Class.forName("oracle.jdbc.xa.client.OracleXADataSource");
        dataSource = (XADataSource) clazz.newInstance();
        clazz.getMethod("setDriverType", new Class[] { String.class }).invoke(dataSource, new Object[] { "thin" });
        clazz.getMethod("setServerName", new Class[] { String.class }).invoke(dataSource, new Object[] { "tywin.eng.hst.ams2.redhat.com" });
        clazz.getMethod("setNetworkProtocol", new Class[] { String.class }).invoke(dataSource, new Object[] { "tcp" });
        clazz.getMethod("setDatabaseName", new Class[] { String.class }).invoke(dataSource, new Object[] { "orcl" });
        clazz.getMethod("setUser", new Class[] { String.class }).invoke(dataSource, new Object[] { "dtf11" });
        clazz.getMethod("setPassword", new Class[] { String.class }).invoke(dataSource, new Object[] { "dtf11" });
        clazz.getMethod("setPortNumber", new Class[] { int.class }).invoke(dataSource, new Object[] { 1521 });
    } else if (dbType.equals("sybase")) {
        Class clazz = Class.forName("com.sybase.jdbc3.jdbc.SybXADataSource");
        dataSource = (XADataSource) clazz.newInstance();
        clazz.getMethod("setServerName", new Class[] { String.class }).invoke(dataSource, new Object[] { "192.168.1.5" });
        clazz.getMethod("setDatabaseName", new Class[] { String.class }).invoke(dataSource, new Object[] { "LOCALHOST" });
        clazz.getMethod("setUser", new Class[] { String.class }).invoke(dataSource, new Object[] { "sa" });
        clazz.getMethod("setPassword", new Class[] { String.class }).invoke(dataSource, new Object[] { "sybase" });
        clazz.getMethod("setPortNumber", new Class[] { int.class }).invoke(dataSource, new Object[] { 5000 });
    } else if (dbType.equals("h2")) {
        dataSource = new org.h2.jdbcx.JdbcDataSource();
        ((JdbcDataSource) dataSource).setURL("jdbc:h2:mem:JBTMDB2;MVCC=TRUE;DB_CLOSE_DELAY=-1");
    } else if (dbType.equals("postgres")) {
        dataSource = new PGXADataSource();
        ((PGXADataSource) dataSource).setPortNumber(5432);
        ((PGXADataSource) dataSource).setUser("dtf11");
        ((PGXADataSource) dataSource).setPassword("dtf11");
        ((PGXADataSource) dataSource).setServerName("tywin.eng.hst.ams2.redhat.com");
        ((PGXADataSource) dataSource).setDatabaseName("jbossts");
    } else if (dbType.equals("mysql")) {
        dataSource = new MysqlXADataSource();
        ((MysqlXADataSource) dataSource).setServerName("tywin.eng.hst.ams2.redhat.com");
        ((MysqlXADataSource) dataSource).setPortNumber(3306);
        ((MysqlXADataSource) dataSource).setDatabaseName("jbossts");
        ((MysqlXADataSource) dataSource).setUser("dtf11");
        ((MysqlXADataSource) dataSource).setPassword("dtf11");
    } else if (dbType.equals("db2")) {
        Class clazz = Class.forName("com.ibm.db2.jcc.DB2XADataSource");
        dataSource = (XADataSource) clazz.newInstance();
        clazz.getMethod("setServerName", new Class[] { String.class }).invoke(dataSource, new Object[] { "tywin.eng.hst.ams2.redhat.com" });
        clazz.getMethod("setDatabaseName", new Class[] { String.class }).invoke(dataSource, new Object[] { "BTDB1" });
        clazz.getMethod("setUser", new Class[] { String.class }).invoke(dataSource, new Object[] { "db2" });
        clazz.getMethod("setPassword", new Class[] { String.class }).invoke(dataSource, new Object[] { "db2" });
        clazz.getMethod("setDriverType", new Class[] { int.class }).invoke(dataSource, new Object[] { 4 });
        clazz.getMethod("setPortNumber", new Class[] { int.class }).invoke(dataSource, new Object[] { 50001 });
    } else if (dbType.equals("sqlserver")) {
        Class clazz = Class.forName("com.microsoft.sqlserver.jdbc.SQLServerXADataSource");
        dataSource = (XADataSource) clazz.newInstance();
        clazz.getMethod("setServerName", new Class[] { String.class }).invoke(dataSource, new Object[] { "dev30.mw.lab.eng.bos.redhat.com" });
        clazz.getMethod("setDatabaseName", new Class[] { String.class }).invoke(dataSource, new Object[] { "crashrec" });
        clazz.getMethod("setUser", new Class[] { String.class }).invoke(dataSource, new Object[] { "crashrec" });
        clazz.getMethod("setPassword", new Class[] { String.class }).invoke(dataSource, new Object[] { "crashrec" });
        clazz.getMethod("setSendStringParametersAsUnicode", new Class[] { Boolean.class }).invoke(dataSource, new Object[] { false });
        clazz.getMethod("setPortNumber", new Class[] { int.class }).invoke(dataSource, new Object[] { 3918 });
    }
    Utils.createTables(dataSource);
    doTest(new Handler(dataSource), "_testXAResource_" + dbType);
}
Example 24
Project: openjpa-master  File: DistributedDataSource.java View source code
Connection getConnection(DataSource ds, String user, String pwd) throws SQLException {
    if (ds instanceof DecoratingDataSource)
        return getConnection(((DecoratingDataSource) ds).getInnermostDelegate(), user, pwd);
    if (ds instanceof XADataSource)
        return ((XADataSource) ds).getXAConnection(user, pwd).getConnection();
    return ds.getConnection(user, pwd);
}
Example 25
Project: pgjdbc-master  File: PGDataSourceFactoryTest.java View source code
@Test
public void testCreateXADataSourceConfigured() throws Exception {
    Properties properties = new Properties();
    properties.put(DataSourceFactory.JDBC_DATABASE_NAME, "db");
    XADataSource dataSource = _dataSourceFactory.createXADataSource(properties);
    Assert.assertNotNull(dataSource);
    Assert.assertTrue(dataSource instanceof PGXADataSource);
    PGXADataSource xaDataSource = (PGXADataSource) dataSource;
    Assert.assertEquals("db", xaDataSource.getDatabaseName());
}
Example 26
Project: quartz-1.8.3-optivo-master  File: JNDIConnectionProvider.java View source code
public Connection getConnection() throws SQLException {
    Context ctx = null;
    try {
        Object ds = this.datasource;
        if (ds == null || isAlwaysLookup()) {
            ctx = (props != null) ? new InitialContext(props) : new InitialContext();
            ds = ctx.lookup(url);
            if (!isAlwaysLookup()) {
                this.datasource = ds;
            }
        }
        if (ds == null) {
            throw new SQLException("There is no object at the JNDI URL '" + url + "'");
        }
        if (ds instanceof XADataSource) {
            return (((XADataSource) ds).getXAConnection().getConnection());
        } else if (ds instanceof DataSource) {
            return ((DataSource) ds).getConnection();
        } else {
            throw new SQLException("Object at JNDI URL '" + url + "' is not a DataSource.");
        }
    } catch (Exception e) {
        this.datasource = null;
        throw new SQLException("Could not retrieve datasource via JNDI url '" + url + "' " + e.getClass().getName() + ": " + e.getMessage());
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception ignore) {
            }
        }
    }
}
Example 27
Project: wisdom-jdbc-master  File: AbstractDataSourceFactoryTest.java View source code
@Test
public void testXADataSourceCreation() throws SQLException {
    MyDataSourceFactory factory = new MyDataSourceFactory();
    Properties props = new Properties();
    props.put(DataSourceFactory.JDBC_DATABASE_NAME, "database");
    props.put(DataSourceFactory.JDBC_USER, "john");
    props.put(DataSourceFactory.JDBC_PASSWORD, "secret");
    XADataSource source = factory.createXADataSource(props);
    assertThat(source).isNotNull();
}
Example 28
Project: moonshine-master  File: Atomikos.java View source code
@Override
public DataSource wrap(String name, XADataSource xaDataSource, PoolOptions poolOptions, String testQuery) {
    AtomikosDataSourceBean wrapped = new AtomikosDataSourceBean();
    wrapped.setXaDataSource(xaDataSource);
    wrapped.setUniqueResourceName(name);
    if (poolOptions == null) {
        poolOptions = new PoolOptions();
    }
    if (poolOptions.getMaxLifeTime() != null && poolOptions.getMaxLifeTime() != 0) {
        wrapped.setMaxLifetime(poolOptions.getMaxLifeTime());
    } else {
        // test query is only needed when we don't know how long Atomikos can keep connections in the pool
        wrapped.setTestQuery(testQuery);
    }
    if (poolOptions.getMinPoolSize() != null) {
        wrapped.setMinPoolSize(poolOptions.getMinPoolSize());
    }
    if (poolOptions.getMaxPoolSize() != null) {
        wrapped.setMaxPoolSize(poolOptions.getMaxPoolSize());
    }
    if (poolOptions.getMaxIdleTime() != null) {
        wrapped.setMaxIdleTime(poolOptions.getMaxIdleTime());
    }
    if (poolOptions.getReapTimeout() != null) {
        wrapped.setReapTimeout(poolOptions.getReapTimeout());
    }
    return wrapped;
}
Example 29
Project: nuxeo-tycho-osgi-master  File: BasicManagedDataSourceFactory.java View source code
/**
     * Creates and configures a {@link BasicManagedDataSource} instance based on
     * the given properties.
     *
     * @param properties the datasource configuration properties
     * @throws Exception if an error occurs creating the data source
     */
public static DataSource createDataSource(Properties properties) throws Exception {
    BasicManagedDataSource dataSource = new BasicManagedDataSource();
    String value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
    if (value != null) {
        dataSource.setDefaultAutoCommit(Boolean.valueOf(value).booleanValue());
    }
    value = properties.getProperty(PROP_DEFAULTREADONLY);
    if (value != null) {
        dataSource.setDefaultReadOnly(Boolean.valueOf(value).booleanValue());
    }
    value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
    if (value != null) {
        int level = UNKNOWN_TRANSACTIONISOLATION;
        if ("NONE".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_NONE;
        } else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_READ_COMMITTED;
        } else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_READ_UNCOMMITTED;
        } else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_REPEATABLE_READ;
        } else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
            level = Connection.TRANSACTION_SERIALIZABLE;
        } else {
            try {
                level = Integer.parseInt(value);
            } catch (NumberFormatException e) {
                System.err.println("Could not parse defaultTransactionIsolation: " + value);
                System.err.println("WARNING: defaultTransactionIsolation not set");
                System.err.println("using default value of database driver");
                level = UNKNOWN_TRANSACTIONISOLATION;
            }
        }
        dataSource.setDefaultTransactionIsolation(level);
    }
    value = properties.getProperty(PROP_DEFAULTCATALOG);
    if (value != null) {
        dataSource.setDefaultCatalog(value);
    }
    value = properties.getProperty(PROP_DRIVERCLASSNAME);
    if (value != null) {
        dataSource.setDriverClassName(value);
    }
    value = properties.getProperty(PROP_MAXACTIVE);
    if (value != null) {
        dataSource.setMaxActive(Integer.parseInt(value));
    }
    value = properties.getProperty(PROP_MAXIDLE);
    if (value != null) {
        dataSource.setMaxIdle(Integer.parseInt(value));
    }
    value = properties.getProperty(PROP_MINIDLE);
    if (value != null) {
        dataSource.setMinIdle(Integer.parseInt(value));
    }
    value = properties.getProperty(PROP_INITIALSIZE);
    if (value != null) {
        dataSource.setInitialSize(Integer.parseInt(value));
    }
    value = properties.getProperty(PROP_MAXWAIT);
    if (value != null) {
        dataSource.setMaxWait(Long.parseLong(value));
    }
    value = properties.getProperty(PROP_TESTONBORROW);
    if (value != null) {
        dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
    }
    value = properties.getProperty(PROP_TESTONRETURN);
    if (value != null) {
        dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
    }
    value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
    if (value != null) {
        dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
    }
    value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
    if (value != null) {
        dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
    }
    value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
    if (value != null) {
        dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
    }
    value = properties.getProperty(PROP_TESTWHILEIDLE);
    if (value != null) {
        dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
    }
    value = properties.getProperty(PROP_PASSWORD);
    if (value != null) {
        dataSource.setPassword(value);
    }
    value = properties.getProperty(PROP_URL);
    if (value != null) {
        dataSource.setUrl(value);
    }
    value = properties.getProperty(PROP_USERNAME);
    if (value != null) {
        dataSource.setUsername(value);
    }
    value = properties.getProperty(PROP_VALIDATIONQUERY);
    if (value != null) {
        dataSource.setValidationQuery(value);
    }
    value = properties.getProperty(PROP_VALIDATIONQUERY_TIMEOUT);
    if (value != null) {
        dataSource.setValidationQueryTimeout(Integer.parseInt(value));
    }
    value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
    if (value != null) {
        dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
    }
    value = properties.getProperty(PROP_REMOVEABANDONED);
    if (value != null) {
        dataSource.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
    }
    value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT);
    if (value != null) {
        dataSource.setRemoveAbandonedTimeout(Integer.parseInt(value));
    }
    value = properties.getProperty(PROP_LOGABANDONED);
    if (value != null) {
        dataSource.setLogAbandoned(Boolean.valueOf(value).booleanValue());
    }
    value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
    if (value != null) {
        dataSource.setPoolPreparedStatements(Boolean.valueOf(value).booleanValue());
    }
    value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
    if (value != null) {
        dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value));
    }
    value = properties.getProperty(PROP_INITCONNECTIONSQLS);
    if (value != null) {
        StringTokenizer tokenizer = new StringTokenizer(value, ";");
        dataSource.setConnectionInitSqls(Collections.list(tokenizer));
    }
    value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
    if (value != null) {
        Properties p = getProperties(value);
        Enumeration<?> e = p.propertyNames();
        while (e.hasMoreElements()) {
            String propertyName = (String) e.nextElement();
            dataSource.addConnectionProperty(propertyName, p.getProperty(propertyName));
        }
    }
    // Managed: initialize XADataSource
    value = properties.getProperty(PROP_XADATASOURCE);
    if (value != null) {
        Class<?> xaDataSourceClass;
        try {
            xaDataSourceClass = Class.forName(value);
        } catch (Throwable t) {
            throw (SQLException) new SQLException("Cannot load XA data source class '" + value + "'").initCause(t);
        }
        XADataSource xaDataSource;
        try {
            xaDataSource = (XADataSource) xaDataSourceClass.newInstance();
        } catch (Throwable t) {
            throw (SQLException) new SQLException("Cannot create XA data source of class '" + value + "'").initCause(t);
        }
        dataSource.setXaDataSourceInstance(xaDataSource);
    }
    // Trick to make sure that initialSize connections are created
    if (dataSource.getInitialSize() > 0) {
        dataSource.getLogWriter();
    }
    // Return the configured DataSource instance
    return dataSource;
}
Example 30
Project: org.eclipse.ecr-master  File: JDBCBackend.java View source code
@Override
public void initialize(RepositoryImpl repository) throws StorageException {
    this.repository = repository;
    RepositoryDescriptor repositoryDescriptor = repository.getRepositoryDescriptor();
    // instantiate the datasource
    String className = repositoryDescriptor.xaDataSourceName;
    Class<?> klass;
    try {
        klass = Class.forName(className);
    } catch (ClassNotFoundException e) {
        throw new StorageException("Unknown class: " + className, e);
    }
    Object instance;
    try {
        instance = klass.newInstance();
    } catch (Exception e) {
        throw new StorageException("Cannot instantiate class: " + className, e);
    }
    if (!(instance instanceof XADataSource)) {
        throw new StorageException("Not a XADataSource: " + className);
    }
    xadatasource = (XADataSource) instance;
    // set JavaBean properties on the datasource
    for (Entry<String, String> entry : repositoryDescriptor.properties.entrySet()) {
        String name = entry.getKey();
        Object value = Framework.expandVars(entry.getValue());
        if (name.contains("/")) {
            // old syntax where non-String types were explicited
            name = name.substring(0, name.indexOf('/'));
        }
        // transform to proper JavaBean convention
        if (Character.isLowerCase(name.charAt(1))) {
            name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
        }
        try {
            BeanUtils.setProperty(xadatasource, name, value);
        } catch (Exception e) {
            log.error(String.format("Cannot set %s = %s", name, value));
        }
    }
}
Example 31
Project: Quartz-master  File: JNDIConnectionProvider.java View source code
public Connection getConnection() throws SQLException {
    Context ctx = null;
    try {
        Object ds = this.datasource;
        if (ds == null || isAlwaysLookup()) {
            ctx = (props != null) ? new InitialContext(props) : new InitialContext();
            ds = ctx.lookup(url);
            if (!isAlwaysLookup()) {
                this.datasource = ds;
            }
        }
        if (ds == null) {
            throw new SQLException("There is no object at the JNDI URL '" + url + "'");
        }
        if (ds instanceof XADataSource) {
            return (((XADataSource) ds).getXAConnection().getConnection());
        } else if (ds instanceof DataSource) {
            return ((DataSource) ds).getConnection();
        } else {
            throw new SQLException("Object at JNDI URL '" + url + "' is not a DataSource.");
        }
    } catch (Exception e) {
        this.datasource = null;
        throw new SQLException("Could not retrieve datasource via JNDI url '" + url + "' " + e.getClass().getName() + ": " + e.getMessage());
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception ignore) {
            }
        }
    }
}
Example 32
Project: quartz-scheduler-master  File: JNDIConnectionProvider.java View source code
public Connection getConnection() throws SQLException {
    Context ctx = null;
    try {
        Object ds = this.datasource;
        if (ds == null || isAlwaysLookup()) {
            ctx = (props != null) ? new InitialContext(props) : new InitialContext();
            ds = ctx.lookup(url);
            if (!isAlwaysLookup()) {
                this.datasource = ds;
            }
        }
        if (ds == null) {
            throw new SQLException("There is no object at the JNDI URL '" + url + "'");
        }
        if (ds instanceof XADataSource) {
            return (((XADataSource) ds).getXAConnection().getConnection());
        } else if (ds instanceof DataSource) {
            return ((DataSource) ds).getConnection();
        } else {
            throw new SQLException("Object at JNDI URL '" + url + "' is not a DataSource.");
        }
    } catch (Exception e) {
        this.datasource = null;
        throw new SQLException("Could not retrieve datasource via JNDI url '" + url + "' " + e.getClass().getName() + ": " + e.getMessage());
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception ignore) {
            }
        }
    }
}
Example 33
Project: siu-master  File: Renovation.java View source code
private String getCatalog(String dbName) throws NamingException, SQLException, BundleException {
    final DataSource dataSource = InitialContext.doLookup(dbName);
    try {
        if (!dataSource.isWrapperFor(XADataSource.class)) {
            throw new BundleException(dbName + " is not XADataSource!", BundleException.ACTIVATOR_ERROR);
        }
    } catch (SQLFeatureNotSupportedException e) {
        throw new BundleException(dbName + " is not XADataSource!", BundleException.ACTIVATOR_ERROR);
    }
    final Connection connection = dataSource.getConnection();
    try {
        return connection.getCatalog();
    } finally {
        connection.close();
    }
}
Example 34
Project: teiid-master  File: DataSourceConnection.java View source code
private XAConnection createConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    //$NON-NLS-1$ //$NON-NLS-2$
    TestLogger.log("Creating Datasource Connection: \"" + this.serverName + " - " + this.databaseName + "\"");
    DataSource ds = (DataSource) Class.forName(this.driver).newInstance();
    if (ds instanceof BaseDataSource) {
        BaseDataSource dataSource = (BaseDataSource) ds;
        dataSource.setDatabaseName(this.databaseName);
        if (this.applName != null) {
            dataSource.setApplicationName(this.applName);
        }
        ((TeiidDataSource) dataSource).setServerName(this.serverName);
        ((TeiidDataSource) dataSource).setPortNumber(Integer.parseInt(this.portNumber));
        if (this.username != null) {
            dataSource.setUser(this.username);
            dataSource.setPassword(this.pwd);
        }
        return ((XADataSource) dataSource).getXAConnection(this.username, this.pwd);
    }
    Properties props = new Properties();
    props.setProperty(DS_DATABASENAME, this.databaseName);
    props.setProperty(DS_SERVERPORT, this.portNumber);
    props.setProperty(DS_URL, this.url);
    props.setProperty(DS_SERVERNAME, this.serverName);
    if (this.username != null) {
        props.setProperty(DS_USERNAME, this.username);
        props.setProperty(DS_USER, this.username);
        props.setProperty(DS_PASSWORD, this.pwd);
    }
    PropertiesUtils.setBeanProperties(ds, props, null);
    return ((XADataSource) ds).getXAConnection();
}
Example 35
Project: bitronix-hp-master  File: JdbcPoolTest.java View source code
public void testWrappers() throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("*** Starting testWrappers");
    }
    try {
        Connection.class.getMethod("isWrapperFor");
    } catch (NoSuchMethodException e) {
        return;
    }
    // XADataSource
    assertTrue(pds.isWrapperFor(XADataSource.class));
    assertFalse(pds.isWrapperFor(DataSource.class));
    XADataSource unwrappedXads = (XADataSource) pds.unwrap(XADataSource.class);
    assertEquals(MockitoXADataSource.class.getName(), unwrappedXads.getClass().getName());
    // Connection
    Connection c = pds.getConnection();
    assertTrue(isWrapperFor(c, Connection.class));
    Connection unwrappedConnection = (Connection) unwrap(c, Connection.class);
    assertTrue(unwrappedConnection.getClass().getName().contains("java.sql.Connection") && unwrappedConnection.getClass().getName().contains("EnhancerByMockito"));
    // Statement
    Statement stmt = c.createStatement();
    assertTrue(isWrapperFor(stmt, Statement.class));
    Statement unwrappedStmt = (Statement) unwrap(stmt, Statement.class);
    assertTrue(unwrappedStmt.getClass().getName().contains("java.sql.Statement") && unwrappedStmt.getClass().getName().contains("EnhancerByMockito"));
    // PreparedStatement
    PreparedStatement pstmt = c.prepareStatement("mock sql");
    assertTrue(isWrapperFor(pstmt, PreparedStatement.class));
    Statement unwrappedPStmt = (Statement) unwrap(pstmt, PreparedStatement.class);
    assertTrue(unwrappedPStmt.getClass().getName().contains("java.sql.PreparedStatement") && unwrappedPStmt.getClass().getName().contains("EnhancerByMockito"));
    // CallableStatement
    CallableStatement cstmt = c.prepareCall("mock stored proc");
    assertTrue(isWrapperFor(cstmt, CallableStatement.class));
    Statement unwrappedCStmt = (Statement) unwrap(cstmt, CallableStatement.class);
    assertTrue(unwrappedCStmt.getClass().getName().contains("java.sql.CallableStatement") && unwrappedCStmt.getClass().getName().contains("EnhancerByMockito"));
}
Example 36
Project: btm-fork-master  File: JdbcPoolTest.java View source code
public void testWrappers() throws Exception {
    try {
        Connection.class.getMethod("isWrapperFor");
    } catch (NoSuchMethodException e) {
        return;
    }
    // XADataSource
    assertTrue(pds.isWrapperFor(XADataSource.class));
    assertFalse(pds.isWrapperFor(DataSource.class));
    XADataSource unwrappedXads = (XADataSource) pds.unwrap(XADataSource.class);
    assertEquals(MockitoXADataSource.class.getName(), unwrappedXads.getClass().getName());
    // Connection
    Connection c = pds.getConnection();
    assertTrue(isWrapperFor(c, Connection.class));
    Connection unwrappedConnection = (Connection) unwrap(c, Connection.class);
    assertTrue(unwrappedConnection.getClass().getName().contains("java.sql.Connection") && unwrappedConnection.getClass().getName().contains("EnhancerByMockito"));
    // Statement
    Statement stmt = c.createStatement();
    assertTrue(isWrapperFor(stmt, Statement.class));
    Statement unwrappedStmt = (Statement) unwrap(stmt, Statement.class);
    assertTrue(unwrappedStmt.getClass().getName().contains("java.sql.Statement") && unwrappedStmt.getClass().getName().contains("EnhancerByMockito"));
    // PreparedStatement
    PreparedStatement pstmt = c.prepareStatement("mock sql");
    assertTrue(isWrapperFor(pstmt, PreparedStatement.class));
    Statement unwrappedPStmt = (Statement) unwrap(pstmt, PreparedStatement.class);
    assertTrue(unwrappedPStmt.getClass().getName().contains("java.sql.PreparedStatement") && unwrappedPStmt.getClass().getName().contains("EnhancerByMockito"));
    // CallableStatement
    CallableStatement cstmt = c.prepareCall("mock stored proc");
    assertTrue(isWrapperFor(cstmt, CallableStatement.class));
    Statement unwrappedCStmt = (Statement) unwrap(cstmt, CallableStatement.class);
    assertTrue(unwrappedCStmt.getClass().getName().contains("java.sql.CallableStatement") && unwrappedCStmt.getClass().getName().contains("EnhancerByMockito"));
}
Example 37
Project: btm-master  File: JdbcPoolTest.java View source code
public void testWrappers() throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("*** Starting testWrappers");
    }
    // XADataSource
    assertTrue(pds.isWrapperFor(XADataSource.class));
    assertFalse(pds.isWrapperFor(DataSource.class));
    XADataSource unwrappedXads = pds.unwrap(XADataSource.class);
    assertEquals(MockitoXADataSource.class.getName(), unwrappedXads.getClass().getName());
    // Connection
    Connection c = pds.getConnection();
    assertTrue(isWrapperFor(c, Connection.class));
    Connection unwrappedConnection = (Connection) unwrap(c, Connection.class);
    assertTrue(unwrappedConnection.getClass().getName().contains("java.sql.Connection") && unwrappedConnection.getClass().getName().contains("EnhancerByMockito"));
    // Statement
    Statement stmt = c.createStatement();
    assertTrue(isWrapperFor(stmt, Statement.class));
    Statement unwrappedStmt = (Statement) unwrap(stmt, Statement.class);
    assertTrue(unwrappedStmt.getClass().getName().contains("java.sql.Statement") && unwrappedStmt.getClass().getName().contains("EnhancerByMockito"));
    // PreparedStatement
    PreparedStatement pstmt = c.prepareStatement("mock sql");
    assertTrue(isWrapperFor(pstmt, PreparedStatement.class));
    Statement unwrappedPStmt = (Statement) unwrap(pstmt, PreparedStatement.class);
    assertTrue(unwrappedPStmt.getClass().getName().contains("java.sql.PreparedStatement") && unwrappedPStmt.getClass().getName().contains("EnhancerByMockito"));
    // CallableStatement
    CallableStatement cstmt = c.prepareCall("mock stored proc");
    assertTrue(isWrapperFor(cstmt, CallableStatement.class));
    Statement unwrappedCStmt = (Statement) unwrap(cstmt, CallableStatement.class);
    assertTrue(unwrappedCStmt.getClass().getName().contains("java.sql.CallableStatement") && unwrappedCStmt.getClass().getName().contains("EnhancerByMockito"));
}
Example 38
Project: droolsjbpm-master  File: PoolingDataSource.java View source code
private void buildXAPool() throws Exception {
    if (this.pool != null)
        return;
    if (log.isDebugEnabled())
        log.debug("building XA pool for " + getUniqueName() + " with " + getMinPoolSize() + " connection(s)");
    this.pool = new XAPool(this, this);
    this.xaDataSource = (XADataSource) pool.getXAFactory();
    ResourceRegistrar.register(this);
}
Example 39
Project: tomcat70-master  File: DataSourceFactory.java View source code
// -------------------------------------------------- ObjectFactory Methods
/**
     * <p>Create and return a new <code>BasicDataSource</code> instance.  If no
     * instance can be created, return <code>null</code> instead.</p>
     *
     * @param obj The possibly null object containing location or
     *  reference information that can be used in creating an object
     * @param name The name of this object relative to <code>nameCtx</code>
     * @param nameCtx The context relative to which the <code>name</code>
     *  parameter is specified, or <code>null</code> if <code>name</code>
     *  is relative to the default initial context
     * @param environment The possibly null environment that is used in
     *  creating this object
     *
     * @exception Exception if an exception occurs creating the instance
     */
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
    // that specify a class name of "javax.sql.DataSource"
    if ((obj == null) || !(obj instanceof Reference)) {
        return null;
    }
    Reference ref = (Reference) obj;
    boolean XA = false;
    boolean ok = false;
    if ("javax.sql.DataSource".equals(ref.getClassName())) {
        ok = true;
    }
    if ("javax.sql.XADataSource".equals(ref.getClassName())) {
        ok = true;
        XA = true;
    }
    if (org.apache.tomcat.jdbc.pool.DataSource.class.getName().equals(ref.getClassName())) {
        ok = true;
    }
    if (!ok) {
        log.warn(ref.getClassName() + " is not a valid class name/type for this JNDI factory.");
        return null;
    }
    Properties properties = new Properties();
    for (int i = 0; i < ALL_PROPERTIES.length; i++) {
        String propertyName = ALL_PROPERTIES[i];
        RefAddr ra = ref.get(propertyName);
        if (ra != null) {
            String propertyValue = ra.getContent().toString();
            properties.setProperty(propertyName, propertyValue);
        }
    }
    return createDataSource(properties, nameCtx, XA);
}
Example 40
Project: bboss-master  File: BasicManagedDataSource.java View source code
@Override
protected ConnectionFactory createConnectionFactory() throws SQLException {
    if (transactionManager == null) {
        throw new SQLException("Transaction manager must be set before a connection can be created");
    }
    // If xa data source is not specified a DriverConnectionFactory is created and wrapped with a LocalXAConnectionFactory
    if (xaDataSource == null) {
        ConnectionFactory connectionFactory = super.createConnectionFactory();
        XAConnectionFactory xaConnectionFactory = new LocalXAConnectionFactory(getTransactionManager(), connectionFactory);
        transactionRegistry = xaConnectionFactory.getTransactionRegistry();
        return xaConnectionFactory;
    }
    // Create the XADataSource instance using the configured class name if it has not been set
    if (xaDataSourceInstance == null) {
        Class<?> xaDataSourceClass = null;
        try {
            xaDataSourceClass = Class.forName(xaDataSource);
        } catch (Exception t) {
            String message = "Cannot load XA data source class '" + xaDataSource + "'";
            throw new SQLException(message, t);
        }
        try {
            xaDataSourceInstance = (XADataSource) xaDataSourceClass.newInstance();
        } catch (Exception t) {
            String message = "Cannot create XA data source of class '" + xaDataSource + "'";
            throw new SQLException(message, t);
        }
    }
    // finally, create the XAConectionFactory using the XA data source
    XAConnectionFactory xaConnectionFactory = new DataSourceXAConnectionFactory(getTransactionManager(), xaDataSourceInstance, getUsername(), getPassword());
    transactionRegistry = xaConnectionFactory.getTransactionRegistry();
    return xaConnectionFactory;
}
Example 41
Project: ByteTCC-master  File: XAResourceDeserializerImpl.java View source code
private XAResourceDescriptor deserializeResource(String identifier, Object bean) throws Exception {
    if (DataSourceHolder.class.isInstance(bean)) {
        DataSourceHolder holder = (DataSourceHolder) bean;
        RecoveredResource xares = new RecoveredResource();
        xares.setDataSource(holder.getDataSource());
        LocalXAResourceDescriptor descriptor = new LocalXAResourceDescriptor();
        descriptor.setDelegate(xares);
        descriptor.setIdentifier(identifier);
        return descriptor;
    } else if (javax.sql.DataSource.class.isInstance(bean)) {
        javax.sql.DataSource dataSource = (javax.sql.DataSource) bean;
        RecoveredResource xares = new RecoveredResource();
        xares.setDataSource(dataSource);
        LocalXAResourceDescriptor descriptor = new LocalXAResourceDescriptor();
        descriptor.setDelegate(xares);
        descriptor.setIdentifier(identifier);
        return descriptor;
    } else if (XADataSource.class.isInstance(bean)) {
        XADataSource xaDataSource = (XADataSource) bean;
        XAConnection xaConnection = xaDataSource.getXAConnection();
        java.sql.Connection connection = null;
        try {
            connection = xaConnection.getConnection();
            XAResource xares = xaConnection.getXAResource();
            CommonResourceDescriptor descriptor = new CommonResourceDescriptor();
            descriptor.setDelegate(xares);
            descriptor.setIdentifier(identifier);
            descriptor.setManaged(xaConnection);
            return descriptor;
        } catch (Exception ex) {
            logger.warn(ex.getMessage());
            XAResource xares = xaConnection.getXAResource();
            CommonResourceDescriptor descriptor = new CommonResourceDescriptor();
            descriptor.setDelegate(xares);
            descriptor.setIdentifier(identifier);
            descriptor.setManaged(xaConnection);
            return descriptor;
        } finally {
            this.closeQuietly(connection);
        }
    } else if (XAConnectionFactory.class.isInstance(bean)) {
        XAConnectionFactory connectionFactory = (XAConnectionFactory) bean;
        javax.jms.XAConnection xaConnection = connectionFactory.createXAConnection();
        XASession xaSession = xaConnection.createXASession();
        javax.jms.Session session = null;
        try {
            session = xaSession.getSession();
            XAResource xares = xaSession.getXAResource();
            CommonResourceDescriptor descriptor = new CommonResourceDescriptor();
            descriptor.setDelegate(xares);
            descriptor.setIdentifier(identifier);
            descriptor.setManaged(xaConnection);
            return descriptor;
        } catch (Exception ex) {
            logger.warn(ex.getMessage());
            XAResource xares = xaSession.getXAResource();
            CommonResourceDescriptor descriptor = new CommonResourceDescriptor();
            descriptor.setDelegate(xares);
            descriptor.setIdentifier(identifier);
            descriptor.setManaged(xaConnection);
            return descriptor;
        } finally {
            this.closeQuietly(session);
        }
    } else if (ManagedConnectionFactory.class.isInstance(bean)) {
        ManagedConnectionFactory connectionFactory = (ManagedConnectionFactory) bean;
        ManagedConnection managedConnection = connectionFactory.createManagedConnection(null, null);
        javax.resource.cci.Connection connection = null;
        try {
            connection = (javax.resource.cci.Connection) managedConnection.getConnection(null, null);
            XAResource xares = managedConnection.getXAResource();
            CommonResourceDescriptor descriptor = new CommonResourceDescriptor();
            descriptor.setDelegate(xares);
            descriptor.setIdentifier(identifier);
            descriptor.setManaged(managedConnection);
            return descriptor;
        } catch (Exception ex) {
            logger.warn(ex.getMessage());
            XAResource xares = managedConnection.getXAResource();
            CommonResourceDescriptor descriptor = new CommonResourceDescriptor();
            descriptor.setDelegate(xares);
            descriptor.setIdentifier(identifier);
            descriptor.setManaged(managedConnection);
            return descriptor;
        } finally {
            this.closeQuietly(connection);
        }
    } else {
        return null;
    }
}
Example 42
Project: clearpool-master  File: ConfigurationVO.java View source code
/**
   * Set dataSource if dataSource is null, check if it's null after setting.And create dataSource by
   * factory.
   */
private void handlerDatasource() {
    if (this.commonDataSource == null) {
        // if we haven't get dataSource from configuration,we should try to
        // get it by DataSourceHolder.
        Map<String, CommonDataSource> dataSourceMap = DataSourceHolder.getDataSourceMap();
        if (dataSourceMap != null) {
            this.commonDataSource = dataSourceMap.get(this.alias);
        }
        if (this.commonDataSource == null) {
            throw new ConnectionPoolXMLParseException("cfg should have a driver or a jndi,otherwise you should set datasource in DataSourceHolder");
        }
    }
    if (this.jtaSupport) {
        if (this.commonDataSource instanceof JDBCDataSource) {
            this.factory = new JDBCXADataSourceFactory();
        } else if (this.commonDataSource instanceof XADataSource) {
            this.factory = new XADataSourceFactory();
        }
    } else {
        if (this.commonDataSource instanceof DataSource) {
            this.factory = new DataSourceFactory();
        } else if (this.commonDataSource instanceof JDBCDataSource) {
            this.factory = new JDBCDataSourceFactory();
        } else if (this.commonDataSource instanceof ConnectionPoolDataSource) {
            this.factory = new PoolDataSourceFactory();
        }
    }
    if (this.factory == null) {
        throw new UnsupportedOperationException("we don't support the datasource: " + this.commonDataSource.getClass().getName());
    }
    this.dataSource = this.factory.createDataSource(this.commonDataSource);
}
Example 43
Project: commons-dbcp-optivo-master  File: BasicManagedDataSource.java View source code
protected ConnectionFactory createConnectionFactory() throws SQLException {
    if (transactionManager == null) {
        throw new SQLException("Transaction manager must be set before a connection can be created");
    }
    // If xa data source is not specified a DriverConnectionFactory is created and wrapped with a LocalXAConnectionFactory
    if (xaDataSource == null) {
        ConnectionFactory connectionFactory = super.createConnectionFactory();
        XAConnectionFactory xaConnectionFactory = new LocalXAConnectionFactory(getTransactionManager(), connectionFactory);
        transactionRegistry = xaConnectionFactory.getTransactionRegistry();
        return xaConnectionFactory;
    }
    // Create the XADataSource instance using the configured class name if it has not been set
    if (xaDataSourceInstance == null) {
        Class xaDataSourceClass = null;
        try {
            xaDataSourceClass = Class.forName(xaDataSource);
        } catch (Throwable t) {
            String message = "Cannot load XA data source class '" + xaDataSource + "'";
            throw (SQLException) new SQLException(message).initCause(t);
        }
        try {
            xaDataSourceInstance = (XADataSource) xaDataSourceClass.newInstance();
        } catch (Throwable t) {
            String message = "Cannot create XA data source of class '" + xaDataSource + "'";
            throw (SQLException) new SQLException(message).initCause(t);
        }
    }
    // finally, create the XAConectionFactory using the XA data source
    XAConnectionFactory xaConnectionFactory = new DataSourceXAConnectionFactory(getTransactionManager(), xaDataSourceInstance, username, password);
    transactionRegistry = xaConnectionFactory.getTransactionRegistry();
    return xaConnectionFactory;
}
Example 44
Project: mut4j-master  File: DataSourceProxyBase.java View source code
public PrintWriter getLogWriter() throws SQLException {
    if (targetDS instanceof DataSource)
        return ((DataSource) targetDS).getLogWriter();
    if (targetDS instanceof XADataSource)
        return ((XADataSource) targetDS).getLogWriter();
    if (targetDS instanceof ConnectionPoolDataSource)
        return ((ConnectionPoolDataSource) targetDS).getLogWriter();
    throw new SQLException("targetDS doesn't have getLogWriter() method");
}
Example 45
Project: nuxeo-core-master  File: JDBCBackend.java View source code
@Override
public void initialize(RepositoryImpl repository) throws StorageException {
    this.repository = repository;
    RepositoryDescriptor repositoryDescriptor = repository.getRepositoryDescriptor();
    pseudoDataSourceName = ConnectionHelper.getPseudoDataSourceNameForRepository(repositoryDescriptor.name);
    try {
        DataSource ds = DataSourceHelper.getDataSource(pseudoDataSourceName);
        if (ds instanceof PooledDataSource) {
            isPooledDataSource = true;
            return;
        }
    } catch (NamingException cause) {
        ;
    }
    // try single-datasource non-XA mode
    try (Connection connection = ConnectionHelper.getConnection(pseudoDataSourceName)) {
        if (connection != null) {
            return;
        }
    } catch (SQLException cause) {
        throw new StorageException("Connection error", cause);
    }
    // standard XA mode
    // instantiate the XA datasource
    String className = repositoryDescriptor.xaDataSourceName;
    Class<?> klass;
    try {
        klass = Class.forName(className);
    } catch (ClassNotFoundException e) {
        throw new StorageException("Unknown class: " + className, e);
    }
    Object instance;
    try {
        instance = klass.newInstance();
    } catch (Exception e) {
        throw new StorageException("Cannot instantiate class: " + className, e);
    }
    if (!(instance instanceof XADataSource)) {
        throw new StorageException("Not a XADataSource: " + className);
    }
    xadatasource = (XADataSource) instance;
    // set JavaBean properties on the datasource
    for (Entry<String, String> entry : repositoryDescriptor.properties.entrySet()) {
        String name = entry.getKey();
        Object value = Framework.expandVars(entry.getValue());
        if (name.contains("/")) {
            // old syntax where non-String types were explicited
            name = name.substring(0, name.indexOf('/'));
        }
        // transform to proper JavaBean convention
        if (Character.isLowerCase(name.charAt(1))) {
            name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
        }
        try {
            BeanUtils.setProperty(xadatasource, name, value);
        } catch (Exception e) {
            log.error(String.format("Cannot set %s = %s", name, value));
        }
    }
}
Example 46
Project: nuxeo-master  File: PooledDataSourceFactory.java View source code
protected ManagedConnectionFactory createFactory(Reference ref, Context ctx) throws NamingException, InvalidPropertyException {
    String className = ref.getClassName();
    if (XADataSource.class.getName().equals(className)) {
        String user = refAttribute(ref, "User", "");
        String password = refAttribute(ref, "Password", "");
        String name = refAttribute(ref, "dataSourceJNDI", null);
        XADataSource ds = NuxeoContainer.lookup(name, XADataSource.class);
        XADataSourceWrapper wrapper = new XADataSourceWrapper(ds);
        wrapper.setUserName(user);
        wrapper.setPassword(password);
        return wrapper;
    }
    if (javax.sql.DataSource.class.getName().equals(className)) {
        String user = refAttribute(ref, "username", "");
        if (user.isEmpty()) {
            user = refAttribute(ref, "user", "");
            if (!user.isEmpty()) {
                LogFactory.getLog(PooledDataSourceFactory.class).warn("wrong attribute 'user' in datasource descriptor, should use 'username' instead");
            }
        }
        String password = refAttribute(ref, "password", "");
        String dsname = refAttribute(ref, "dataSourceJNDI", "");
        if (!dsname.isEmpty()) {
            javax.sql.DataSource ds = NuxeoContainer.lookup(dsname, DataSource.class);
            LocalDataSourceWrapper wrapper = new LocalDataSourceWrapper(ds);
            wrapper.setUserName(user);
            wrapper.setPassword(password);
            return wrapper;
        }
        String name = refAttribute(ref, "driverClassName", null);
        String url = refAttribute(ref, "url", null);
        String sqlExceptionSorter = refAttribute(ref, "sqlExceptionSorter", DatasourceExceptionSorter.class.getName());
        boolean commitBeforeAutocommit = Boolean.valueOf(refAttribute(ref, "commitBeforeAutocommit", "true")).booleanValue();
        JdbcConnectionFactory factory = new JdbcConnectionFactory();
        factory.setDriver(name);
        factory.setUserName(user);
        factory.setPassword(password);
        factory.setConnectionURL(url);
        factory.setExceptionSorterClass(sqlExceptionSorter);
        factory.setCommitBeforeAutocommit(commitBeforeAutocommit);
        return factory;
    }
    throw new IllegalArgumentException("unsupported class " + className);
}
Example 47
Project: ofbiz-master  File: JNDITransactionFactory.java View source code
public static Connection getJndiConnection(String jndiName, String jndiServerName) throws SQLException, GenericEntityException {
    // if (Debug.verboseOn()) Debug.logVerbose("Trying JNDI name " + jndiName, module);
    DataSource ds = dsCache.get(jndiName);
    if (ds != null) {
        if (ds instanceof XADataSource) {
            XADataSource xads = (XADataSource) ds;
            return TransactionUtil.enlistConnection(xads.getXAConnection());
        } else {
            return ds.getConnection();
        }
    }
    try {
        if (Debug.infoOn())
            Debug.logInfo("Doing JNDI lookup for name " + jndiName, module);
        InitialContext ic = JNDIContextFactory.getInitialContext(jndiServerName);
        if (ic != null) {
            ds = (DataSource) ic.lookup(jndiName);
        } else {
            Debug.logWarning("Initial Context returned was NULL for server name " + jndiServerName, module);
        }
        if (ds != null) {
            if (Debug.verboseOn())
                Debug.logVerbose("Got a Datasource object.", module);
            dsCache.putIfAbsent(jndiName, ds);
            ds = dsCache.get(jndiName);
            Connection con;
            if (ds instanceof XADataSource) {
                if (Debug.infoOn())
                    Debug.logInfo("Got XADataSource for name " + jndiName, module);
                XADataSource xads = (XADataSource) ds;
                XAConnection xac = xads.getXAConnection();
                con = TransactionUtil.enlistConnection(xac);
            } else {
                if (Debug.infoOn())
                    Debug.logInfo("Got DataSource for name " + jndiName, module);
                con = ds.getConnection();
            }
            return con;
        } else {
            Debug.logError("Datasource returned was NULL.", module);
        }
    } catch (NamingException ne) {
        Debug.logWarning(ne, "Failed to find DataSource named " + jndiName + " in JNDI server with name " + jndiServerName + ". Trying normal database.", module);
    } catch (GenericConfigException gce) {
        throw new GenericEntityException("Problems with the JNDI configuration.", gce.getNested());
    }
    return null;
}
Example 48
Project: SQLBulkQueryTool-master  File: DataSourceConnection.java View source code
private XAConnection createConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    FrameworkPlugin.LOGGER.info(//$NON-NLS-1$ //$NON-NLS-2$
    "Creating Datasource Connection: \"" + this.serverName + " - " + this.databaseName + "\"");
    DataSource ds = (DataSource) Class.forName(this.driver).newInstance();
    // if (ds instanceof DataSource) {
    //
    // DataSource dataSource = (DataSource) ds;
    //
    // dataSource.setDatabaseName(this.databaseName);
    // if (this.applName != null) {
    // dataSource.setApplicationName(this.applName);
    // }
    //
    // ((TeiidDataSource) dataSource).setServerName(this.serverName);
    // ((TeiidDataSource)
    // dataSource).setPortNumber(Integer.parseInt(this.portNumber));
    //
    // if (this.username != null) {
    // dataSource.setUser(this.username);
    // dataSource.setPassword(this.pwd);
    // }
    //
    // return ((XADataSource) dataSource).getXAConnection(this.username,
    // this.pwd);
    // }
    Properties props = new Properties();
    props.setProperty(DS_DATABASENAME, this.databaseName);
    props.setProperty(DS_SERVERPORT, this.portNumber);
    props.setProperty(DS_URL, this.url);
    props.setProperty(DS_SERVERNAME, this.serverName);
    if (this.username != null) {
        props.setProperty(DS_USERNAME, this.username);
        props.setProperty(DS_USER, this.username);
        props.setProperty(DS_PASSWORD, this.pwd);
    }
    if (this.applName != null) {
        props.setProperty(DS_APPLICATION_NAME, applName);
    }
    PropertiesUtils.setBeanProperties(ds, props, null);
    return ((XADataSource) ds).getXAConnection();
}
Example 49
Project: h2-bitmap-master  File: TestXA.java View source code
private void testXA(boolean useOneDatabase) throws SQLException {
    String url1 = getURL(DB_NAME1, true);
    String url2 = getURL(DB_NAME2, true);
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    Connection conn1 = null;
    Connection conn2 = null;
    Statement stat1 = null;
    Statement stat2 = null;
    try {
        trace("xads1 = createXADatasource1()");
        XADataSource xaDs1 = createXADatasource(useOneDatabase, url1);
        trace("xads2 = createXADatasource2()");
        XADataSource xaDs2 = createXADatasource(useOneDatabase, url2);
        trace("xacon1 = xads1.getXAConnection()");
        xaConn1 = xaDs1.getXAConnection();
        trace("xacon2 = xads2.getXAConnection()");
        xaConn2 = xaDs2.getXAConnection();
        trace("xares1 = xacon1.getXAResource()");
        XAResource xares1 = xaConn1.getXAResource();
        trace("xares2 = xacon2.getXAResource()");
        XAResource xares2 = xaConn2.getXAResource();
        trace("xares1.recover(XAResource.TMSTARTRSCAN)");
        Xid[] xids1 = xares1.recover(XAResource.TMSTARTRSCAN);
        if ((xids1 == null) || (xids1.length == 0)) {
            trace("xares1.recover(XAResource.TMSTARTRSCAN): 0");
        } else {
            trace("xares1.recover(XAResource.TMSTARTRSCAN): " + xids1.length);
        }
        trace("xares2.recover(XAResource.TMSTARTRSCAN)");
        Xid[] xids2 = xares2.recover(XAResource.TMSTARTRSCAN);
        if ((xids2 == null) || (xids2.length == 0)) {
            trace("xares2.recover(XAResource.TMSTARTRSCAN): 0");
        } else {
            trace("xares2.recover(XAResource.TMSTARTRSCAN): " + xids2.length);
        }
        trace("con1 = xacon1.getConnection()");
        conn1 = xaConn1.getConnection();
        trace("stmt1 = con1.createStatement()");
        stat1 = conn1.createStatement();
        trace("con2 = xacon2.getConnection()");
        conn2 = xaConn2.getConnection();
        trace("stmt2 = con2.createStatement()");
        stat2 = conn2.createStatement();
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"DROP TABLE xatest1\")");
            try {
                stat1.executeUpdate("DROP TABLE xatest1");
            } catch (SQLException e) {
            }
            trace("stmt2.executeUpdate(\"DROP TABLE xatest2\")");
            try {
                stat2.executeUpdate("DROP TABLE xatest2");
            } catch (SQLException e) {
            }
        } else {
            trace("stmt1.executeUpdate(\"DROP TABLE xatest\")");
            try {
                stat1.executeUpdate("DROP TABLE xatest");
            } catch (SQLException e) {
            }
            trace("stmt2.executeUpdate(\"DROP TABLE xatest\")");
            try {
                stat2.executeUpdate("DROP TABLE xatest");
            } catch (SQLException e) {
            }
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"CREATE TABLE xatest1 (id INT PRIMARY KEY, value INT)\")");
            stat1.executeUpdate("CREATE TABLE xatest1 (id INT PRIMARY KEY, value INT)");
            trace("stmt2.executeUpdate(\"CREATE TABLE xatest2 (id INT PRIMARY KEY, value INT)\")");
            stat2.executeUpdate("CREATE TABLE xatest2 (id INT PRIMARY KEY, value INT)");
        } else {
            trace("stmt1.executeUpdate(\"CREATE TABLE xatest (id INT PRIMARY KEY, value INT)\")");
            stat1.executeUpdate("CREATE TABLE xatest (id INT PRIMARY KEY, value INT)");
            trace("stmt2.executeUpdate(\"CREATE TABLE xatest (id INT PRIMARY KEY, value INT)\")");
            stat2.executeUpdate("CREATE TABLE xatest (id INT PRIMARY KEY, value INT)");
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"INSERT INTO xatest1 VALUES (1, 0)\")");
            stat1.executeUpdate("INSERT INTO xatest1 VALUES (1, 0)");
            trace("stmt2.executeUpdate(\"INSERT INTO xatest2 VALUES (2, 0)\")");
            stat2.executeUpdate("INSERT INTO xatest2 VALUES (2, 0)");
        } else {
            trace("stmt1.executeUpdate(\"INSERT INTO xatest VALUES (1, 0)\")");
            stat1.executeUpdate("INSERT INTO xatest VALUES (1, 0)");
            trace("stmt2.executeUpdate(\"INSERT INTO xatest VALUES (2, 0)\")");
            stat2.executeUpdate("INSERT INTO xatest VALUES (2, 0)");
        }
        Xid xid1 = null;
        Xid xid2 = null;
        if (useOneDatabase) {
            xid1 = SimpleXid.createRandom();
            xid2 = SimpleXid.createRandom();
        } else {
            xid1 = SimpleXid.createRandom();
            xid2 = xid1;
        }
        if (useOneDatabase) {
            trace("xares1.start(xid1, XAResource.TMNOFLAGS)");
            xares1.start(xid1, XAResource.TMNOFLAGS);
            trace("xares2.start(xid2, XAResource.TMJOIN)");
            xares2.start(xid2, XAResource.TMJOIN);
        } else {
            trace("xares1.start(xid1, XAResource.TMNOFLAGS)");
            xares1.start(xid1, XAResource.TMNOFLAGS);
            trace("xares2.start(xid2, XAResource.TMNOFLAGS)");
            xares2.start(xid2, XAResource.TMNOFLAGS);
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"UPDATE xatest1 SET value=1 WHERE id=1\")");
            stat1.executeUpdate("UPDATE xatest1 SET value=1 WHERE id=1");
            trace("stmt2.executeUpdate(\"UPDATE xatest2 SET value=1 WHERE id=2\")");
            stat2.executeUpdate("UPDATE xatest2 SET value=1 WHERE id=2");
        } else {
            trace("stmt1.executeUpdate(\"UPDATE xatest SET value=1 WHERE id=1\")");
            stat1.executeUpdate("UPDATE xatest SET value=1 WHERE id=1");
            trace("stmt2.executeUpdate(\"UPDATE xatest SET value=1 WHERE id=2\")");
            stat2.executeUpdate("UPDATE xatest SET value=1 WHERE id=2");
        }
        trace("xares1.end(xid1, XAResource.TMSUCCESS)");
        xares1.end(xid1, XAResource.TMSUCCESS);
        trace("xares2.end(xid2, XAResource.TMSUCCESS)");
        xares2.end(xid2, XAResource.TMSUCCESS);
        int ret1;
        int ret2;
        trace("ret1 = xares1.prepare(xid1)");
        ret1 = xares1.prepare(xid1);
        trace("xares1.prepare(xid1): " + ret1);
        trace("ret2 = xares2.prepare(xid2)");
        ret2 = xares2.prepare(xid2);
        trace("xares2.prepare(xid2): " + ret2);
        if ((ret1 != XAResource.XA_OK) && (ret1 != XAResource.XA_RDONLY)) {
            throw new IllegalStateException("xares1.prepare(xid1) must return XA_OK or XA_RDONLY");
        }
        if ((ret2 != XAResource.XA_OK) && (ret2 != XAResource.XA_RDONLY)) {
            throw new IllegalStateException("xares2.prepare(xid2) must return XA_OK or XA_RDONLY");
        }
        if (ret1 == XAResource.XA_OK) {
            trace("xares1.commit(xid1, false)");
            xares1.commit(xid1, false);
        }
        if (ret2 == XAResource.XA_OK) {
            trace("xares2.commit(xid2, false)");
            xares2.commit(xid2, false);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        JdbcUtils.closeSilently(stat1);
        JdbcUtils.closeSilently(stat2);
        JdbcUtils.closeSilently(conn1);
        JdbcUtils.closeSilently(conn2);
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 50
Project: H2-Mirror-master  File: TestXA.java View source code
private void testXA(boolean useOneDatabase) throws SQLException {
    String url1 = getURL(DB_NAME1, true);
    String url2 = getURL(DB_NAME2, true);
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    Connection conn1 = null;
    Connection conn2 = null;
    Statement stat1 = null;
    Statement stat2 = null;
    try {
        trace("xads1 = createXADatasource1()");
        XADataSource xaDs1 = createXADatasource(useOneDatabase, url1);
        trace("xads2 = createXADatasource2()");
        XADataSource xaDs2 = createXADatasource(useOneDatabase, url2);
        trace("xacon1 = xads1.getXAConnection()");
        xaConn1 = xaDs1.getXAConnection();
        trace("xacon2 = xads2.getXAConnection()");
        xaConn2 = xaDs2.getXAConnection();
        trace("xares1 = xacon1.getXAResource()");
        XAResource xares1 = xaConn1.getXAResource();
        trace("xares2 = xacon2.getXAResource()");
        XAResource xares2 = xaConn2.getXAResource();
        trace("xares1.recover(XAResource.TMSTARTRSCAN)");
        Xid[] xids1 = xares1.recover(XAResource.TMSTARTRSCAN);
        if ((xids1 == null) || (xids1.length == 0)) {
            trace("xares1.recover(XAResource.TMSTARTRSCAN): 0");
        } else {
            trace("xares1.recover(XAResource.TMSTARTRSCAN): " + xids1.length);
        }
        trace("xares2.recover(XAResource.TMSTARTRSCAN)");
        Xid[] xids2 = xares2.recover(XAResource.TMSTARTRSCAN);
        if ((xids2 == null) || (xids2.length == 0)) {
            trace("xares2.recover(XAResource.TMSTARTRSCAN): 0");
        } else {
            trace("xares2.recover(XAResource.TMSTARTRSCAN): " + xids2.length);
        }
        trace("con1 = xacon1.getConnection()");
        conn1 = xaConn1.getConnection();
        trace("stmt1 = con1.createStatement()");
        stat1 = conn1.createStatement();
        trace("con2 = xacon2.getConnection()");
        conn2 = xaConn2.getConnection();
        trace("stmt2 = con2.createStatement()");
        stat2 = conn2.createStatement();
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"DROP TABLE xatest1\")");
            try {
                stat1.executeUpdate("DROP TABLE xatest1");
            } catch (SQLException e) {
            }
            trace("stmt2.executeUpdate(\"DROP TABLE xatest2\")");
            try {
                stat2.executeUpdate("DROP TABLE xatest2");
            } catch (SQLException e) {
            }
        } else {
            trace("stmt1.executeUpdate(\"DROP TABLE xatest\")");
            try {
                stat1.executeUpdate("DROP TABLE xatest");
            } catch (SQLException e) {
            }
            trace("stmt2.executeUpdate(\"DROP TABLE xatest\")");
            try {
                stat2.executeUpdate("DROP TABLE xatest");
            } catch (SQLException e) {
            }
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"CREATE TABLE xatest1 " + "(id INT PRIMARY KEY, value INT)\")");
            stat1.executeUpdate("CREATE TABLE xatest1 " + "(id INT PRIMARY KEY, value INT)");
            trace("stmt2.executeUpdate(\"CREATE TABLE xatest2 " + "(id INT PRIMARY KEY, value INT)\")");
            stat2.executeUpdate("CREATE TABLE xatest2 " + "(id INT PRIMARY KEY, value INT)");
        } else {
            trace("stmt1.executeUpdate(\"CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)\")");
            stat1.executeUpdate("CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)");
            trace("stmt2.executeUpdate(\"CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)\")");
            stat2.executeUpdate("CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)");
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"INSERT INTO xatest1 " + "VALUES (1, 0)\")");
            stat1.executeUpdate("INSERT INTO xatest1 VALUES (1, 0)");
            trace("stmt2.executeUpdate(\"INSERT INTO xatest2 " + "VALUES (2, 0)\")");
            stat2.executeUpdate("INSERT INTO xatest2 " + "VALUES (2, 0)");
        } else {
            trace("stmt1.executeUpdate(\"INSERT INTO xatest " + "VALUES (1, 0)\")");
            stat1.executeUpdate("INSERT INTO xatest " + "VALUES (1, 0)");
            trace("stmt2.executeUpdate(\"INSERT INTO xatest " + "VALUES (2, 0)\")");
            stat2.executeUpdate("INSERT INTO xatest " + "VALUES (2, 0)");
        }
        Xid xid1 = null;
        Xid xid2 = null;
        if (useOneDatabase) {
            xid1 = SimpleXid.createRandom();
            xid2 = SimpleXid.createRandom();
        } else {
            xid1 = SimpleXid.createRandom();
            xid2 = xid1;
        }
        if (useOneDatabase) {
            trace("xares1.start(xid1, XAResource.TMNOFLAGS)");
            xares1.start(xid1, XAResource.TMNOFLAGS);
            trace("xares2.start(xid2, XAResource.TMJOIN)");
            xares2.start(xid2, XAResource.TMJOIN);
        } else {
            trace("xares1.start(xid1, XAResource.TMNOFLAGS)");
            xares1.start(xid1, XAResource.TMNOFLAGS);
            trace("xares2.start(xid2, XAResource.TMNOFLAGS)");
            xares2.start(xid2, XAResource.TMNOFLAGS);
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"UPDATE xatest1 " + "SET value=1 WHERE id=1\")");
            stat1.executeUpdate("UPDATE xatest1 " + "SET value=1 WHERE id=1");
            trace("stmt2.executeUpdate(\"UPDATE xatest2 " + "SET value=1 WHERE id=2\")");
            stat2.executeUpdate("UPDATE xatest2 " + "SET value=1 WHERE id=2");
        } else {
            trace("stmt1.executeUpdate(\"UPDATE xatest " + "SET value=1 WHERE id=1\")");
            stat1.executeUpdate("UPDATE xatest " + "SET value=1 WHERE id=1");
            trace("stmt2.executeUpdate(\"UPDATE xatest " + "SET value=1 WHERE id=2\")");
            stat2.executeUpdate("UPDATE xatest " + "SET value=1 WHERE id=2");
        }
        trace("xares1.end(xid1, XAResource.TMSUCCESS)");
        xares1.end(xid1, XAResource.TMSUCCESS);
        trace("xares2.end(xid2, XAResource.TMSUCCESS)");
        xares2.end(xid2, XAResource.TMSUCCESS);
        int ret1;
        int ret2;
        trace("ret1 = xares1.prepare(xid1)");
        ret1 = xares1.prepare(xid1);
        trace("xares1.prepare(xid1): " + ret1);
        trace("ret2 = xares2.prepare(xid2)");
        ret2 = xares2.prepare(xid2);
        trace("xares2.prepare(xid2): " + ret2);
        if ((ret1 != XAResource.XA_OK) && (ret1 != XAResource.XA_RDONLY)) {
            throw new IllegalStateException("xares1.prepare(xid1) must return XA_OK or XA_RDONLY");
        }
        if ((ret2 != XAResource.XA_OK) && (ret2 != XAResource.XA_RDONLY)) {
            throw new IllegalStateException("xares2.prepare(xid2) must return XA_OK or XA_RDONLY");
        }
        if (ret1 == XAResource.XA_OK) {
            trace("xares1.commit(xid1, false)");
            xares1.commit(xid1, false);
        }
        if (ret2 == XAResource.XA_OK) {
            trace("xares2.commit(xid2, false)");
            xares2.commit(xid2, false);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        JdbcUtils.closeSilently(stat1);
        JdbcUtils.closeSilently(stat2);
        JdbcUtils.closeSilently(conn1);
        JdbcUtils.closeSilently(conn2);
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 51
Project: H2-Research-master  File: TestXA.java View source code
private void testXA(boolean useOneDatabase) throws SQLException {
    String url1 = getURL(DB_NAME1, true);
    String url2 = getURL(DB_NAME2, true);
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    Connection conn1 = null;
    Connection conn2 = null;
    Statement stat1 = null;
    Statement stat2 = null;
    try {
        trace("xads1 = createXADatasource1()");
        XADataSource xaDs1 = createXADatasource(useOneDatabase, url1);
        trace("xads2 = createXADatasource2()");
        XADataSource xaDs2 = createXADatasource(useOneDatabase, url2);
        trace("xacon1 = xads1.getXAConnection()");
        xaConn1 = xaDs1.getXAConnection();
        trace("xacon2 = xads2.getXAConnection()");
        xaConn2 = xaDs2.getXAConnection();
        trace("xares1 = xacon1.getXAResource()");
        XAResource xares1 = xaConn1.getXAResource();
        trace("xares2 = xacon2.getXAResource()");
        XAResource xares2 = xaConn2.getXAResource();
        trace("xares1.recover(XAResource.TMSTARTRSCAN)");
        Xid[] xids1 = xares1.recover(XAResource.TMSTARTRSCAN);
        if ((xids1 == null) || (xids1.length == 0)) {
            trace("xares1.recover(XAResource.TMSTARTRSCAN): 0");
        } else {
            trace("xares1.recover(XAResource.TMSTARTRSCAN): " + xids1.length);
        }
        trace("xares2.recover(XAResource.TMSTARTRSCAN)");
        Xid[] xids2 = xares2.recover(XAResource.TMSTARTRSCAN);
        if ((xids2 == null) || (xids2.length == 0)) {
            trace("xares2.recover(XAResource.TMSTARTRSCAN): 0");
        } else {
            trace("xares2.recover(XAResource.TMSTARTRSCAN): " + xids2.length);
        }
        trace("con1 = xacon1.getConnection()");
        conn1 = xaConn1.getConnection();
        trace("stmt1 = con1.createStatement()");
        stat1 = conn1.createStatement();
        trace("con2 = xacon2.getConnection()");
        conn2 = xaConn2.getConnection();
        trace("stmt2 = con2.createStatement()");
        stat2 = conn2.createStatement();
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"DROP TABLE xatest1\")");
            try {
                stat1.executeUpdate("DROP TABLE xatest1");
            } catch (SQLException e) {
            }
            trace("stmt2.executeUpdate(\"DROP TABLE xatest2\")");
            try {
                stat2.executeUpdate("DROP TABLE xatest2");
            } catch (SQLException e) {
            }
        } else {
            trace("stmt1.executeUpdate(\"DROP TABLE xatest\")");
            try {
                stat1.executeUpdate("DROP TABLE xatest");
            } catch (SQLException e) {
            }
            trace("stmt2.executeUpdate(\"DROP TABLE xatest\")");
            try {
                stat2.executeUpdate("DROP TABLE xatest");
            } catch (SQLException e) {
            }
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"CREATE TABLE xatest1 " + "(id INT PRIMARY KEY, value INT)\")");
            stat1.executeUpdate("CREATE TABLE xatest1 " + "(id INT PRIMARY KEY, value INT)");
            trace("stmt2.executeUpdate(\"CREATE TABLE xatest2 " + "(id INT PRIMARY KEY, value INT)\")");
            stat2.executeUpdate("CREATE TABLE xatest2 " + "(id INT PRIMARY KEY, value INT)");
        } else {
            trace("stmt1.executeUpdate(\"CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)\")");
            stat1.executeUpdate("CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)");
            trace("stmt2.executeUpdate(\"CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)\")");
            stat2.executeUpdate("CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)");
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"INSERT INTO xatest1 " + "VALUES (1, 0)\")");
            stat1.executeUpdate("INSERT INTO xatest1 VALUES (1, 0)");
            trace("stmt2.executeUpdate(\"INSERT INTO xatest2 " + "VALUES (2, 0)\")");
            stat2.executeUpdate("INSERT INTO xatest2 " + "VALUES (2, 0)");
        } else {
            trace("stmt1.executeUpdate(\"INSERT INTO xatest " + "VALUES (1, 0)\")");
            stat1.executeUpdate("INSERT INTO xatest " + "VALUES (1, 0)");
            trace("stmt2.executeUpdate(\"INSERT INTO xatest " + "VALUES (2, 0)\")");
            stat2.executeUpdate("INSERT INTO xatest " + "VALUES (2, 0)");
        }
        Xid xid1 = null;
        Xid xid2 = null;
        if (useOneDatabase) {
            xid1 = SimpleXid.createRandom();
            xid2 = SimpleXid.createRandom();
        } else {
            xid1 = SimpleXid.createRandom();
            xid2 = xid1;
        }
        if (useOneDatabase) {
            trace("xares1.start(xid1, XAResource.TMNOFLAGS)");
            xares1.start(xid1, XAResource.TMNOFLAGS);
            trace("xares2.start(xid2, XAResource.TMJOIN)");
            xares2.start(xid2, XAResource.TMJOIN);
        } else {
            trace("xares1.start(xid1, XAResource.TMNOFLAGS)");
            xares1.start(xid1, XAResource.TMNOFLAGS);
            trace("xares2.start(xid2, XAResource.TMNOFLAGS)");
            xares2.start(xid2, XAResource.TMNOFLAGS);
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"UPDATE xatest1 " + "SET value=1 WHERE id=1\")");
            stat1.executeUpdate("UPDATE xatest1 " + "SET value=1 WHERE id=1");
            trace("stmt2.executeUpdate(\"UPDATE xatest2 " + "SET value=1 WHERE id=2\")");
            stat2.executeUpdate("UPDATE xatest2 " + "SET value=1 WHERE id=2");
        } else {
            trace("stmt1.executeUpdate(\"UPDATE xatest " + "SET value=1 WHERE id=1\")");
            stat1.executeUpdate("UPDATE xatest " + "SET value=1 WHERE id=1");
            trace("stmt2.executeUpdate(\"UPDATE xatest " + "SET value=1 WHERE id=2\")");
            stat2.executeUpdate("UPDATE xatest " + "SET value=1 WHERE id=2");
        }
        trace("xares1.end(xid1, XAResource.TMSUCCESS)");
        xares1.end(xid1, XAResource.TMSUCCESS);
        trace("xares2.end(xid2, XAResource.TMSUCCESS)");
        xares2.end(xid2, XAResource.TMSUCCESS);
        int ret1;
        int ret2;
        trace("ret1 = xares1.prepare(xid1)");
        ret1 = xares1.prepare(xid1);
        trace("xares1.prepare(xid1): " + ret1);
        trace("ret2 = xares2.prepare(xid2)");
        ret2 = xares2.prepare(xid2);
        trace("xares2.prepare(xid2): " + ret2);
        if ((ret1 != XAResource.XA_OK) && (ret1 != XAResource.XA_RDONLY)) {
            throw new IllegalStateException("xares1.prepare(xid1) must return XA_OK or XA_RDONLY");
        }
        if ((ret2 != XAResource.XA_OK) && (ret2 != XAResource.XA_RDONLY)) {
            throw new IllegalStateException("xares2.prepare(xid2) must return XA_OK or XA_RDONLY");
        }
        if (ret1 == XAResource.XA_OK) {
            trace("xares1.commit(xid1, false)");
            xares1.commit(xid1, false);
        }
        if (ret2 == XAResource.XA_OK) {
            trace("xares2.commit(xid2, false)");
            xares2.commit(xid2, false);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        JdbcUtils.closeSilently(stat1);
        JdbcUtils.closeSilently(stat2);
        JdbcUtils.closeSilently(conn1);
        JdbcUtils.closeSilently(conn2);
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 52
Project: h2database-master  File: TestXA.java View source code
private void testXA(boolean useOneDatabase) throws SQLException {
    String url1 = getURL(DB_NAME1, true);
    String url2 = getURL(DB_NAME2, true);
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;
    Connection conn1 = null;
    Connection conn2 = null;
    Statement stat1 = null;
    Statement stat2 = null;
    try {
        trace("xads1 = createXADatasource1()");
        XADataSource xaDs1 = createXADatasource(useOneDatabase, url1);
        trace("xads2 = createXADatasource2()");
        XADataSource xaDs2 = createXADatasource(useOneDatabase, url2);
        trace("xacon1 = xads1.getXAConnection()");
        xaConn1 = xaDs1.getXAConnection();
        trace("xacon2 = xads2.getXAConnection()");
        xaConn2 = xaDs2.getXAConnection();
        trace("xares1 = xacon1.getXAResource()");
        XAResource xares1 = xaConn1.getXAResource();
        trace("xares2 = xacon2.getXAResource()");
        XAResource xares2 = xaConn2.getXAResource();
        trace("xares1.recover(XAResource.TMSTARTRSCAN)");
        Xid[] xids1 = xares1.recover(XAResource.TMSTARTRSCAN);
        if ((xids1 == null) || (xids1.length == 0)) {
            trace("xares1.recover(XAResource.TMSTARTRSCAN): 0");
        } else {
            trace("xares1.recover(XAResource.TMSTARTRSCAN): " + xids1.length);
        }
        trace("xares2.recover(XAResource.TMSTARTRSCAN)");
        Xid[] xids2 = xares2.recover(XAResource.TMSTARTRSCAN);
        if ((xids2 == null) || (xids2.length == 0)) {
            trace("xares2.recover(XAResource.TMSTARTRSCAN): 0");
        } else {
            trace("xares2.recover(XAResource.TMSTARTRSCAN): " + xids2.length);
        }
        trace("con1 = xacon1.getConnection()");
        conn1 = xaConn1.getConnection();
        trace("stmt1 = con1.createStatement()");
        stat1 = conn1.createStatement();
        trace("con2 = xacon2.getConnection()");
        conn2 = xaConn2.getConnection();
        trace("stmt2 = con2.createStatement()");
        stat2 = conn2.createStatement();
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"DROP TABLE xatest1\")");
            try {
                stat1.executeUpdate("DROP TABLE xatest1");
            } catch (SQLException e) {
            }
            trace("stmt2.executeUpdate(\"DROP TABLE xatest2\")");
            try {
                stat2.executeUpdate("DROP TABLE xatest2");
            } catch (SQLException e) {
            }
        } else {
            trace("stmt1.executeUpdate(\"DROP TABLE xatest\")");
            try {
                stat1.executeUpdate("DROP TABLE xatest");
            } catch (SQLException e) {
            }
            trace("stmt2.executeUpdate(\"DROP TABLE xatest\")");
            try {
                stat2.executeUpdate("DROP TABLE xatest");
            } catch (SQLException e) {
            }
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"CREATE TABLE xatest1 " + "(id INT PRIMARY KEY, value INT)\")");
            stat1.executeUpdate("CREATE TABLE xatest1 " + "(id INT PRIMARY KEY, value INT)");
            trace("stmt2.executeUpdate(\"CREATE TABLE xatest2 " + "(id INT PRIMARY KEY, value INT)\")");
            stat2.executeUpdate("CREATE TABLE xatest2 " + "(id INT PRIMARY KEY, value INT)");
        } else {
            trace("stmt1.executeUpdate(\"CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)\")");
            stat1.executeUpdate("CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)");
            trace("stmt2.executeUpdate(\"CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)\")");
            stat2.executeUpdate("CREATE TABLE xatest " + "(id INT PRIMARY KEY, value INT)");
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"INSERT INTO xatest1 " + "VALUES (1, 0)\")");
            stat1.executeUpdate("INSERT INTO xatest1 VALUES (1, 0)");
            trace("stmt2.executeUpdate(\"INSERT INTO xatest2 " + "VALUES (2, 0)\")");
            stat2.executeUpdate("INSERT INTO xatest2 " + "VALUES (2, 0)");
        } else {
            trace("stmt1.executeUpdate(\"INSERT INTO xatest " + "VALUES (1, 0)\")");
            stat1.executeUpdate("INSERT INTO xatest " + "VALUES (1, 0)");
            trace("stmt2.executeUpdate(\"INSERT INTO xatest " + "VALUES (2, 0)\")");
            stat2.executeUpdate("INSERT INTO xatest " + "VALUES (2, 0)");
        }
        Xid xid1 = null;
        Xid xid2 = null;
        if (useOneDatabase) {
            xid1 = SimpleXid.createRandom();
            xid2 = SimpleXid.createRandom();
        } else {
            xid1 = SimpleXid.createRandom();
            xid2 = xid1;
        }
        if (useOneDatabase) {
            trace("xares1.start(xid1, XAResource.TMNOFLAGS)");
            xares1.start(xid1, XAResource.TMNOFLAGS);
            trace("xares2.start(xid2, XAResource.TMJOIN)");
            xares2.start(xid2, XAResource.TMJOIN);
        } else {
            trace("xares1.start(xid1, XAResource.TMNOFLAGS)");
            xares1.start(xid1, XAResource.TMNOFLAGS);
            trace("xares2.start(xid2, XAResource.TMNOFLAGS)");
            xares2.start(xid2, XAResource.TMNOFLAGS);
        }
        if (useOneDatabase) {
            trace("stmt1.executeUpdate(\"UPDATE xatest1 " + "SET value=1 WHERE id=1\")");
            stat1.executeUpdate("UPDATE xatest1 " + "SET value=1 WHERE id=1");
            trace("stmt2.executeUpdate(\"UPDATE xatest2 " + "SET value=1 WHERE id=2\")");
            stat2.executeUpdate("UPDATE xatest2 " + "SET value=1 WHERE id=2");
        } else {
            trace("stmt1.executeUpdate(\"UPDATE xatest " + "SET value=1 WHERE id=1\")");
            stat1.executeUpdate("UPDATE xatest " + "SET value=1 WHERE id=1");
            trace("stmt2.executeUpdate(\"UPDATE xatest " + "SET value=1 WHERE id=2\")");
            stat2.executeUpdate("UPDATE xatest " + "SET value=1 WHERE id=2");
        }
        trace("xares1.end(xid1, XAResource.TMSUCCESS)");
        xares1.end(xid1, XAResource.TMSUCCESS);
        trace("xares2.end(xid2, XAResource.TMSUCCESS)");
        xares2.end(xid2, XAResource.TMSUCCESS);
        int ret1;
        int ret2;
        trace("ret1 = xares1.prepare(xid1)");
        ret1 = xares1.prepare(xid1);
        trace("xares1.prepare(xid1): " + ret1);
        trace("ret2 = xares2.prepare(xid2)");
        ret2 = xares2.prepare(xid2);
        trace("xares2.prepare(xid2): " + ret2);
        if ((ret1 != XAResource.XA_OK) && (ret1 != XAResource.XA_RDONLY)) {
            throw new IllegalStateException("xares1.prepare(xid1) must return XA_OK or XA_RDONLY");
        }
        if ((ret2 != XAResource.XA_OK) && (ret2 != XAResource.XA_RDONLY)) {
            throw new IllegalStateException("xares2.prepare(xid2) must return XA_OK or XA_RDONLY");
        }
        if (ret1 == XAResource.XA_OK) {
            trace("xares1.commit(xid1, false)");
            xares1.commit(xid1, false);
        }
        if (ret2 == XAResource.XA_OK) {
            trace("xares2.commit(xid2, false)");
            xares2.commit(xid2, false);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        JdbcUtils.closeSilently(stat1);
        JdbcUtils.closeSilently(stat2);
        JdbcUtils.closeSilently(conn1);
        JdbcUtils.closeSilently(conn2);
        if (xaConn1 != null) {
            xaConn1.close();
        }
        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
Example 53
Project: p6spy-master  File: XADataSourceTest.java View source code
@Before
public void setUpXADataSourceTest() throws NamingException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {
    final P6TestLoadableOptions testOptions = P6TestOptions.getActiveInstance();
    jndiResources = new ArrayList<Resource>();
    poolingDSs = new ArrayList<PoolingDataSource>();
    tm = TransactionManagerServices.getTransactionManager();
    // in test DS setup
    {
        final XADataSource realInTestDs = (XADataSource) P6Util.forName(testOptions.getXaDataSource().getClass().getName()).newInstance();
        setXADSProperties(realInTestDs, testOptions.getUrl().replace(":p6spy", ""), testOptions.getUser(), testOptions.getPassword());
        jndiResources.add(new Resource("jdbc/realInTestDs", realInTestDs));
        final PoolingDataSource inTestDs = new PoolingDataSource();
        inTestDs.setClassName(P6DataSource.class.getName());
        inTestDs.setUniqueName("jdbc/inTestDs");
        inTestDs.setMaxPoolSize(10);
        inTestDs.getDriverProperties().setProperty("realDataSource", "jdbc/realInTestDs");
        inTestDs.setAllowLocalTransactions(true);
        inTestDs.init();
        jndiResources.add(new Resource("jdbc/inTestDs", inTestDs));
        poolingDSs.add(inTestDs);
    }
    // fixed DS setup
    {
        final XADataSource realFixedDs = (XADataSource) P6Util.forName("org.h2.jdbcx.JdbcDataSource").newInstance();
        setXADSProperties(realFixedDs, "jdbc:h2:mem:p6spy_realFixedDs", "sa", "sa");
        jndiResources.add(new Resource("jdbc/realFixedDs", realFixedDs));
        final PoolingDataSource fixedDs = new PoolingDataSource();
        fixedDs.setClassName(P6DataSource.class.getName());
        fixedDs.setUniqueName("jdbc/fixedDs");
        fixedDs.setMaxPoolSize(10);
        fixedDs.getDriverProperties().setProperty("realDataSource", "jdbc/realFixedDs");
        fixedDs.setAllowLocalTransactions(true);
        fixedDs.init();
        jndiResources.add(new Resource("jdbc/fixedDs", fixedDs));
        poolingDSs.add(fixedDs);
    }
    // liquibase opens it's own transaction => keep it out of ours
    try {
        P6TestUtil.setupTestData(new JndiDataSourceLookup().getDataSource("jdbc/inTestDs"));
        P6TestUtil.setupTestData(new JndiDataSourceLookup().getDataSource("jdbc/fixedDs"));
    } catch (LiquibaseException e) {
        e.printStackTrace();
    }
    try {
        tm.begin();
        // TODO move to liquibase?
        cleanData(new JndiDataSourceLookup().getDataSource("jdbc/inTestDs"));
        cleanData(new JndiDataSourceLookup().getDataSource("jdbc/fixedDs"));
        tm.commit();
    } catch (NotSupportedException e) {
        e.printStackTrace();
    } catch (SystemException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (HeuristicMixedException e) {
        e.printStackTrace();
    } catch (HeuristicRollbackException e) {
        e.printStackTrace();
    } catch (RollbackException e) {
        e.printStackTrace();
    }
}
Example 54
Project: Tomcat-master  File: DataSourceFactory.java View source code
// -------------------------------------------------- ObjectFactory Methods
/**
     * <p>Create and return a new <code>BasicDataSource</code> instance.  If no
     * instance can be created, return <code>null</code> instead.</p>
     *
     * @param obj The possibly null object containing location or
     *  reference information that can be used in creating an object
     * @param name The name of this object relative to <code>nameCtx</code>
     * @param nameCtx The context relative to which the <code>name</code>
     *  parameter is specified, or <code>null</code> if <code>name</code>
     *  is relative to the default initial context
     * @param environment The possibly null environment that is used in
     *  creating this object
     *
     * @exception Exception if an exception occurs creating the instance
     */
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
    // that specify a class name of "javax.sql.DataSource"
    if ((obj == null) || !(obj instanceof Reference)) {
        return null;
    }
    Reference ref = (Reference) obj;
    boolean XA = false;
    boolean ok = false;
    if ("javax.sql.DataSource".equals(ref.getClassName())) {
        ok = true;
    }
    if ("javax.sql.XADataSource".equals(ref.getClassName())) {
        ok = true;
        XA = true;
    }
    if (org.apache.tomcat.jdbc.pool.DataSource.class.getName().equals(ref.getClassName())) {
        ok = true;
    }
    if (!ok) {
        log.warn(ref.getClassName() + " is not a valid class name/type for this JNDI factory.");
        return null;
    }
    Properties properties = new Properties();
    for (int i = 0; i < ALL_PROPERTIES.length; i++) {
        String propertyName = ALL_PROPERTIES[i];
        RefAddr ra = ref.get(propertyName);
        if (ra != null) {
            String propertyValue = ra.getContent().toString();
            properties.setProperty(propertyName, propertyValue);
        }
    }
    return createDataSource(properties, nameCtx, XA);
}
Example 55
Project: geode-master  File: DataSourceFactory.java View source code
/**
   * This function returns the datasource with connection pooling and transaction participation
   * capabilities.
   * 
   * @param configMap a map containing configurations required for datasource.
   * @throws DataSourceCreateException
   * @return ???
   */
public static DataSource getTranxDataSource(Map configMap, List props) throws DataSourceCreateException {
    ConfiguredDataSourceProperties configs = createDataSourceProperties(configMap);
    String xaClassName = configs.getXADSClass();
    if (xaClassName == null) {
        logger.error(LocalizedMessage.create(LocalizedStrings.DataSourceFactory_DATASOURCEFACTORYGETTRANXDATASOURCEXADATASOURCE_CLASS_NAME_FOR_THE_RESOURCEMANAGER_IS_NOT_AVAILABLE));
        throw new DataSourceCreateException(LocalizedStrings.DataSourceFactory_DATASOURCEFACTORYGETTRANXDATASOURCEXADATASOURCE_CLASS_NAME_FOR_THE_RESOURCEMANAGER_IS_NOT_AVAILABLE.toLocalizedString());
    }
    if (TEST_CONNECTION_HOST != null) {
        props.add(new ConfigProperty("serverName", TEST_CONNECTION_HOST, "java.lang.String"));
    }
    if (TEST_CONNECTION_PORT != null) {
        props.add(new ConfigProperty("portNumber", TEST_CONNECTION_PORT, "int"));
    }
    try {
        Class cl = ClassPathLoader.getLatest().forName(xaClassName);
        Object Obj = cl.newInstance();
        invokeAllMethods(cl, Obj, props);
        return new GemFireTransactionDataSource((XADataSource) Obj, configs);
    } catch (Exception ex) {
        String exception = LocalizedStrings.DataSourceFactory_DATASOURCEFACTORY_GETTRANXDATASOURCE_EXCEPTION_IN_CREATING_GEMFIRETRANSACTIONDATASOURCE__EXCEPTION_STRING_0.toLocalizedString(new Object[] { ex });
        logger.error(LocalizedMessage.create(LocalizedStrings.DataSourceFactory_DATASOURCEFACTORY_GETTRANXDATASOURCE_EXCEPTION_IN_CREATING_GEMFIRETRANSACTIONDATASOURCE__EXCEPTION_STRING_0, ex), ex);
        throw new DataSourceCreateException(exception, ex);
    }
}
Example 56
Project: JBossAS51-master  File: AppServerJDBCXARecovery.java View source code
/**
     * Lookup the XADataSource in JNDI.
     */
private final void createDataSource() throws SQLException {
    try {
        if (_dataSource == null) {
            // This is where we do JBossAS specific magic. Use the JMX to fetch the name of the XADataSource class
            // and its config params so that we don't have to duplicate the information in the -ds.xml file.
            // TODO: can we make this flexible enough to handle remote app server processes, so that
            // we can run the recovery manager out of process? The server addr would need to be on a per
            // jndiname basis, as we may be doing recovery for a whole cluster. We would need AS
            // jmx classes (and the db drivers naturally) on the recovery manager classpath.
            InitialContext context = new InitialContext();
            MBeanServerConnection server = (MBeanServerConnection) context.lookup("jmx/invoker/RMIAdaptor");
            ObjectName objectName = new ObjectName("jboss.jca:name=" + _dataSourceId + ",service=ManagedConnectionFactory");
            if (_username != null && _password != null) {
                SecurityAssociation.setPrincipal(new SimplePrincipal(_username));
                SecurityAssociation.setCredential(_password);
            }
            String className = (String) server.invoke(objectName, "getManagedConnectionFactoryAttribute", new Object[] { "XADataSourceClass" }, new String[] { "java.lang.String" });
            log.debug("AppServerJDBCXARecovery datasource classname = " + className);
            if (_username != null && _password != null) {
                SecurityAssociation.setPrincipal(new SimplePrincipal(_username));
                SecurityAssociation.setCredential(_password);
            }
            String properties = (String) server.invoke(objectName, "getManagedConnectionFactoryAttribute", new Object[] { "XADataSourceProperties" }, new String[] { "java.lang.String" });
            try {
                _dataSource = getXADataSource(className, properties);
                // assume it does; we'll lazily check the first time we try to connect
                _supportsIsValidMethod = true;
            } catch (Exception e) {
                _dataSource = null;
                log.error("AppServerJDBCXARecovery.createDataSource got exception during getXADataSource call: " + e.toString(), e);
                throw new SQLException(e.toString());
            }
        }
    } catch (MBeanException mbe) {
        if (mbe.getTargetException() instanceof InstanceNotFoundException) {
            log.warn("AppServerJDBCXARecovery.createDataSource(name=" + _dataSourceId + "): InstanceNotFound. Datasource not deployed, or wrong name?");
            return;
        } else {
            log.error("AppServerJDBCXARecovery.createDataSource(name=" + _dataSourceId + ") got exception " + mbe.toString(), mbe);
        }
        throw new SQLException(mbe.toString());
    } catch (SQLException ex) {
        log.error("AppServerJDBCXARecovery.createDataSource got exception " + ex.toString(), ex);
        throw ex;
    } catch (Exception e) {
        log.error("AppServerJDBCXARecovery.createDataSource got exception " + e.toString(), e);
        throw new SQLException(e.toString());
    }
}
Example 57
Project: JBossAS_5_1_EDG-master  File: AppServerJDBCXARecovery.java View source code
/**
     * Lookup the XADataSource in JNDI.
     */
private final void createDataSource() throws SQLException {
    try {
        if (_dataSource == null) {
            // This is where we do JBossAS specific magic. Use the JMX to fetch the name of the XADataSource class
            // and its config params so that we don't have to duplicate the information in the -ds.xml file.
            // TODO: can we make this flexible enough to handle remote app server processes, so that
            // we can run the recovery manager out of process? The server addr would need to be on a per
            // jndiname basis, as we may be doing recovery for a whole cluster. We would need AS
            // jmx classes (and the db drivers naturally) on the recovery manager classpath.
            InitialContext context = new InitialContext();
            MBeanServerConnection server = (MBeanServerConnection) context.lookup("jmx/invoker/RMIAdaptor");
            ObjectName objectName = new ObjectName("jboss.jca:name=" + _dataSourceId + ",service=ManagedConnectionFactory");
            if (_username != null && _password != null) {
                SecurityAssociation.setPrincipal(new SimplePrincipal(_username));
                SecurityAssociation.setCredential(_password);
            }
            String className = (String) server.invoke(objectName, "getManagedConnectionFactoryAttribute", new Object[] { "XADataSourceClass" }, new String[] { "java.lang.String" });
            log.debug("AppServerJDBCXARecovery datasource classname = " + className);
            if (_username != null && _password != null) {
                SecurityAssociation.setPrincipal(new SimplePrincipal(_username));
                SecurityAssociation.setCredential(_password);
            }
            String properties = (String) server.invoke(objectName, "getManagedConnectionFactoryAttribute", new Object[] { "XADataSourceProperties" }, new String[] { "java.lang.String" });
            try {
                _dataSource = getXADataSource(className, properties);
                // assume it does; we'll lazily check the first time we try to connect
                _supportsIsValidMethod = true;
            } catch (Exception e) {
                _dataSource = null;
                log.error("AppServerJDBCXARecovery.createDataSource got exception during getXADataSource call: " + e.toString(), e);
                throw new SQLException(e.toString());
            }
        }
    } catch (MBeanException mbe) {
        if (mbe.getTargetException() instanceof InstanceNotFoundException) {
            log.warn("AppServerJDBCXARecovery.createDataSource(name=" + _dataSourceId + "): InstanceNotFound. Datasource not deployed, or wrong name?");
            return;
        } else {
            log.error("AppServerJDBCXARecovery.createDataSource(name=" + _dataSourceId + ") got exception " + mbe.toString(), mbe);
        }
        throw new SQLException(mbe.toString());
    } catch (SQLException ex) {
        log.error("AppServerJDBCXARecovery.createDataSource got exception " + ex.toString(), ex);
        throw ex;
    } catch (Exception e) {
        log.error("AppServerJDBCXARecovery.createDataSource got exception " + e.toString(), e);
        throw new SQLException(e.toString());
    }
}
Example 58
Project: jTDS-master  File: XaTest.java View source code
/**
     * Obtain an XADataSource.
     *
     * @return the <code>XADataSource.
     * @throws SQLException if an error condition occurs
     */
public XADataSource getDataSource() throws SQLException {
    JtdsDataSource xaDS = new JtdsDataSource();
    String user = props.getProperty(Messages.get(Driver.USER));
    String pwd = props.getProperty(Messages.get(Driver.PASSWORD));
    String host = props.getProperty(Messages.get(Driver.SERVERNAME));
    String port = props.getProperty(Messages.get(Driver.PORTNUMBER));
    String database = props.getProperty(Messages.get(Driver.DATABASENAME));
    String xaMode = props.getProperty(Messages.get(Driver.XAEMULATION));
    String tds = props.getProperty(Messages.get(Driver.TDS));
    String serverType = props.getProperty(Messages.get(Driver.SERVERTYPE));
    int portn;
    try {
        portn = Integer.parseInt(port);
    } catch (NumberFormatException e) {
        portn = 1433;
    }
    xaDS.setServerName(host);
    xaDS.setPortNumber(portn);
    xaDS.setUser(user);
    xaDS.setPassword(pwd);
    xaDS.setDatabaseName(database);
    xaDS.setXaEmulation(xaMode.equalsIgnoreCase("true"));
    xaDS.setTds(tds);
    xaDS.setServerType("2".equals(serverType) ? 2 : 1);
    return xaDS;
}
Example 59
Project: datanucleus-rdbms-master  File: ConnectionFactoryImpl.java View source code
/**
     * Method to generate the datasource used by this connection factory.
     * Searches initially for a provided DataSource then, if not found, for JNDI DataSource, and finally for the DataSource at a connection URL.
     * @param storeMgr Store Manager
     * @param connDS Factory data source object
     * @param connJNDI DataSource JNDI name(s)
     * @param resourceType Type of resource
     * @param requiredPoolingType Type of connection pool
     * @param connURL URL for connections
     * @return The DataSource
     */
private DataSource generateDataSource(StoreManager storeMgr, Object connDS, String connJNDI, String resourceType, String requiredPoolingType, String connURL) {
    DataSource dataSource = null;
    if (connDS != null) {
        if (!(connDS instanceof DataSource) && !(connDS instanceof XADataSource)) {
            throw new UnsupportedConnectionFactoryException(connDS);
        }
        dataSource = (DataSource) connDS;
    } else if (connJNDI != null) {
        String connectionFactoryName = connJNDI.trim();
        try {
            Object obj = new InitialContext().lookup(connectionFactoryName);
            if (!(obj instanceof DataSource) && !(obj instanceof XADataSource)) {
                throw new UnsupportedConnectionFactoryException(obj);
            }
            dataSource = (DataSource) obj;
        } catch (NamingException e) {
            throw new ConnectionFactoryNotFoundException(connectionFactoryName, e);
        }
    } else if (connURL != null) {
        String poolingType = requiredPoolingType;
        if (StringUtils.isWhitespace(requiredPoolingType)) {
            // Default to dbcp2-builtin when nothing specified
            poolingType = "dbcp2-builtin";
        }
        // User has requested internal database connection pooling so check the registered plugins
        try {
            // Create the ConnectionPool to be used
            ConnectionPoolFactory connPoolFactory = (ConnectionPoolFactory) storeMgr.getNucleusContext().getPluginManager().createExecutableExtension("org.datanucleus.store.rdbms.connectionpool", "name", poolingType, "class-name", null, null);
            if (connPoolFactory == null) {
                // User has specified a pool plugin that has not registered
                throw new NucleusUserException(Localiser.msg("047003", poolingType)).setFatal();
            }
            // Create the ConnectionPool and get the DataSource
            pool = connPoolFactory.createConnectionPool(storeMgr);
            dataSource = pool.getDataSource();
            if (NucleusLogger.CONNECTION.isDebugEnabled()) {
                NucleusLogger.CONNECTION.debug(Localiser.msg("047008", resourceType, poolingType));
            }
        } catch (ClassNotFoundException cnfe) {
            throw new NucleusUserException(Localiser.msg("047003", poolingType), cnfe).setFatal();
        } catch (Exception e) {
            if (e instanceof InvocationTargetException) {
                InvocationTargetException ite = (InvocationTargetException) e;
                throw new NucleusException(Localiser.msg("047004", poolingType, ite.getTargetException().getMessage()), ite.getTargetException()).setFatal();
            }
            throw new NucleusException(Localiser.msg("047004", poolingType, e.getMessage()), e).setFatal();
        }
    }
    return dataSource;
}
Example 60
Project: jetty-project-master  File: Runner.java View source code
public void usage(String error) {
    if (error != null)
        System.err.println("ERROR: " + error);
    System.err.println("Usage: java [-DDEBUG] [-Djetty.home=dir] -jar jetty-runner.jar [--help|--version] [ server opts] [[ context opts] context ...] ");
    System.err.println("Server Options:");
    System.err.println(" --version                          - display version and exit");
    System.err.println(" --log file                         - request log filename (with optional 'yyyy_mm_dd' wildcard");
    System.err.println(" --out file                         - info/warn/debug log filename (with optional 'yyyy_mm_dd' wildcard");
    System.err.println(" --port n                           - port to listen on (default 8080)");
    System.err.println(" --stop-port n                      - port to listen for stop command");
    System.err.println(" --stop-key n                       - security string for stop command (required if --stop-port is present)");
    System.err.println(" --jar file                         - a jar to be added to the classloader");
    System.err.println(" --jdbc classname properties jndiname - classname of XADataSource or driver; properties string; name to register in jndi");
    System.err.println(" --lib dir                          - a directory of jars to be added to the classloader");
    System.err.println(" --classes dir                      - a directory of classes to be added to the classloader");
    System.err.println(" --txFile                           - override properties file for Atomikos");
    System.err.println(" --stats [unsecure|realm.properties] - enable stats gathering servlet context");
    System.err.println(" --config file                      - a jetty xml config file to use instead of command line options");
    System.err.println("Context Options:");
    System.err.println(" --path /path       - context path (default /)");
    System.err.println(" context            - WAR file, web app dir or context.xml file");
    System.exit(1);
}
Example 61
Project: resin-master  File: DriverConfig.java View source code
/**
   * Sets the driver as data source.
   */
public void setDriverType(String type) throws ConfigException {
    if ("ConnectionPoolDataSource".equals(type)) {
        _driverType = TYPE_POOL;
    } else if ("XADataSource".equals(type)) {
        _driverType = TYPE_XA;
    } else if ("ManagedConnectionFactory".equals(type)) {
        _driverType = TYPE_JCA;
    } else if ("Driver".equals(type)) {
        _driverType = TYPE_DRIVER;
    } else if ("DataSource".equals(type)) {
        _driverType = TYPE_DATA_SOURCE;
    } else if (hasDriverTypeMethod(_driverClass)) {
        _init.addProgram(new PropertyStringProgram("driverType", type));
    } else {
        throw new ConfigException(L.l("'{0}' is an unknown driver type. Valid types are 'ConnectionPoolDataSource', 'XADataSource' and 'Driver'"));
    }
}
Example 62
Project: wildfly-master  File: DataSourceDefinitionInjectionSource.java View source code
public void getResourceValue(final ResolutionContext context, final ServiceBuilder<?> serviceBuilder, final DeploymentPhaseContext phaseContext, final Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final Module module = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE);
    final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
    final String poolName = uniqueName(context, jndiName);
    final ContextNames.BindInfo bindInfo = ContextNames.bindInfoForEnvEntry(context.getApplicationName(), context.getModuleName(), context.getComponentName(), !context.isCompUsesModule(), jndiName);
    final DeploymentReflectionIndex reflectionIndex = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.REFLECTION_INDEX);
    try {
        final Class<?> clazz = module.getClassLoader().loadClass(className);
        clearUnknownProperties(reflectionIndex, clazz, properties);
        populateProperties(reflectionIndex, clazz, properties);
        DsSecurityImpl dsSecurity = new DsSecurityImpl(user, password, null, false, null, null);
        if (XADataSource.class.isAssignableFrom(clazz) && transactional) {
            final DsXaPoolImpl xaPool = new DsXaPoolImpl(minPoolSize < 0 ? Defaults.MIN_POOL_SIZE : Integer.valueOf(minPoolSize), initialPoolSize < 0 ? Defaults.INITIAL_POOL_SIZE : Integer.valueOf(initialPoolSize), maxPoolSize < 1 ? Defaults.MAX_POOL_SIZE : Integer.valueOf(maxPoolSize), Defaults.PREFILL, Defaults.USE_STRICT_MIN, Defaults.FLUSH_STRATEGY, Defaults.IS_SAME_RM_OVERRIDE, Defaults.INTERLEAVING, Defaults.PAD_XID, Defaults.WRAP_XA_RESOURCE, Defaults.NO_TX_SEPARATE_POOL, Boolean.FALSE, null, Defaults.FAIR, null);
            final ModifiableXaDataSource dataSource = new ModifiableXaDataSource(transactionIsolation(), null, dsSecurity, null, null, null, null, null, null, poolName, true, jndiName, false, false, Defaults.CONNECTABLE, Defaults.TRACKING, Defaults.MCP, Defaults.ENLISTMENT_TRACE, properties, className, null, null, xaPool, null);
            final XaDataSourceService xds = new XaDataSourceService(bindInfo.getBinderServiceName().getCanonicalName(), bindInfo, module.getClassLoader());
            xds.getDataSourceConfigInjector().inject(dataSource);
            startDataSource(xds, bindInfo, eeModuleDescription, context, phaseContext.getServiceTarget(), serviceBuilder, injector);
        } else {
            final DsPoolImpl commonPool = new DsPoolImpl(minPoolSize < 0 ? Defaults.MIN_POOL_SIZE : Integer.valueOf(minPoolSize), initialPoolSize < 0 ? Defaults.INITIAL_POOL_SIZE : Integer.valueOf(initialPoolSize), maxPoolSize < 1 ? Defaults.MAX_POOL_SIZE : Integer.valueOf(maxPoolSize), Defaults.PREFILL, Defaults.USE_STRICT_MIN, Defaults.FLUSH_STRATEGY, Boolean.FALSE, null, Defaults.FAIR, null);
            final ModifiableDataSource dataSource = new ModifiableDataSource(url, null, className, null, transactionIsolation(), properties, null, dsSecurity, null, null, null, null, null, false, poolName, true, jndiName, Defaults.SPY, Defaults.USE_CCM, transactional, Defaults.CONNECTABLE, Defaults.TRACKING, Defaults.MCP, Defaults.ENLISTMENT_TRACE, commonPool);
            final LocalDataSourceService ds = new LocalDataSourceService(bindInfo.getBinderServiceName().getCanonicalName(), bindInfo, module.getClassLoader());
            ds.getDataSourceConfigInjector().inject(dataSource);
            startDataSource(ds, bindInfo, eeModuleDescription, context, phaseContext.getServiceTarget(), serviceBuilder, injector);
        }
    } catch (Exception e) {
        throw new DeploymentUnitProcessingException(e);
    }
}
Example 63
Project: mirage-master  File: XADataSourceConnectionProvider.java View source code
public void setDataSource(XADataSource xaDataSource) {
    this.xaDataSource = xaDataSource;
}
Example 64
Project: infinispan-master  File: DataSourceResolver.java View source code
@Override
public XADataSource getDataSource(String url) {
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL(String.format("jdbc:%s;DB_CLOSE_DELAY=-1", url));
    dataSource.setUser("sa");
    dataSource.setPassword("");
    return dataSource;
}
Example 65
Project: reactive-audit-master  File: XADataSourceAudit.java View source code
@Before("call(* javax.sql.XADataSource.getXAConnection(..))")
public void getXAConnection(JoinPoint thisJoinPoint) {
    latency(HIGH, thisJoinPoint);
}
Example 66
Project: metrics-sql-master  File: XADataSourceProxyHandler.java View source code
@Override
protected Object invoke(MethodInvocation<XADataSource> methodInvocation) throws Throwable {
    final String methodName = methodInvocation.getMethodName();
    Object result;
    if (methodName.equals("getXAConnection")) {
        result = getXAConnection(methodInvocation);
    } else {
        result = methodInvocation.proceed();
    }
    return result;
}
Example 67
Project: seasar2-master  File: DBXAResourceImplTest.java View source code
protected void setUp() throws Exception {
    include(PATH);
    xads2_ = (XADataSource) getComponent("xads");
    xacon_ = xads2_.getXAConnection();
    con_ = xacon_.getConnection();
    xares_ = new DBXAResourceImpl(con_);
}
Example 68
Project: geronimo-master  File: XATransactionTester.java View source code
/*
     * @todo get something that loads this from a file
     */
private XADataSource getDataSource(String[] args) throws Exception {
    //        return ds;
    return null;
}
Example 69
Project: orbisgis-master  File: DataSourceFactoryImpl.java View source code
@Override
public XADataSource createXADataSource(Properties properties) throws SQLException {
    throw new SQLFeatureNotSupportedException();
}
Example 70
Project: pg-inet-maven-master  File: PostgreSQLDataSourceFactory.java View source code
public XADataSource createXADataSource(Properties prprts) throws SQLException {
    PGXADataSource ds = new PGXADataSource();
    setBaseDSProperties(ds, prprts);
    return new DelegatingXADataSource(ds, context);
}
Example 71
Project: solarnetwork-external-master  File: DerbyDataSourceFactory.java View source code
@Override
public XADataSource createXADataSource(Properties props) throws SQLException {
    EmbeddedXADataSource ds = new EmbeddedXADataSource();
    configureDataSourceProperties(ds, props);
    return ds;
}
Example 72
Project: org.openscada.external-master  File: DataSourceFactoryImpl.java View source code
@Override
public XADataSource createXADataSource(final Properties paramProperties) throws SQLException {
    final PGXADataSource dataSource = new PGXADataSource();
    setProperties(dataSource, paramProperties, this.properties);
    return dataSource;
}
Example 73
Project: CommonDao-master  File: GenerationCodeJDBC.java View source code
/**
	 * set xa datasource
	 * @param dataSource the XAdataSource to set
	 * @throws SQLException exception
	 */
public void setXADataSource(XADataSource dataSource) throws SQLException {
    this.connection = dataSource.getXAConnection().getConnection();
}