javax.sql.XADataSource Java Examples

The following examples show how to use javax.sql.XADataSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FHIRProxyXADataSourceTest.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@Test
public void testDerby_3() throws Exception {
    FHIRRequestContext.set(new FHIRRequestContext("tenant1", "derby_3"));
    
    FHIRProxyXADataSource proxyDS = new FHIRProxyXADataSource();
    XADataSource xaDS = proxyDS.getDelegate();
    assertNotNull(xaDS);
    assertTrue(xaDS instanceof EmbeddedXADataSource);
    EmbeddedXADataSource derbyDS = (EmbeddedXADataSource) xaDS;
    assertEquals("myDerbyDatabase3", derbyDS.getDatabaseName());
    assertEquals("create", derbyDS.getCreateDatabase());
    assertEquals("dbuser", derbyDS.getUser());
    assertEquals("change-password", derbyDS.getPassword());
    assertEquals("myDataSource", derbyDS.getDataSourceName());
    assertEquals("shutdown", derbyDS.getShutdownDatabase());
    assertEquals(1000, derbyDS.getLoginTimeout());
    assertEquals("DataSource description", derbyDS.getDescription());
    assertEquals("prop1=value1", derbyDS.getConnectionAttributes());
    assertEquals(false, derbyDS.getAttributesAsPassword());
}
 
Example #2
Source File: TeiidServer.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
String getDriverName(Object source) {
    String driverName = null;
    if (source instanceof org.apache.tomcat.jdbc.pool.DataSource) {
        driverName = ((org.apache.tomcat.jdbc.pool.DataSource) source).getDriverClassName();
    } else if (source instanceof HikariDataSource) {
        driverName = ((HikariDataSource) source).getDriverClassName();
    } else {
        if (source instanceof DataSource) {
            try {
                XADataSource xads = ((DataSource) source).unwrap(XADataSource.class);
                if (xads != null) {
                    if (xads instanceof XADataSourceBuilder) {
                        driverName = ((XADataSourceBuilder) xads).dataSourceClassName();
                    } else {
                        driverName = xads.getClass().getName();
                    }
                }
            } catch (SQLException e1) {
                // ignore.
            }
        }
    }
    return driverName;
}
 
Example #3
Source File: PooledXADataSourceWrapper.java    From narayana-spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Wrap the provided data source and initialize the connection pool if its initial size is higher than 0.
 *
 * @param xaDataSource data source that needs to be wrapped
 * @return wrapped data source
 * @throws Exception if data source copy or connection pool initialization has failed.
 */
@Override
protected DataSource wrapDataSourceInternal(XADataSource xaDataSource) throws Exception {
    BasicManagedDataSource basicManagedDataSource = new BasicManagedDataSource();
    // Managed data source does't have a factory. Therefore we need to create an unmanaged data source and then copy
    // it's configuration to the managed one.
    BasicDataSource basicDataSource = getBasicDataSource();
    copyFields(basicDataSource, basicManagedDataSource);
    basicManagedDataSource.setTransactionManager(this.transactionManager);
    basicManagedDataSource.setXaDataSourceInstance(xaDataSource);

    // Initialize the connections pool
    int initialSize = Integer.valueOf(this.properties.getDbcp().getOrDefault("initialSize", "0"));
    if (initialSize > 0) {
        basicManagedDataSource.setInitialSize(initialSize);
        basicManagedDataSource.getLogWriter(); // A trick to trigger pool initialization
    }

    return basicManagedDataSource;
}
 
Example #4
Source File: J2EEDataSourceTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testSetSchemaInXAConnection() throws SQLException {
    // tests that set schema works correctly in an XA connection.

    XADataSource dsx = J2EEDataSource.getXADataSource();
    XAConnection xac3 = dsx.getXAConnection();
    Connection conn3 = xac3.getConnection();
    Statement st3 = conn3.createStatement();
    st3.execute("SET SCHEMA SCHEMA_Patricio");
    st3.close();

    PreparedStatement ps3 = 
        conn3.prepareStatement("INSERT INTO Patricio VALUES (?, ?)");
    ps3.setString(1, "Patricio");
    ps3.setInt(2, 3);
    ps3.executeUpdate();

    assertEquals(1, ps3.getUpdateCount());
    ps3.close();
    conn3.close();
    xac3.close();
}
 
Example #5
Source File: XADSAuthenticationTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
protected void assertConnectionWOUPFail(
    String expectedSqlState, String dbName, String user, String password)
throws SQLException
{
    XADataSource xads = J2EEDataSource.getXADataSource();
    JDBCDataSource.setBeanProperty(xads, "databaseName", dbName);
    JDBCDataSource.setBeanProperty(xads, "user", user);
    JDBCDataSource.setBeanProperty(xads, "password", password);
    try {
        xads.getXAConnection();
        fail("Connection should've been refused/failed");
    }
    catch (SQLException e) {
        assertSQLState(expectedSqlState, e);
    }
}
 
Example #6
Source File: PoolXADSCreateShutdownDBTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
protected void assertSetConOK(Object ds, String expectedSQLState, 
    String dbName, String connAttrValue, String setter, String setValue) 
throws SQLException {
    JDBCDataSource.setBeanProperty(ds, "databaseName", dbName);
    JDBCDataSource.setBeanProperty(
        ds, "ConnectionAttributes", connAttrValue);
    JDBCDataSource.setBeanProperty(ds, setter, setValue);
    // check that the db exists; execute an unnecessary, but harmless, stmt
    try {
        
        if (ds instanceof javax.sql.ConnectionPoolDataSource)
            ((ConnectionPoolDataSource)ds).getPooledConnection();
        else
            ((XADataSource)ds).getXAConnection();
        fail("expected an sqlexception " + expectedSQLState);
    } catch (SQLException se) {
        assertSQLState(expectedSQLState, se);
    }
    JDBCDataSource.clearStringBeanProperty(ds, "ConnectionAttributes");
    JDBCDataSource.clearStringBeanProperty(ds, setter);
}
 
Example #7
Source File: J2EEDataSourceTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Test that connections retrieved from {@code XADataSource} that are part
 * of a global XA transaction, behave as expected when {@code close()} is
 * called and the transaction is active.
 */
public void testCloseActiveConnection_XA_global()
    throws SQLException, XAException
{
    XADataSource ds = J2EEDataSource.getXADataSource();
    XAConnection xa = ds.getXAConnection();
    XAResource xar = xa.getXAResource();
    Xid xid = new cdsXid(1, (byte) 2, (byte) 3);
    xar.start(xid, XAResource.TMNOFLAGS);
    // auto-commit is always off in XA transactions, so we expect
    // getAutoCommit() to return false without having set it explicitly
    testCloseActiveConnection(xa.getConnection(), false, true);
    Connection c = xa.getConnection();
    c.setAutoCommit(false);
    testCloseActiveConnection(c, false, true);
    xar.end(xid, XAResource.TMSUCCESS);
}
 
Example #8
Source File: DataSourceSwapper.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
private XADataSource createXADataSource() {
    XADataSource result = null;
    List<ShardingSphereException> exceptions = new LinkedList<>();
    for (String each : xaDataSourceDefinition.getXADriverClassName()) {
        try {
            result = loadXADataSource(each);
        } catch (final ShardingSphereException ex) {
            exceptions.add(ex);
        }
    }
    if (null == result && !exceptions.isEmpty()) {
        if (exceptions.size() > 1) {
            throw new ShardingSphereException("Failed to create [%s] XA DataSource", xaDataSourceDefinition);
        } else {
            throw exceptions.iterator().next();
        }
    }
    return result;
}
 
Example #9
Source File: J2EEDataSourceTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private static void dsConnectionRequests(
    String[] expectedValues, XADataSource ds) {
    try {
        ds.getXAConnection();
        if (!expectedValues[0].equals("OK"))
            fail (" expected connection to fail, but was OK");
    } catch (SQLException sqle) {
        assertSQLState(expectedValues[0], sqle);
    }

    dsConnectionRequest(expectedValues[1], ds, null, null);
    dsConnectionRequest(expectedValues[2], ds, "fred", null);
    dsConnectionRequest(expectedValues[3], ds, "fred", "wilma");
    dsConnectionRequest(expectedValues[4], ds, null, "wilma");
    dsConnectionRequest(
        expectedValues[5], ds, null, "databaseName=" + dbName);
    dsConnectionRequest(
        expectedValues[6], ds, "fred", "databaseName=" + dbName);
    dsConnectionRequest(expectedValues[7], 
        ds, "fred", "databaseName=" + dbName + ";password=wilma");
    dsConnectionRequest(expectedValues[8], 
        ds, "fred", "databaseName=" + dbName + ";password=betty");
}
 
Example #10
Source File: J2EEDataSourceTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * check whether commit without statement will flow by checking its transaction id
 * on client. This test is run only for client where commits without an
 * active transactions will not flow to the server.
 * DERBY-4653
 * 
 * @throws SQLException
 **/
public void testConnectionFlowCommit()
        throws SQLException {
    ConnectionPoolDataSource ds = J2EEDataSource.getConnectionPoolDataSource();

    PooledConnection pc = ds.getPooledConnection();
    Connection conn = pc.getConnection();

    testConnectionFlowCommitWork(conn, 1);
    conn.close();
    
    //Test for XADataSource
    XADataSource xs = J2EEDataSource.getXADataSource();
    XAConnection xc = xs.getXAConnection();
    conn = xc.getConnection();
    testConnectionFlowCommitWork(conn, 1);
    conn.close();
    
    //Test for DataSource
    DataSource jds = JDBCDataSource.getDataSource();
    conn = jds.getConnection();
    testConnectionFlowCommitWork(conn, 1);
    conn.close();       
}
 
Example #11
Source File: FHIRProxyXADataSourceTest.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@Test
public void testDerby_4() throws Exception {
    FHIRRequestContext.set(new FHIRRequestContext("tenant2", "derby_4"));
    
    FHIRProxyXADataSource proxyDS = new FHIRProxyXADataSource();
    XADataSource xaDS = proxyDS.getDelegate();
    assertNotNull(xaDS);
    assertTrue(xaDS instanceof ClientXADataSource);
    ClientXADataSource derbyDS = (ClientXADataSource) xaDS;
    assertEquals("myDerbyDatabase4", derbyDS.getDatabaseName());
    assertEquals("create", derbyDS.getCreateDatabase());
    assertEquals("dbuser", derbyDS.getUser());
    assertEquals("change-password", derbyDS.getPassword());
    assertEquals("x.x.x.x", derbyDS.getServerName());
    assertEquals(1527, derbyDS.getPortNumber());
}
 
Example #12
Source File: MySql.java    From morf with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a MySQL XA data source. Note that this method may fail at
 * run-time if {@code MysqlXADataSource} is not available on the classpath.
 *
 * @throws IllegalStateException If the data source cannot be created.
 *
 * @see org.alfasoftware.morf.jdbc.DatabaseType#getXADataSource(java.lang.String,
 *      java.lang.String, java.lang.String)
 */
@Override
public XADataSource getXADataSource(String jdbcUrl, String username, String password) {
  try {
    log.info("Initialising MySQL XA data source...");
    XADataSource dataSource = (XADataSource) Class.forName("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource").newInstance();
    dataSource.getClass().getMethod("setURL", String.class).invoke(dataSource, jdbcUrl);
    dataSource.getClass().getMethod("setUser", String.class).invoke(dataSource, username);
    dataSource.getClass().getMethod("setPassword", String.class).invoke(dataSource, password);
    //see http://www.atomikos.com/Documentation/KnownProblems#MySQL_XA_bug
    //did not have to set com.atomikos.icatch.serial_jta_transactions=false
    dataSource.getClass().getMethod("setPinGlobalTxToPhysicalConnection", boolean.class).invoke(dataSource, true);
    return dataSource;
  } catch (Exception e) {
    throw new IllegalStateException("Failed to create Oracle XA data source", e);
  }
}
 
Example #13
Source File: XADataSourceConnector.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public Connection openConnection(String databaseName, String user, String password)
        throws SQLException {
    JDBCDataSource.setBeanProperty(ds, "databaseName", databaseName);
    try {
        return ds.getXAConnection(user, password).getConnection();
    } catch (SQLException e) {
        // If there is a database not found exception
        // then retry the connection request with
        // a new DataSource with the createDatabase property set.
        if (!"XJ004".equals(e.getSQLState()))
            throw e;
        XADataSource tmpDs = singleUseDS("createDatabase", "create");
        JDBCDataSource.setBeanProperty(tmpDs, "databaseName", databaseName);
        return tmpDs.getXAConnection(user, password).getConnection(); 
   }
}
 
Example #14
Source File: XADSAuthenticationTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
protected void assertShutdownWOUPOK(
    String dbName, String user, String password)
throws SQLException {
    XADataSource xads = J2EEDataSource.getXADataSource();
    JDBCDataSource.setBeanProperty(xads, "databaseName", dbName);
    JDBCDataSource.setBeanProperty(
            xads, "shutdownDatabase", "shutdown");
    JDBCDataSource.setBeanProperty(xads, "user", user);
    JDBCDataSource.setBeanProperty(xads, "password", password);
    try {
        xads.getXAConnection();
        fail ("expected a failed shutdown connection");
    } catch (SQLException e) {
        // expect 08006 on successful shutdown
        assertSQLState("08006", e);
    }
}
 
Example #15
Source File: XADataSourceConnector.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public Connection openConnection(String databaseName) throws SQLException {
    JDBCDataSource.setBeanProperty(ds, "databaseName", databaseName);
    try {
        return ds.getXAConnection().getConnection();
    } catch (SQLException e) {
        // Expected state for database not found.
        // For the client the generic 08004 is returned,
        // will just retry on that.
        String expectedState = 
            config.getJDBCClient().isEmbedded() ? "XJ004" : "08004";

        // If there is a database not found exception
        // then retry the connection request with
        // a new DataSource with the createDtabase property set.
        if (!expectedState.equals(e.getSQLState()))
            throw e;
        XADataSource tmpDs = singleUseDS("createDatabase", "create");
        JDBCDataSource.setBeanProperty(tmpDs, "databaseName", databaseName);
        return tmpDs.getXAConnection().getConnection();
   }
}
 
Example #16
Source File: FHIRProxyXADataSource.java    From FHIR with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns a list of all the cached XADataSource instances held by this proxy datasource.
 */
public List<XADataSource> getCachedDataSources() {
    log.entering(this.getClass().getName(), "getCachedDataSources");
    try {
        List<XADataSource> result = new ArrayList<>();
        log.fine("Building list of cached DataSources...");
        for (Map.Entry<String, Map<String, DataSourceCacheEntry>> tenantEntry : datasourceCache.entrySet()) {
            log.fine("Tenant id: " + tenantEntry.getKey());
            for (Map.Entry<String, DataSourceCacheEntry> dsEntry : tenantEntry.getValue().entrySet()) {

                log.fine("   XADataSource for dsId: " + dsEntry.getKey());
                result.add(dsEntry.getValue().getDataSource());
            }
        }

        log.fine("Returning XADataSource list of size: '" + result.size() + "'");

        return result;
    } finally {
        log.exiting(this.getClass().getName(), "getCachedDataSources");
    }
}
 
Example #17
Source File: NarayanaDataSourceTests.java    From narayana-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetConnectionAndCommit() throws SQLException {
    Connection mockConnection = mock(Connection.class);
    XAConnection mockXaConnection = mock(XAConnection.class);
    given(mockXaConnection.getConnection()).willReturn(mockConnection);
    given(this.mockXaDataSource.getXAConnection()).willReturn(mockXaConnection);

    // TODO properties not used
    Properties properties = new Properties();
    properties.put(TransactionalDriver.XADataSource, this.mockXaDataSource);

    Connection connection = this.dataSourceBean.getConnection();
    assertThat(connection).isInstanceOf(ConnectionImple.class);

    connection.commit();

    verify(this.mockXaDataSource, times(1)).getXAConnection();
    verify(mockXaConnection, times(1)).getConnection();
    verify(mockConnection, times(1)).commit();
}
 
Example #18
Source File: NarayanaDataSourceTests.java    From narayana-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetConnectionAndCommitWithCredentials() throws SQLException {
    String username = "testUsername";
    String password = "testPassword";
    Connection mockConnection = mock(Connection.class);
    XAConnection mockXaConnection = mock(XAConnection.class);
    given(mockXaConnection.getConnection()).willReturn(mockConnection);
    given(this.mockXaDataSource.getXAConnection(username, password)).willReturn(mockXaConnection);

    // TODO properties not used
    Properties properties = new Properties();
    properties.put(TransactionalDriver.XADataSource, this.mockXaDataSource);
    properties.put(TransactionalDriver.userName, username);
    properties.put(TransactionalDriver.password, password);

    Connection connection = this.dataSourceBean.getConnection(username, password);
    assertThat(connection).isInstanceOf(ConnectionImple.class);

    connection.commit();

    verify(this.mockXaDataSource, times(1)).getXAConnection(username, password);
    verify(mockXaConnection, times(1)).getConnection();
    verify(mockConnection, times(1)).commit();
}
 
Example #19
Source File: XAConnectionFactory.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
/**
 * Create XA connection from normal connection.
 *
 * @param databaseType database type
 * @param connection normal connection
 * @param xaDataSource XA data source
 * @return XA connection
 */
public static XAConnection createXAConnection(final DatabaseType databaseType, final XADataSource xaDataSource, final Connection connection) {
    switch (databaseType.getName()) {
        case "MySQL":
            return new MySQLXAConnectionWrapper().wrap(xaDataSource, connection);
        case "MariaDB":
            return new MariaDBXAConnectionWrapper().wrap(xaDataSource, connection);
        case "PostgreSQL":
            return new PostgreSQLXAConnectionWrapper().wrap(xaDataSource, connection);
        case "H2":
            return new H2XAConnectionWrapper().wrap(xaDataSource, connection);
        case "Oracle":
            return new OracleXAConnectionWrapper().wrap(xaDataSource, connection);
        default:
            throw new UnsupportedOperationException(String.format("Cannot support database type: `%s`", databaseType));
    }
}
 
Example #20
Source File: J2EEDataSourceTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testClosedXADSConnection() throws SQLException, Exception {
    // verify that outstanding updates from a closed connection, obtained
    // from an XADataSource, are not committed, but rolled back.
    XADataSource dsx = J2EEDataSource.getXADataSource();
    XAConnection xac = dsx.getXAConnection();
    Connection c1 = xac.getConnection();
    Statement s = c1.createStatement();

    c1.setAutoCommit(false);

    // this update should be rolled back
    s.executeUpdate("insert into intTable values(2)");
    
    c1 = xac.getConnection();

    ResultSet rs = c1.createStatement().executeQuery(
       "select count(*) from intTable");
    rs.next();

    assertEquals(0, rs.getInt(1));

    rs.close();
    c1.close();
    xac.close();
    xac = null;

    PoolReset("XADataSource", dsx.getXAConnection());
}
 
Example #21
Source File: AtomikosDataSourceConfig.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
public void putProperties(AtomikosDataSourceBean atomikosDataSourceBean) {

    if (null != xaProperties) {
        xaProperties.entrySet().forEach(entry -> entry.setValue(String.valueOf(entry.getValue())));
    }
    //fix #87
    XADataSource dataSource = (XADataSource) Class.forName(getXaDataSourceClassName()).newInstance();
    FastBeanCopier.copy(xaProperties, dataSource);
    atomikosDataSourceBean.setXaDataSource(dataSource);

    atomikosDataSourceBean.setXaDataSourceClassName(getXaDataSourceClassName());
    atomikosDataSourceBean.setBorrowConnectionTimeout(getBorrowConnectionTimeout());
    if (loginTimeout != 0) {
        try {
            atomikosDataSourceBean.setLoginTimeout(getLoginTimeout());
        } catch (SQLException e) {
            log.warn(e.getMessage(), e);
        }
    }
    atomikosDataSourceBean.setMaxIdleTime(getMaxIdleTime());
    atomikosDataSourceBean.setMaxPoolSize(getMaxPoolSize());
    atomikosDataSourceBean.setMinPoolSize(getMinPoolSize());
    atomikosDataSourceBean.setDefaultIsolationLevel(getDefaultIsolationLevel());
    atomikosDataSourceBean.setMaintenanceInterval(getMaintenanceInterval());
    atomikosDataSourceBean.setReapTimeout(getReapTimeout());
    atomikosDataSourceBean.setTestQuery(getTestQuery());
    atomikosDataSourceBean.setXaProperties(getXaProperties());
    atomikosDataSourceBean.setMaxLifetime(getMaxLifetime());
}
 
Example #22
Source File: XADataSourceConnector.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Get a connection from a single use XADataSource configured
 * from the configuration but with the passed in property set.
 */
private XADataSource singleUseDS(String property, String value)
   throws SQLException {
    HashMap hm = JDBCDataSource.getDataSourceProperties(config);
    hm.put(property, value);
    XADataSource sds = J2EEDataSource.getXADataSource(config, hm);
    return sds;
}
 
Example #23
Source File: H2.java    From morf with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.alfasoftware.morf.jdbc.DatabaseType#getXADataSource(java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public XADataSource getXADataSource(String jdbcUrl, String username, String password) {
  throw new UnsupportedOperationException("H2 does not fully support XA connections. "
      + "It may cause many different problems while running integration tests with H2. "
      + "Please switch off Atomikos or change database engine. See WEB-31172 for details");
  // JdbcDataSource xaDataSource = new JdbcDataSource();
  // xaDataSource.setURL(jdbcUrl);
  // xaDataSource.setUser(username);
  // xaDataSource.setPassword(password);
  // return xaDataSource;
}
 
Example #24
Source File: Oracle.java    From morf with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an Oracle XA data source. Note that this method may fail at
 * run-time if {@code OracleXADataSource} is not available on the classpath.
 *
 * @throws IllegalStateException If the data source cannot be created.
 *
 * @see org.alfasoftware.morf.jdbc.DatabaseType#getXADataSource(java.lang.String,
 *      java.lang.String, java.lang.String)
 */
@Override
public XADataSource getXADataSource(String jdbcUrl, String username, String password) {
  try {
    log.info("Initialising Oracle XA data source...");
    XADataSource dataSource = (XADataSource) Class.forName("oracle.jdbc.xa.client.OracleXADataSource").newInstance();
    dataSource.getClass().getMethod("setURL", String.class).invoke(dataSource, jdbcUrl);
    dataSource.getClass().getMethod("setUser", String.class).invoke(dataSource, username);
    dataSource.getClass().getMethod("setPassword", String.class).invoke(dataSource, password);
    return dataSource;
  } catch (Exception e) {
    throw new IllegalStateException("Failed to create Oracle XA data source", e);
  }
}
 
Example #25
Source File: AgroalProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void validateBuildTimeConfig(AggregatedDataSourceBuildTimeConfigBuildItem aggregatedConfig) {
    DataSourceJdbcBuildTimeConfig jdbcBuildTimeConfig = aggregatedConfig.getJdbcConfig();

    String fullDataSourceName = aggregatedConfig.isDefault() ? "default datasource"
            : "datasource named '" + aggregatedConfig.getName() + "'";

    String driverName = aggregatedConfig.getResolvedDriverClass();
    Class<?> driver;
    try {
        driver = Class.forName(driverName, true, Thread.currentThread().getContextClassLoader());
    } catch (ClassNotFoundException e) {
        throw new ConfigurationException(
                "Unable to load the datasource driver " + driverName + " for the " + fullDataSourceName, e);
    }
    if (jdbcBuildTimeConfig.transactions == TransactionIntegration.XA) {
        if (!XADataSource.class.isAssignableFrom(driver)) {
            throw new ConfigurationException(
                    "Driver is not an XA dataSource, while XA has been enabled in the configuration of the "
                            + fullDataSourceName + ": either disable XA or switch the driver to an XADataSource");
        }
    } else {
        if (driver != null && !javax.sql.DataSource.class.isAssignableFrom(driver)
                && !Driver.class.isAssignableFrom(driver)) {
            if (aggregatedConfig.isDefault()) {
                throw new ConfigurationException(
                        "Driver " + driverName
                                + " is an XA datasource, but XA transactions have not been enabled on the default datasource; please either set 'quarkus.datasource.jdbc.transactions=xa' or switch to a standard non-XA JDBC driver implementation");
            } else {
                throw new ConfigurationException(
                        "Driver " + driverName
                                + " is an XA datasource, but XA transactions have not been enabled on the datasource named '"
                                + fullDataSourceName + "'; please either set 'quarkus.datasource." + fullDataSourceName
                                + ".jdbc.transactions=xa' or switch to a standard non-XA JDBC driver implementation");
            }
        }
    }
}
 
Example #26
Source File: OracleXAConnectionWrapper.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@SneakyThrows
@Override
public XAConnection wrap(final XADataSource xaDataSource, final Connection connection) {
    Connection physicalConnection = (Connection) connection.unwrap(Class.forName("oracle.jdbc.internal.OracleConnection"));
    Class clazz = Class.forName("oracle.jdbc.xa.client.OracleXAConnection");
    Constructor constructor = clazz.getConstructor(Connection.class);
    return (XAConnection) constructor.newInstance(physicalConnection);
}
 
Example #27
Source File: SqlServer.java    From morf with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a SQL Server XA data source. Note that this method may fail at
 * run-time if {@code SQLServerXADataSource} is not available on the classpath.
 *
 * @throws IllegalStateException If the data source cannot be created.
 *
 * @see org.alfasoftware.morf.jdbc.DatabaseType#getXADataSource(java.lang.String,
 *      java.lang.String, java.lang.String)
 */
@Override
public XADataSource getXADataSource(String jdbcUrl, String username, String password) {
  try {
    log.info("Initialising SQL Server XA data source...");
    XADataSource dataSource = (XADataSource) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerXADataSource").newInstance();
    dataSource.getClass().getMethod("setURL", String.class).invoke(dataSource, jdbcUrl);
    dataSource.getClass().getMethod("setUser", String.class).invoke(dataSource, username);
    dataSource.getClass().getMethod("setPassword", String.class).invoke(dataSource, password);
    return dataSource;
  } catch (Exception e) {
    throw new IllegalStateException("Failed to create SQL Server XA data source", e);
  }
}
 
Example #28
Source File: XADataSourceBuilder.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
private void bindXaProperties(Bindable<XADataSource> target) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(
            this.properties);
    ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
    aliases.addAliases("url", "jdbc-url");
    aliases.addAliases("username", "user");
    aliases.addAliases("portNumber", "port");
    aliases.addAliases("serverName", "server");
    aliases.addAliases("databaseName", "database");

    Binder binder = new Binder(source.withAliases(aliases));
    binder.bind(ConfigurationPropertyName.EMPTY, target);
}
 
Example #29
Source File: PoolXADSCreateShutdownDBTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected void assertDSConnectionFailed(
    String expectedSQLState, Object ds) throws SQLException {
    try {
        if (ds instanceof javax.sql.ConnectionPoolDataSource)
            ((ConnectionPoolDataSource)ds).getPooledConnection();
        else
            ((XADataSource)ds).getXAConnection();
        fail("expected an sqlexception " + expectedSQLState);
    } catch (SQLException sqle) {
        assertSQLState(expectedSQLState, sqle);
    }
}
 
Example #30
Source File: AbstractXADataSourceWrapper.java    From narayana-spring-boot with Apache License 2.0 5 votes vote down vote up
private XAResourceRecoveryHelper getRecoveryHelper(XADataSource dataSource) {
    if (this.properties.getRecoveryDbUser() == null && this.properties.getRecoveryDbPass() == null) {
        return new DataSourceXAResourceRecoveryHelper(dataSource);
    }
    return new DataSourceXAResourceRecoveryHelper(dataSource, this.properties.getRecoveryDbUser(),
            this.properties.getRecoveryDbPass());
}