Java Code Examples for javax.sql.XADataSource

The following examples show how to use javax.sql.XADataSource. These examples are extracted from open source projects. 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 Project: shardingsphere   Source File: XAConnectionFactory.java    License: 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 2
Source Project: FHIR   Source File: FHIRProxyXADataSource.java    License: 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 3
Source Project: FHIR   Source File: FHIRProxyXADataSourceTest.java    License: 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 4
Source Project: FHIR   Source File: FHIRProxyXADataSourceTest.java    License: 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 5
Source Project: gemfirexd-oss   Source File: J2EEDataSourceTest.java    License: 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 6
/**
 * 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 7
Source Project: shardingsphere   Source File: DataSourceSwapper.java    License: 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 8
@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 9
@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 10
Source Project: gemfirexd-oss   Source File: J2EEDataSourceTest.java    License: 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 11
Source Project: teiid-spring-boot   Source File: TeiidServer.java    License: 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 12
Source Project: gemfirexd-oss   Source File: J2EEDataSourceTest.java    License: 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 13
Source Project: morf   Source File: MySql.java    License: 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 14
Source Project: gemfirexd-oss   Source File: XADataSourceConnector.java    License: 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 15
Source Project: gemfirexd-oss   Source File: XADataSourceConnector.java    License: 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 16
Source Project: gemfirexd-oss   Source File: J2EEDataSourceTest.java    License: 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 17
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 18
Source Project: gemfirexd-oss   Source File: XADSAuthenticationTest.java    License: 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 19
Source Project: gemfirexd-oss   Source File: XADSAuthenticationTest.java    License: 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 20
Source Project: micro-integrator   Source File: XADataSourceInfo.java    License: Apache License 2.0 5 votes vote down vote up
private void initXA() throws DataServiceFault {
	try {
		this.xaDataSource = (XADataSource) Class.forName(this.getClassName()).newInstance();
		this.assignProps(this.getXADataSource(), this.getProperties());
	} catch (Exception e) {
		throw new DataServiceFault(e,
				"Cannot create XADataSource instance using the class: "
						+ this.getClassName());
	}
}
 
Example 21
Source Project: gemfirexd-oss   Source File: J2EEDataSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check that traceFile connection attribute functions correctly.
 * tracefile was tested in checkDriver, but not for DataSources.
 * tracefile= was used in datasourcepermissions_net, but that's 
 * incorrect syntax. Note that we're not checking the contents of
 * the tracefile.
 *
 * Note also that this test cannot run against a remote server.
 *  
 * @throws SQLException
 */
public void testClientTraceFileDSConnectionAttribute() throws SQLException
{
    if (usingEmbedded())
        return;

    String traceFile;

    // with ConnectionPoolDataSource
    ConnectionPoolDataSource cpds = J2EEDataSource.getConnectionPoolDataSource();

    traceFile = "trace3.out";
    JDBCDataSource.setBeanProperty(cpds, "connectionAttributes",
    		"traceFile="+traceFile);
    // DERBY-2468 - trace3.out does not get created
    ((ClientConnectionPoolDataSource) cpds).getConnection();
    JDBCDataSource.clearStringBeanProperty(cpds, "connectionAttributes");

    traceFile = "trace4.out";
    JDBCDataSource.setBeanProperty(cpds, "traceFile", traceFile);
    ((ClientConnectionPoolDataSource) cpds).getConnection();
    cpds = null;

    // now with XADataSource
    XADataSource xads = J2EEDataSource.getXADataSource();

    traceFile = "trace5.out";
    JDBCDataSource.setBeanProperty(xads, "connectionAttributes",
    		"traceFile="+traceFile);
    ((ClientXADataSource) xads).getConnection();
    // DERBY-2468 - trace5.out does not get created
    JDBCDataSource.clearStringBeanProperty(xads, "connectionAttributes");

    traceFile = "trace6.out";
    JDBCDataSource.setBeanProperty(xads, "traceFile", traceFile);
    ((ClientXADataSource) xads).getConnection();

    assertTraceFilesExist();
}
 
Example 22
Source Project: FHIR   Source File: FHIRProxyXADataSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDerby_2() throws Exception {
    FHIRRequestContext.set(new FHIRRequestContext("tenant1", "derby_2"));
    
    FHIRProxyXADataSource proxyDS = new FHIRProxyXADataSource();
    XADataSource xaDS = proxyDS.getDelegate();
    assertNotNull(xaDS);
    assertTrue(xaDS instanceof EmbeddedXADataSource);
    EmbeddedXADataSource derbyDS = (EmbeddedXADataSource) xaDS;
    assertEquals("myDerbyDatabase2", derbyDS.getDatabaseName());
    assertEquals("create", derbyDS.getCreateDatabase());
}
 
Example 23
Source Project: gemfirexd-oss   Source File: J2EEDataSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
public void timeoutTestDerby1144XADS() throws SQLException {
   
    XADataSource xds = J2EEDataSource.getXADataSource();
    // Test xa connection isolation
    XAConnection xpc1 = xds.getXAConnection();        
    assertPooledConnIso("XAConnection", xpc1);                 
    xpc1.close();
}
 
Example 24
Source Project: FHIR   Source File: FHIRProxyXADataSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDB2_1() throws Exception {
    FHIRRequestContext.set(new FHIRRequestContext("tenant1", "db2_1"));
    
    FHIRProxyXADataSource proxyDS = new FHIRProxyXADataSource();
    XADataSource xaDS= proxyDS.getDelegate();
    assertNotNull(xaDS);
    assertTrue(xaDS instanceof DB2XADataSource);
    DB2XADataSource derbyDS = (DB2XADataSource) xaDS;
    assertEquals("MYDB", derbyDS.getDatabaseName());
    assertEquals("mydbserver", derbyDS.getServerName());
    assertEquals(50000, derbyDS.getPortNumber());
}
 
Example 25
Source Project: FHIR   Source File: FHIRProxyXADataSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDB2_2() throws Exception {
    FHIRRequestContext.set(new FHIRRequestContext("tenant1", "db2_2"));
    
    FHIRProxyXADataSource proxyDS = new FHIRProxyXADataSource();
    XADataSource xaDS= proxyDS.getDelegate();
    assertNotNull(xaDS);
    assertTrue(xaDS instanceof DB2XADataSource);
    DB2XADataSource derbyDS = (DB2XADataSource) xaDS;
    assertEquals("FHIRDB", derbyDS.getDatabaseName());
    assertEquals("localhost", derbyDS.getServerName());
    assertEquals(50001, derbyDS.getPortNumber());
    assertEquals("MyDB2DataSource", derbyDS.getDataSourceName());
    assertEquals("My DB2 DataSource Description", derbyDS.getDescription());
    assertEquals("FHIR1", derbyDS.getCurrentSchema());
    assertEquals("db2inst1", derbyDS.getUser());
    assertEquals(true, derbyDS.getSslConnection());
    assertEquals("mytruststore", derbyDS.getSslTrustStoreLocation());
    assertEquals("change-password", derbyDS.getSslTrustStorePassword());
    assertEquals("mysslcert", derbyDS.getSslCertLocation());
    assertEquals(1000, derbyDS.getLoginTimeout());
    assertEquals(1001, derbyDS.getCommandTimeout());
    assertEquals(1002, derbyDS.getMemberConnectTimeout());
    assertEquals(1003, derbyDS.getConnectionTimeout());
    assertEquals(1004, derbyDS.getBlockingReadConnectionTimeout());
    assertEquals("GMT", derbyDS.getSessionTimeZone());
}
 
Example 26
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());
}
 
Example 27
Source Project: gemfirexd-oss   Source File: J2EEDataSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test that connections retrieved from {@code XADataSource} that are not
 * part of a global XA transaction, behave as expected when {@code close()}
 * is called and the transaction is active.
 */
public void testCloseActiveConnection_XA_local() throws SQLException {
    XADataSource ds = J2EEDataSource.getXADataSource();
    XAConnection xa = ds.getXAConnection();
    testCloseActiveConnection(xa.getConnection(), true, false);
    Connection c = xa.getConnection();
    c.setAutoCommit(false);
    testCloseActiveConnection(c, false, false);
}
 
Example 28
Source Project: quarkus   Source File: AgroalProcessor.java    License: 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 29
Source Project: teiid-spring-boot   Source File: XADataSourceBuilder.java    License: 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 30
Source Project: AsuraFramework   Source File: JNDIConnectionProvider.java    License: Apache License 2.0 5 votes vote down vote up
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) {}
        }
    }
}