Search in sources :

Example 1 with AgroalDataSource

use of io.agroal.api.AgroalDataSource in project hibernate-orm by hibernate.

the class AgroalConnectionProvider method configure.

@Override
@SuppressWarnings("unchecked")
public void configure(Map props) throws HibernateException {
    LOGGER.debug("Configuring Agroal");
    try {
        AgroalPropertiesReader agroalProperties = new AgroalPropertiesReader(CONFIG_PREFIX).readProperties(props);
        agroalProperties.modify().connectionPoolConfiguration(cp -> cp.connectionFactoryConfiguration(cf -> {
            copyProperty(props, AvailableSettings.DRIVER, cf::driverClassName, Function.identity());
            copyProperty(props, AvailableSettings.URL, cf::jdbcUrl, Function.identity());
            copyProperty(props, AvailableSettings.USER, cf::principal, NamePrincipal::new);
            copyProperty(props, AvailableSettings.PASS, cf::credential, SimplePassword::new);
            copyProperty(props, AvailableSettings.AUTOCOMMIT, cf::autoCommit, Boolean::valueOf);
            resolveIsolationSetting(props, cf);
            return cf;
        }));
        agroalDataSource = AgroalDataSource.from(agroalProperties);
    } catch (Exception e) {
        throw new HibernateException(e);
    }
    LOGGER.debug("Agroal Configured");
}
Also used : ConnectionProviderInitiator(org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator) Stoppable(org.hibernate.service.spi.Stoppable) Connection(java.sql.Connection) AvailableSettings(org.hibernate.cfg.AvailableSettings) Configurable(org.hibernate.service.spi.Configurable) Logger(org.jboss.logging.Logger) UnknownUnwrapTypeException(org.hibernate.service.UnknownUnwrapTypeException) AgroalPropertiesReader(io.agroal.api.configuration.supplier.AgroalPropertiesReader) NamePrincipal(io.agroal.api.security.NamePrincipal) Function(java.util.function.Function) AgroalConnectionFactoryConfigurationSupplier(io.agroal.api.configuration.supplier.AgroalConnectionFactoryConfigurationSupplier) Consumer(java.util.function.Consumer) SQLException(java.sql.SQLException) Map(java.util.Map) DataSource(javax.sql.DataSource) AgroalConnectionFactoryConfiguration(io.agroal.api.configuration.AgroalConnectionFactoryConfiguration) SimplePassword(io.agroal.api.security.SimplePassword) HibernateException(org.hibernate.HibernateException) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) AgroalDataSource(io.agroal.api.AgroalDataSource) HibernateException(org.hibernate.HibernateException) AgroalPropertiesReader(io.agroal.api.configuration.supplier.AgroalPropertiesReader) UnknownUnwrapTypeException(org.hibernate.service.UnknownUnwrapTypeException) SQLException(java.sql.SQLException) HibernateException(org.hibernate.HibernateException)

Example 2 with AgroalDataSource

use of io.agroal.api.AgroalDataSource in project indy by Commonjava.

the class ConnectionPoolProvider method init.

public void init() throws IndyLifecycleException {
    logger.info("Starting connection pool binding...");
    Properties properties = System.getProperties();
    properties.setProperty(INITIAL_CONTEXT_FACTORY, CPInitialContextFactory.class.getName());
    System.setProperties(properties);
    InitialContext ctx;
    try {
        ctx = new InitialContext();
    } catch (NamingException e) {
        throw new IndyLifecycleException("Failed to create JNDI InitialContext for binding datasources", e);
    }
    Map<String, ConnectionPoolInfo> poolConfigs = config.getPools();
    logger.info("Creating bindings for {} pools from config: {}", poolConfigs.size(), config);
    for (ConnectionPoolInfo poolInfo : poolConfigs.values()) {
        try {
            AgroalPropertiesReader propertiesReader = new AgroalPropertiesReader(ConnectionPoolConfig.DS_PROPERTY_PREFIX);
            AgroalDataSourceConfiguration config = propertiesReader.readProperties(poolInfo.getProperties()).get();
            config.setMetricsEnabled(poolInfo.isUseMetrics());
            AgroalDataSource ds = AgroalDataSource.from(config, new AgroalDataSourceLogger(poolInfo.getName()));
            if (poolInfo.isUseMetrics()) {
                registerMetrics(ds.getMetrics(), poolInfo.getName());
            }
            if (poolInfo.isUseHealthChecks()) {
                registerHealthChecks(ds, poolInfo.getName());
            }
            String jndiName = "java:/comp/env/jdbc/" + poolInfo.getName();
            logger.info("Binding datasource: {}", jndiName);
            ctx.rebind(jndiName, ds);
        } catch (NamingException e) {
            throw new IndyLifecycleException("Failed to bind datasource: " + poolInfo.getName(), e);
        } catch (SQLException e) {
            throw new IndyLifecycleException("Failed to start datasource: " + poolInfo.getName(), e);
        }
    }
}
Also used : SQLException(java.sql.SQLException) AgroalDataSourceConfiguration(io.agroal.api.configuration.AgroalDataSourceConfiguration) AgroalDataSource(io.agroal.api.AgroalDataSource) Properties(java.util.Properties) InitialContext(javax.naming.InitialContext) AgroalPropertiesReader(io.agroal.api.configuration.supplier.AgroalPropertiesReader) NamingException(javax.naming.NamingException) IndyLifecycleException(org.commonjava.indy.action.IndyLifecycleException)

Example 3 with AgroalDataSource

use of io.agroal.api.AgroalDataSource 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)

Aggregations

AgroalDataSource (io.agroal.api.AgroalDataSource)3 SQLException (java.sql.SQLException)3 AgroalPropertiesReader (io.agroal.api.configuration.supplier.AgroalPropertiesReader)2 SimplePassword (io.agroal.api.security.SimplePassword)2 DataSource (javax.sql.DataSource)2 AgroalConnectionFactoryConfiguration (io.agroal.api.configuration.AgroalConnectionFactoryConfiguration)1 AgroalDataSourceConfiguration (io.agroal.api.configuration.AgroalDataSourceConfiguration)1 AgroalConnectionFactoryConfigurationSupplier (io.agroal.api.configuration.supplier.AgroalConnectionFactoryConfigurationSupplier)1 NamePrincipal (io.agroal.api.security.NamePrincipal)1 TransactionIntegration (io.agroal.api.transaction.TransactionIntegration)1 NarayanaTransactionIntegration (io.agroal.narayana.NarayanaTransactionIntegration)1 IOException (java.io.IOException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 Connection (java.sql.Connection)1 Map (java.util.Map)1 Properties (java.util.Properties)1 Consumer (java.util.function.Consumer)1 Function (java.util.function.Function)1 InitialContext (javax.naming.InitialContext)1