Search in sources :

Example 41 with TransactionSynchronizationRegistry

use of javax.transaction.TransactionSynchronizationRegistry in project wildfly by wildfly.

the class InjectedJMSContext method getTransactionSynchronizationRegistry.

/**
 * lookup the transactionSynchronizationRegistry and cache it.
 */
private TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() {
    TransactionSynchronizationRegistry cachedTSR = transactionSynchronizationRegistry;
    if (cachedTSR == null) {
        cachedTSR = (TransactionSynchronizationRegistry) lookup(TRANSACTION_SYNCHRONIZATION_REGISTRY_LOOKUP);
        transactionSynchronizationRegistry = cachedTSR;
    }
    return cachedTSR;
}
Also used : TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry)

Example 42 with TransactionSynchronizationRegistry

use of javax.transaction.TransactionSynchronizationRegistry in project wildfly by wildfly.

the class DataSourceService method start.

@Override
public void start(StartContext context) throws StartException {
    Class<?> providerClass = driverInjector.getOptionalValue();
    if (xa) {
        if (!XADataSource.class.isAssignableFrom(providerClass)) {
            throw AgroalLogger.SERVICE_LOGGER.invalidXAConnectionProvider();
        }
    } else {
        if (providerClass != null && !DataSource.class.isAssignableFrom(providerClass) && !Driver.class.isAssignableFrom(providerClass)) {
            throw AgroalLogger.SERVICE_LOGGER.invalidConnectionProvider();
        }
    }
    dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().connectionProviderClass(providerClass);
    if (jta || xa) {
        TransactionManager transactionManager = ContextTransactionManager.getInstance();
        TransactionSynchronizationRegistry transactionSynchronizationRegistry = transactionSynchronizationRegistryInjector.getValue();
        if (transactionManager == null || transactionSynchronizationRegistry == null) {
            throw AgroalLogger.SERVICE_LOGGER.missingTransactionManager();
        }
        TransactionIntegration txIntegration = new NarayanaTransactionIntegration(transactionManager, transactionSynchronizationRegistry, jndiName, connectable);
        dataSourceConfiguration.connectionPoolConfiguration().transactionIntegration(txIntegration);
    }
    AuthenticationContext authenticationContext = authenticationContextInjector.getOptionalValue();
    if (authenticationContext != null) {
        try {
            // Probably some other thing should be used as URI. Using jndiName for consistency with the datasources subsystem (simplicity as a bonus)
            URI targetURI = new URI(jndiName);
            NameCallback nameCallback = new NameCallback("Username: ");
            PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
            CredentialCallback credentialCallback = new CredentialCallback(GSSKerberosCredential.class);
            AuthenticationConfiguration authenticationConfiguration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(targetURI, authenticationContext, -1, "jdbc", "jboss");
            AUTH_CONFIG_CLIENT.getCallbackHandler(authenticationConfiguration).handle(new Callback[] { nameCallback, passwordCallback, credentialCallback });
            // if a GSSKerberosCredential was found, add the enclosed GSSCredential and KerberosTicket to the private set in the Subject.
            if (credentialCallback.getCredential() != null) {
                GSSKerberosCredential kerberosCredential = credentialCallback.getCredential(GSSKerberosCredential.class);
                // use the GSSName to build a kerberos principal
                dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().principal(new NamePrincipal(kerberosCredential.getGssCredential().getName().toString()));
                dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().credential(kerberosCredential.getKerberosTicket());
                dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().credential(kerberosCredential.getGssCredential());
            }
            // use the name / password from the callbacks
            if (nameCallback.getName() != null) {
                dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().principal(new NamePrincipal(nameCallback.getName()));
            }
            if (passwordCallback.getPassword() != null) {
                dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().credential(new SimplePassword(new String(passwordCallback.getPassword())));
            }
        } catch (URISyntaxException | UnsupportedCallbackException | IOException | GSSException e) {
            throw AgroalLogger.SERVICE_LOGGER.invalidAuthentication(e, dataSourceName);
        }
    }
    ExceptionSupplier<CredentialSource, Exception> credentialSourceExceptionExceptionSupplier = credentialSourceSupplierInjector.getOptionalValue();
    if (credentialSourceExceptionExceptionSupplier != null) {
        try {
            String password = new String(credentialSourceExceptionExceptionSupplier.get().getCredential(PasswordCredential.class).getPassword(ClearPassword.class).getPassword());
            dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().credential(new SimplePassword(password));
        } catch (Exception e) {
            throw AgroalLogger.SERVICE_LOGGER.invalidCredentialSourceSupplier(e, dataSourceName);
        }
    }
    try {
        agroalDataSource = AgroalDataSource.from(dataSourceConfiguration, new LoggingDataSourceListener(dataSourceName));
        ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(jndiName);
        BinderService binderService = new BinderService(bindInfo.getBindName());
        binderService.getManagedObjectInjector().inject(new ImmediateManagedReferenceFactory(agroalDataSource));
        context.getChildTarget().addService(bindInfo.getBinderServiceName(), binderService).addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()).install();
        if (xa) {
            AgroalLogger.SERVICE_LOGGER.startedXADataSource(dataSourceName, jndiName);
        } else {
            AgroalLogger.SERVICE_LOGGER.startedDataSource(dataSourceName, jndiName);
        }
    } catch (SQLException e) {
        agroalDataSource = null;
        if (xa) {
            throw AgroalLogger.SERVICE_LOGGER.xaDatasourceStartException(e, dataSourceName);
        } else {
            throw AgroalLogger.SERVICE_LOGGER.datasourceStartException(e, dataSourceName);
        }
    }
}
Also used : TransactionIntegration(io.agroal.api.transaction.TransactionIntegration) NarayanaTransactionIntegration(io.agroal.narayana.NarayanaTransactionIntegration) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) SQLException(java.sql.SQLException) NamePrincipal(org.wildfly.security.auth.principal.NamePrincipal) PasswordCredential(org.wildfly.security.credential.PasswordCredential) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) GSSKerberosCredential(org.wildfly.security.credential.GSSKerberosCredential) BinderService(org.jboss.as.naming.service.BinderService) GSSException(org.ietf.jgss.GSSException) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) CredentialSource(org.wildfly.security.credential.source.CredentialSource) ContextNames(org.jboss.as.naming.deployment.ContextNames) ImmediateManagedReferenceFactory(org.jboss.as.naming.ImmediateManagedReferenceFactory) AuthenticationConfiguration(org.wildfly.security.auth.client.AuthenticationConfiguration) XADataSource(javax.sql.XADataSource) LoggingDataSourceListener(org.wildfly.extension.datasources.agroal.logging.LoggingDataSourceListener) CredentialCallback(org.wildfly.security.auth.callback.CredentialCallback) IOException(java.io.IOException) NarayanaTransactionIntegration(io.agroal.narayana.NarayanaTransactionIntegration) URISyntaxException(java.net.URISyntaxException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) SQLException(java.sql.SQLException) StartException(org.jboss.msc.service.StartException) IOException(java.io.IOException) GSSException(org.ietf.jgss.GSSException) XADataSource(javax.sql.XADataSource) DataSource(javax.sql.DataSource) AgroalDataSource(io.agroal.api.AgroalDataSource) NameCallback(javax.security.auth.callback.NameCallback) ServiceBasedNamingStore(org.jboss.as.naming.ServiceBasedNamingStore) ContextTransactionManager(org.wildfly.transaction.client.ContextTransactionManager) TransactionManager(javax.transaction.TransactionManager) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) SimplePassword(io.agroal.api.security.SimplePassword)

Example 43 with TransactionSynchronizationRegistry

use of javax.transaction.TransactionSynchronizationRegistry in project wildfly by wildfly.

the class DataSourceDefinitionInjectionSource method getResourceValue.

// --- //
@Override
public void getResourceValue(ResolutionContext context, ServiceBuilder<?> serviceBuilder, DeploymentPhaseContext phaseContext, Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException {
    AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfiguration = new AgroalConnectionFactoryConfigurationSupplier();
    try {
        Class<?> providerClass = phaseContext.getDeploymentUnit().getAttachment(MODULE).getClassLoader().loadClass(className);
        if (providerClass != null && !DataSource.class.isAssignableFrom(providerClass) && !Driver.class.isAssignableFrom(providerClass)) {
            throw AgroalLogger.SERVICE_LOGGER.invalidDeploymentConnectionProvider();
        }
        connectionFactoryConfiguration.connectionProviderClass(providerClass);
    } catch (ClassNotFoundException e) {
        throw AgroalLogger.SERVICE_LOGGER.loadClassDeploymentException(e, className);
    }
    for (Map.Entry<String, String> property : properties.entrySet()) {
        connectionFactoryConfiguration.jdbcProperty(property.getKey(), property.getValue());
    }
    if (databaseName != null && !databaseName.isEmpty()) {
        connectionFactoryConfiguration.jdbcProperty(DATABASE_NAME_PROP, databaseName);
    }
    if (description != null && !description.isEmpty()) {
        connectionFactoryConfiguration.jdbcProperty(DESCRIPTION_PROP, description);
    }
    if (serverName != null && !serverName.isEmpty()) {
        connectionFactoryConfiguration.jdbcProperty(SERVER_NAME_PROP, serverName);
    }
    if (portNumber >= 0) {
        connectionFactoryConfiguration.jdbcProperty(PORT_NUMBER_PROP, Integer.toString(portNumber));
    }
    if (loginTimeout >= 0) {
        connectionFactoryConfiguration.jdbcProperty(LOGIN_TIMEOUT_PROP, Integer.toString(loginTimeout));
    }
    if (maxStatements >= 0) {
        connectionFactoryConfiguration.jdbcProperty(MAX_STATEMENTS_PROP, Integer.toString(maxStatements));
    }
    if (url != null && !url.isEmpty()) {
        connectionFactoryConfiguration.jdbcUrl(url);
    }
    if (user != null && !user.isEmpty()) {
        connectionFactoryConfiguration.principal(new NamePrincipal(user));
    }
    if (password != null && !password.isEmpty()) {
        connectionFactoryConfiguration.credential(new SimplePassword(password));
    }
    connectionFactoryConfiguration.jdbcTransactionIsolation(AgroalConnectionFactoryConfiguration.TransactionIsolation.fromLevel(isolationLevel));
    AgroalConnectionPoolConfigurationSupplier connectionPoolConfiguration = new AgroalConnectionPoolConfigurationSupplier();
    connectionPoolConfiguration.connectionFactoryConfiguration(connectionFactoryConfiguration);
    if (initialPoolSize >= 0) {
        connectionPoolConfiguration.initialSize(initialPoolSize);
    }
    if (minPoolSize >= 0) {
        connectionPoolConfiguration.minSize(minPoolSize);
    }
    if (maxPoolSize >= 0) {
        connectionPoolConfiguration.maxSize(maxPoolSize);
    }
    if (maxIdleTime >= 0) {
        connectionPoolConfiguration.reapTimeout(Duration.ofSeconds(maxIdleTime));
    }
    AgroalDataSourceConfigurationSupplier dataSourceConfiguration = new AgroalDataSourceConfigurationSupplier();
    dataSourceConfiguration.connectionPoolConfiguration(connectionPoolConfiguration);
    ContextNames.BindInfo bindInfo = ContextNames.bindInfoForEnvEntry(context.getApplicationName(), context.getModuleName(), context.getComponentName(), !context.isCompUsesModule(), jndiName);
    ServiceName dataSourceServiceName = DATASOURCE_DEFINITION_SERVICE_PREFIX.append(bindInfo.getBinderServiceName().getCanonicalName());
    // This is the service responsible for the JNDI binding, with a dependency on the datasource service that acts as a ManagedReferenceFactory and is used as the injection source
    BinderService binderService = new BinderService(bindInfo.getBindName(), this);
    phaseContext.getServiceTarget().addService(bindInfo.getBinderServiceName(), binderService).addDependency(dataSourceServiceName, ManagedReferenceFactory.class, binderService.getManagedObjectInjector()).addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()).install();
    ServiceBuilder svcBuilder = phaseContext.getServiceTarget().addService(dataSourceServiceName);
    Supplier<TransactionSynchronizationRegistry> tsrSupplier = null;
    if (transactional) {
        CapabilityServiceSupport css = phaseContext.getDeploymentUnit().getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
        ServiceName tsrName = css.getCapabilityServiceName("org.wildfly.transactions.transaction-synchronization-registry");
        // noinspection unchecked
        tsrSupplier = (Supplier<TransactionSynchronizationRegistry>) svcBuilder.requires(tsrName);
    }
    DataSourceDefinitionService dataSourceService = new DataSourceDefinitionService(bindInfo, transactional, dataSourceConfiguration, tsrSupplier);
    svcBuilder.setInstance(dataSourceService).install();
    serviceBuilder.requires(bindInfo.getBinderServiceName());
    serviceBuilder.addDependency(dataSourceServiceName, ManagedReferenceFactory.class, injector);
}
Also used : AgroalDataSourceConfigurationSupplier(io.agroal.api.configuration.supplier.AgroalDataSourceConfigurationSupplier) NamePrincipal(io.agroal.api.security.NamePrincipal) AgroalConnectionFactoryConfigurationSupplier(io.agroal.api.configuration.supplier.AgroalConnectionFactoryConfigurationSupplier) DataSource(javax.sql.DataSource) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) CapabilityServiceSupport(org.jboss.as.controller.capability.CapabilityServiceSupport) BinderService(org.jboss.as.naming.service.BinderService) AgroalConnectionPoolConfigurationSupplier(io.agroal.api.configuration.supplier.AgroalConnectionPoolConfigurationSupplier) ServiceName(org.jboss.msc.service.ServiceName) ServiceBasedNamingStore(org.jboss.as.naming.ServiceBasedNamingStore) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) SimplePassword(io.agroal.api.security.SimplePassword) Map(java.util.Map) ContextNames(org.jboss.as.naming.deployment.ContextNames)

Example 44 with TransactionSynchronizationRegistry

use of javax.transaction.TransactionSynchronizationRegistry in project wildfly by wildfly.

the class DataSourceDefinitionService method start.

@Override
public void start(StartContext context) throws StartException {
    if (transactional) {
        TransactionManager transactionManager = ContextTransactionManager.getInstance();
        TransactionSynchronizationRegistry transactionSynchronizationRegistry = tsrSupplier != null ? tsrSupplier.get() : null;
        if (transactionManager == null || transactionSynchronizationRegistry == null) {
            throw AgroalLogger.SERVICE_LOGGER.missingTransactionManager();
        }
        NarayanaTransactionIntegration txIntegration = new NarayanaTransactionIntegration(transactionManager, transactionSynchronizationRegistry, jndiBinding, false);
        dataSourceConfiguration.connectionPoolConfiguration().transactionIntegration(txIntegration);
    }
    try {
        agroalDataSource = AgroalDataSource.from(dataSourceConfiguration, new LoggingDataSourceListener(dataSourceName));
        AgroalLogger.SERVICE_LOGGER.startedDataSource(dataSourceName, jndiBinding);
    } catch (SQLException e) {
        agroalDataSource = null;
        throw AgroalLogger.SERVICE_LOGGER.datasourceStartException(e, dataSourceName);
    }
}
Also used : SQLException(java.sql.SQLException) ContextTransactionManager(org.wildfly.transaction.client.ContextTransactionManager) TransactionManager(javax.transaction.TransactionManager) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) LoggingDataSourceListener(org.wildfly.extension.datasources.agroal.logging.LoggingDataSourceListener) NarayanaTransactionIntegration(io.agroal.narayana.NarayanaTransactionIntegration)

Example 45 with TransactionSynchronizationRegistry

use of javax.transaction.TransactionSynchronizationRegistry in project wildfly by wildfly.

the class LifecycleMethodTransactionManagementTestCase method testStatelessRequiredAsRequiresNew.

@Test
public void testStatelessRequiredAsRequiresNew() throws SystemException, NotSupportedException, NamingException {
    UserTransaction userTransaction = (UserTransaction) new InitialContext().lookup("java:jboss/UserTransaction");
    TransactionSynchronizationRegistry tsr = (TransactionSynchronizationRegistry) new InitialContext().lookup("java:jboss/TransactionSynchronizationRegistry");
    userTransaction.begin();
    StatelessRequiredLifecycleBean required = (StatelessRequiredLifecycleBean) new InitialContext().lookup("java:module/StatelessRequiredLifecycleBean");
    try {
        Object key = tsr.getTransactionKey();
        Assert.assertNotSame(key, required.getKey());
        Assert.assertEquals(Status.STATUS_ACTIVE, required.getState());
    } finally {
        userTransaction.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) InitialContext(javax.naming.InitialContext) Test(org.junit.Test)

Aggregations

TransactionSynchronizationRegistry (javax.transaction.TransactionSynchronizationRegistry)45 TransactionManager (javax.transaction.TransactionManager)20 Test (org.junit.Test)13 InitialContext (javax.naming.InitialContext)8 ContextTransactionManager (org.wildfly.transaction.client.ContextTransactionManager)8 Synchronization (javax.transaction.Synchronization)7 ServiceName (org.jboss.msc.service.ServiceName)7 NamingException (javax.naming.NamingException)6 TransactionSynchronizationRegistryImple (com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple)5 HashMap (java.util.HashMap)5 CapabilityServiceSupport (org.jboss.as.controller.capability.CapabilityServiceSupport)5 UserTransaction (javax.transaction.UserTransaction)4 ValidatorFactory (javax.validation.ValidatorFactory)4 BinderService (org.jboss.as.naming.service.BinderService)4 BeanManager (javax.enterprise.inject.spi.BeanManager)3 DataSource (javax.sql.DataSource)3 BeanManagerAfterDeploymentValidation (org.jboss.as.jpa.beanmanager.BeanManagerAfterDeploymentValidation)3 PersistenceUnitServiceImpl (org.jboss.as.jpa.service.PersistenceUnitServiceImpl)3 PhaseOnePersistenceUnitServiceImpl (org.jboss.as.jpa.service.PhaseOnePersistenceUnitServiceImpl)3 PersistenceUnitService (org.jboss.as.jpa.spi.PersistenceUnitService)3