Java Code Examples for io.agroal.api.AgroalDataSource

The following examples show how to use io.agroal.api.AgroalDataSource. 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: quarkus   Source File: NamedDataSourceConfigTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void dataSourceAssert(String dataSourceName, AgroalDataSource dataSource, String jdbcUrl, String username,
        int minSize, int maxSize)
        throws SQLException {
    AgroalConnectionPoolConfiguration configuration = null;

    try {
        configuration = dataSource.getConfiguration().connectionPoolConfiguration();
    } catch (NullPointerException e) {
        // we catch the NPE here as we have a proxy and we can't test dataSource directly
        fail("Datasource " + dataSourceName + " should not be null");
    }
    assertEquals(jdbcUrl, configuration.connectionFactoryConfiguration().jdbcUrl());
    assertEquals(username, configuration.connectionFactoryConfiguration().principal().getName());
    assertEquals(minSize, configuration.minSize());
    assertEquals(maxSize, configuration.maxSize());
    assertFalse(dataSource.getConfiguration().metricsEnabled()); // metrics not enabled by default

    try (Connection connection = dataSource.getConnection()) {
    }
}
 
Example 2
Source Project: quarkus   Source File: DevModeTestEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{dataSourceName}/{jdbcUrl}/{username}/{minSize}/{maxSize}")
public String test(@PathParam("dataSourceName") String dataSourceName, @PathParam("jdbcUrl") String jdbcUrl,
        @PathParam("username") String username,
        @PathParam("minSize") int minSize, @PathParam("maxSize") int maxSize) throws Exception {
    AgroalDataSource ds;
    if (dataSourceName.equals("default")) {
        ds = CDI.current().select(AgroalDataSource.class)
                .get();
    } else {
        ds = CDI.current().select(AgroalDataSource.class, new DataSource.DataSourceLiteral(dataSourceName))
                .get();
    }
    testDataSource(dataSourceName, ds, URLDecoder.decode(jdbcUrl, StandardCharsets.UTF_8.name()), username, minSize,
            maxSize);
    return "ok";
}
 
Example 3
Source Project: quarkus   Source File: UnknownDriverConfigTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void testDataSource(AgroalDataSource dataSource, String username, int minSize, int maxSize,
        int initialSize, Duration backgroundValidationInterval, Duration acquisitionTimeout, Duration leakDetectionInterval,
        Duration idleRemovalInterval, Duration maxLifetime, String newConnectionSql) throws SQLException {
    AgroalConnectionPoolConfiguration configuration = dataSource.getConfiguration().connectionPoolConfiguration();
    AgroalConnectionFactoryConfiguration agroalConnectionFactoryConfiguration = configuration
            .connectionFactoryConfiguration();

    assertEquals("jdbc:h2:tcp://localhost/mem:default", agroalConnectionFactoryConfiguration.jdbcUrl());
    assertEquals(username, agroalConnectionFactoryConfiguration.principal().getName());
    assertEquals(minSize, configuration.minSize());
    assertEquals(maxSize, configuration.maxSize());
    assertEquals(initialSize, configuration.initialSize());
    assertEquals(backgroundValidationInterval, configuration.validationTimeout());
    assertEquals(acquisitionTimeout, configuration.acquisitionTimeout());
    assertEquals(leakDetectionInterval, configuration.leakTimeout());
    assertEquals(idleRemovalInterval, configuration.reapTimeout());
    assertEquals(maxLifetime, configuration.maxLifetime());
    assertTrue(configuration.transactionIntegration() instanceof NarayanaTransactionIntegration);
    assertEquals(AgroalConnectionFactoryConfiguration.TransactionIsolation.SERIALIZABLE,
            agroalConnectionFactoryConfiguration.jdbcTransactionIsolation());
    assertTrue(agroalConnectionFactoryConfiguration.trackJdbcResources());
    assertTrue(dataSource.getConfiguration().metricsEnabled());
    assertEquals(newConnectionSql, agroalConnectionFactoryConfiguration.initialSql());
    try (Connection connection = dataSource.getConnection()) {
    }
}
 
Example 4
Source Project: quarkus   Source File: MultipleDataSourcesTestUtil.java    License: Apache License 2.0 6 votes vote down vote up
static void testDataSource(String dataSourceName, AgroalDataSource dataSource, String jdbcUrl, String username,
        int minSize, int maxSize)
        throws SQLException {
    AgroalConnectionPoolConfiguration configuration = null;

    try {
        configuration = dataSource.getConfiguration().connectionPoolConfiguration();
    } catch (NullPointerException e) {
        // we catch the NPE here as we have a proxy and we can't test dataSource directly
        fail("Datasource " + dataSourceName + " should not be null");
    }
    assertEquals(jdbcUrl, configuration.connectionFactoryConfiguration().jdbcUrl());
    assertEquals(username, configuration.connectionFactoryConfiguration().principal().getName());
    assertEquals(minSize, configuration.minSize());
    assertEquals(maxSize, configuration.maxSize());

    try (Connection connection = dataSource.getConnection()) {
    }
}
 
Example 5
private static void testDataSource(String dataSourceName, AgroalDataSource dataSource, String jdbcUrl, String username,
        int minSize, int maxSize)
        throws SQLException {
    AgroalConnectionPoolConfiguration configuration = null;

    try {
        configuration = dataSource.getConfiguration().connectionPoolConfiguration();
    } catch (NullPointerException e) {
        // we catch the NPE here as we have a proxy and we can't test dataSource directly
        fail("Datasource " + dataSourceName + " should not be null");
    }
    assertEquals(jdbcUrl, configuration.connectionFactoryConfiguration().jdbcUrl());
    assertEquals(username, configuration.connectionFactoryConfiguration().principal().getName());
    assertEquals(minSize, configuration.minSize());
    assertEquals(maxSize, configuration.maxSize());

    try (Connection connection = dataSource.getConnection()) {
    }
}
 
Example 6
Source Project: quarkus   Source File: LegacyDefaultDataSourceConfigTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void testDataSource(AgroalDataSource dataSource, String username, int minSize, int maxSize,
        int initialSize, Duration backgroundValidationInterval, Duration acquisitionTimeout, Duration leakDetectionInterval,
        Duration idleRemovalInterval, Duration maxLifetime, String newConnectionSql) throws SQLException {
    AgroalConnectionPoolConfiguration configuration = dataSource.getConfiguration().connectionPoolConfiguration();
    AgroalConnectionFactoryConfiguration agroalConnectionFactoryConfiguration = configuration
            .connectionFactoryConfiguration();

    assertEquals("jdbc:h2:tcp://localhost/mem:default", agroalConnectionFactoryConfiguration.jdbcUrl());
    assertEquals(username, agroalConnectionFactoryConfiguration.principal().getName());
    assertEquals(minSize, configuration.minSize());
    assertEquals(maxSize, configuration.maxSize());
    assertEquals(initialSize, configuration.initialSize());
    assertEquals(backgroundValidationInterval, configuration.validationTimeout());
    assertEquals(acquisitionTimeout, configuration.acquisitionTimeout());
    assertEquals(leakDetectionInterval, configuration.leakTimeout());
    assertEquals(idleRemovalInterval, configuration.reapTimeout());
    assertEquals(maxLifetime, configuration.maxLifetime());
    assertTrue(configuration.transactionIntegration() instanceof NarayanaTransactionIntegration);
    assertEquals(AgroalConnectionFactoryConfiguration.TransactionIsolation.SERIALIZABLE,
            agroalConnectionFactoryConfiguration.jdbcTransactionIsolation());
    assertTrue(agroalConnectionFactoryConfiguration.trackJdbcResources());
    assertTrue(dataSource.getConfiguration().metricsEnabled());
    assertEquals(newConnectionSql, agroalConnectionFactoryConfiguration.initialSql());
    try (Connection connection = dataSource.getConnection()) {
    }
}
 
Example 7
Source Project: quarkus   Source File: DefaultDataSourceConfigTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void testDataSource(AgroalDataSource dataSource, String username, int minSize, int maxSize,
        int initialSize, Duration backgroundValidationInterval, Duration acquisitionTimeout, Duration leakDetectionInterval,
        Duration idleRemovalInterval, Duration maxLifetime, String newConnectionSql) throws SQLException {
    AgroalConnectionPoolConfiguration configuration = dataSource.getConfiguration().connectionPoolConfiguration();
    AgroalConnectionFactoryConfiguration agroalConnectionFactoryConfiguration = configuration
            .connectionFactoryConfiguration();

    assertEquals("jdbc:h2:tcp://localhost/mem:default", agroalConnectionFactoryConfiguration.jdbcUrl());
    assertEquals(username, agroalConnectionFactoryConfiguration.principal().getName());
    assertEquals(minSize, configuration.minSize());
    assertEquals(maxSize, configuration.maxSize());
    assertEquals(initialSize, configuration.initialSize());
    assertEquals(backgroundValidationInterval, configuration.validationTimeout());
    assertEquals(acquisitionTimeout, configuration.acquisitionTimeout());
    assertEquals(leakDetectionInterval, configuration.leakTimeout());
    assertEquals(idleRemovalInterval, configuration.reapTimeout());
    assertEquals(maxLifetime, configuration.maxLifetime());
    assertTrue(configuration.transactionIntegration() instanceof NarayanaTransactionIntegration);
    assertEquals(AgroalConnectionFactoryConfiguration.TransactionIsolation.SERIALIZABLE,
            agroalConnectionFactoryConfiguration.jdbcTransactionIsolation());
    assertTrue(agroalConnectionFactoryConfiguration.trackJdbcResources());
    assertTrue(dataSource.getConfiguration().metricsEnabled());
    assertEquals(newConnectionSql, agroalConnectionFactoryConfiguration.initialSql());
    try (Connection connection = dataSource.getConnection()) {
    }
}
 
Example 8
Source Project: quarkus   Source File: AgroalCounter.java    License: Apache License 2.0 6 votes vote down vote up
private AgroalDataSource getDataSource() {
    AgroalDataSource dsLocal = dataSource;
    if (dsLocal == null) {
        synchronized (this) {
            dsLocal = dataSource;
            if (dsLocal == null) {
                if (dataSourceName == null || DataSourceUtil.isDefault(dataSourceName)) {
                    dataSource = dsLocal = Arc.container().instance(AgroalDataSource.class).get();
                } else {
                    dataSource = dsLocal = Arc.container()
                            .instance(AgroalDataSource.class, new DataSourceLiteral(dataSourceName))
                            .get();
                }
            }
        }
    }
    return dsLocal;
}
 
Example 9
Source Project: quarkus   Source File: AgroalGauge.java    License: Apache License 2.0 6 votes vote down vote up
private AgroalDataSource getDataSource() {
    AgroalDataSource dsLocal = dataSource;
    if (dsLocal == null) {
        synchronized (this) {
            dsLocal = dataSource;
            if (dsLocal == null) {
                if (dataSourceName == null || DataSourceUtil.isDefault(dataSourceName)) {
                    dataSource = dsLocal = Arc.container().instance(AgroalDataSource.class).get();
                } else {
                    dataSource = dsLocal = Arc.container()
                            .instance(AgroalDataSource.class, new DataSourceLiteral(dataSourceName))
                            .get();
                }
            }
        }
    }
    return dsLocal;
}
 
Example 10
@Override
public ConnectionProvider resolve(String tenantId) {

    LOG.debugv("resolve({0})", tenantId);

    final MultiTenancyStrategy strategy = jpaConfig.getMultiTenancyStrategy();
    LOG.debugv("multitenancy strategy: {0}", strategy);
    AgroalDataSource dataSource = tenantDataSource(jpaConfig, tenantId, strategy);
    if (dataSource == null) {
        throw new IllegalStateException("No instance of datasource found for tenant: " + tenantId);
    }
    if (strategy == MultiTenancyStrategy.SCHEMA) {
        return new TenantConnectionProvider(tenantId, dataSource);
    }
    return new QuarkusConnectionProvider(dataSource);
}
 
Example 11
public QuarkusQuartzConnectionPoolProvider() {
    final ArcContainer container = Arc.container();
    final InstanceHandle<AgroalDataSource> instanceHandle;
    final boolean useDefaultDataSource = "QUARKUS_QUARTZ_DEFAULT_DATASOURCE".equals(dataSourceName);
    if (useDefaultDataSource) {
        instanceHandle = container.instance(AgroalDataSource.class);
    } else {
        instanceHandle = container.instance(AgroalDataSource.class, new DataSourceLiteral(dataSourceName));
    }
    if (instanceHandle.isAvailable()) {
        this.dataSource = instanceHandle.get();
    } else {
        String message = String.format(
                "JDBC Store configured but '%s' datasource is missing. You can configure your datasource by following the guide available at: https://quarkus.io/guides/datasource",
                useDefaultDataSource ? "default" : dataSourceName);
        throw new IllegalStateException(message);
    }
}
 
Example 12
Source Project: quarkus   Source File: AgroalRecorder.java    License: Apache License 2.0 5 votes vote down vote up
public Supplier<AgroalDataSource> agroalDataSourceSupplier(String dataSourceName,
        @SuppressWarnings("unused") DataSourcesRuntimeConfig dataSourcesRuntimeConfig) {
    final AgroalDataSource agroalDataSource = DataSources.fromName(dataSourceName);
    return new Supplier<AgroalDataSource>() {
        @Override
        public AgroalDataSource get() {
            return agroalDataSource;
        }
    };
}
 
Example 13
Source Project: quarkus   Source File: DataSources.java    License: Apache License 2.0 5 votes vote down vote up
public AgroalDataSource getDataSource(String dataSourceName) {
    return dataSources.computeIfAbsent(dataSourceName, new Function<String, AgroalDataSource>() {
        @Override
        public AgroalDataSource apply(String s) {
            return doCreateDataSource(s);
        }
    });
}
 
Example 14
Source Project: quarkus   Source File: DataSources.java    License: Apache License 2.0 5 votes vote down vote up
@PreDestroy
public void stop() {
    for (AgroalDataSource dataSource : dataSources.values()) {
        if (dataSource != null) {
            dataSource.close();
        }
    }
}
 
Example 15
/**
 * Create a new data source from the given configuration.
 * 
 * @param config Configuration to use.
 * 
 * @return New data source instance.
 */
private static AgroalDataSource createFrom(AgroalDataSourceConfiguration config) {
    try {
        return AgroalDataSource.from(config);
    } catch (SQLException ex) {
        throw new IllegalStateException("Failed to create a new data source based on the default config", ex);
    }
}
 
Example 16
/**
 * Returns either the default data source or the tenant specific one.
 * 
 * @param tenantId Tenant identifier. The value is required (non-{@literal null}) in case of
 *        {@link MultiTenancyStrategy#DATABASE}.
 * @param strategy Current multitenancy strategy Required value that cannot be {@literal null}.
 * 
 * @return Data source.
 */
private static AgroalDataSource tenantDataSource(JPAConfig jpaConfig, String tenantId, MultiTenancyStrategy strategy) {
    if (strategy != MultiTenancyStrategy.SCHEMA) {
        return Arc.container().instance(AgroalDataSource.class, new DataSource.DataSourceLiteral(tenantId)).get();
    }
    String dataSourceName = jpaConfig.getMultiTenancySchemaDataSource();
    if (dataSourceName == null) {
        AgroalDataSource dataSource = Arc.container().instance(AgroalDataSource.class).get();
        return createFrom(dataSource.getConfiguration());
    }
    return Arc.container().instance(AgroalDataSource.class, new DataSource.DataSourceLiteral(dataSourceName)).get();
}
 
Example 17
Source Project: quarkus   Source File: QuarkusConnectionProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isUnwrappableAs(final Class unwrapType) {
    return ConnectionProvider.class.equals(unwrapType) ||
            QuarkusConnectionProvider.class.isAssignableFrom(unwrapType) ||
            DataSource.class.isAssignableFrom(unwrapType) ||
            AgroalDataSource.class.isAssignableFrom(unwrapType);
}
 
Example 18
Source Project: quarkus   Source File: QuarkusConnectionProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> T unwrap(final Class<T> unwrapType) {
    if (ConnectionProvider.class.equals(unwrapType) ||
            QuarkusConnectionProvider.class.isAssignableFrom(unwrapType)) {
        return (T) this;
    } else if (DataSource.class.isAssignableFrom(unwrapType) || AgroalDataSource.class.isAssignableFrom(unwrapType)) {
        return (T) dataSource;
    } else {
        throw new UnknownUnwrapTypeException(unwrapType);
    }
}
 
Example 19
Source Project: kumuluzee   Source File: AgroalDataSourceFactory.java    License: MIT License 5 votes vote down vote up
public static AgroalDataSource createDataSource(DataSourceConfig dsc, boolean jtaPresent) {
    AgroalDataSourceConfigurationSupplier dataSourceConfig = new AgroalDataSourceConfigurationSupplier();

    AgroalConnectionPoolConfigurationSupplier poolConfig = dataSourceConfig.connectionPoolConfiguration();

    AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfig = poolConfig.connectionFactoryConfiguration();

    if (!jtaPresent) {
        dataSourceConfig.dataSourceImplementation(DataSourceImplementation.HIKARI);
    } else {
        poolConfig.transactionIntegration( JtaProvider.getInstance().getTransactionIntegration() );
    }

    if (!StringUtils.isNullOrEmpty( dsc.getDriverClass() )) {
        connectionFactoryConfig.connectionProviderClassName(dsc.getDriverClass());
    } else if (!StringUtils.isNullOrEmpty( dsc.getDataSourceClass( ))) {
        connectionFactoryConfig.connectionProviderClassName(dsc.getDataSourceClass());
    }

    if (!StringUtils.isNullOrEmpty( dsc.getConnectionUrl() )) {
        connectionFactoryConfig.jdbcUrl(dsc.getConnectionUrl());
    }

    setDatabaseCredentials(connectionFactoryConfig, dsc.getUsername(), dsc.getPassword());

    setConnectionPoolConfiguration(poolConfig, connectionFactoryConfig, dsc.getPool(), !jtaPresent);

    dsc.getProps().forEach(connectionFactoryConfig::jdbcProperty);

    try {
        return AgroalDataSource.from( dataSourceConfig );
    } catch (SQLException e) {
        throw new KumuluzServerException("Failed to create DataSource", e);
    }
}
 
Example 20
Source Project: kumuluzee   Source File: AgroalDataSourceFactory.java    License: MIT License 5 votes vote down vote up
public static AgroalDataSource createXaDataSource(XaDataSourceConfig xdsc, boolean jtaPresent) {
    AgroalDataSourceConfigurationSupplier xaDataSourceConfig = new AgroalDataSourceConfigurationSupplier();

    AgroalConnectionPoolConfigurationSupplier poolConfig = xaDataSourceConfig.connectionPoolConfiguration();

    AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfig = poolConfig.connectionFactoryConfiguration();

    if (jtaPresent) {
        poolConfig.transactionIntegration( JtaProvider.getInstance().getTransactionIntegration() );
    }

    if (!StringUtils.isNullOrEmpty( xdsc.getXaDatasourceClass() )) {
        connectionFactoryConfig.connectionProviderClassName( xdsc.getXaDatasourceClass() );
    }

    setDatabaseCredentials(connectionFactoryConfig, xdsc.getUsername(), xdsc.getPassword());

    setConnectionPoolConfiguration(poolConfig, connectionFactoryConfig, xdsc.getPool(), false);

    xdsc.getProps().forEach(connectionFactoryConfig::jdbcProperty);

    try {
        return AgroalDataSource.from( xaDataSourceConfig );
    } catch (SQLException e) {
        throw new KumuluzServerException("Failed to create XaDataSource", e);
    }
}
 
Example 21
@Override
public int maximumPoolSize(DataSource dataSource, JsonObject config) throws SQLException {
  if (dataSource instanceof AgroalDataSource) {
    return ((AgroalDataSource) dataSource).getConfiguration().connectionPoolConfiguration().maxSize();
  }
  return -1;
}
 
Example 22
Source Project: quarkus   Source File: AgroalProcessor.java    License: Apache License 2.0 4 votes vote down vote up
@Record(ExecutionTime.RUNTIME_INIT)
@BuildStep
void generateDataSourceBeans(AgroalRecorder recorder,
        DataSourcesRuntimeConfig dataSourcesRuntimeConfig,
        List<AggregatedDataSourceBuildTimeConfigBuildItem> aggregatedBuildTimeConfigBuildItems,
        SslNativeConfigBuildItem sslNativeConfig,
        Capabilities capabilities,
        BuildProducer<SyntheticBeanBuildItem> syntheticBeanBuildItemBuildProducer,
        BuildProducer<JdbcDataSourceBuildItem> jdbcDataSource) {
    if (aggregatedBuildTimeConfigBuildItems.isEmpty()) {
        // No datasource has been configured so bail out
        return;
    }

    for (Map.Entry<String, DataSourceSupport.Entry> entry : getDataSourceSupport(aggregatedBuildTimeConfigBuildItems,
            sslNativeConfig,
            capabilities).entries.entrySet()) {

        String dataSourceName = entry.getKey();

        SyntheticBeanBuildItem.ExtendedBeanConfigurator configurator = SyntheticBeanBuildItem
                .configure(AgroalDataSource.class)
                .addType(DATA_SOURCE)
                .scope(Singleton.class)
                .setRuntimeInit()
                .unremovable()
                // pass the runtime config into the recorder to ensure that the DataSource related beans
                // are created after runtime configuration has been setup
                .supplier(recorder.agroalDataSourceSupplier(dataSourceName, dataSourcesRuntimeConfig));

        if (entry.getValue().isDefault) {
            configurator.addQualifier(Default.class);
        } else {
            // this definitely not ideal, but 'elytron-jdbc-security' uses it (although it could be easily changed)
            // which means that perhaps other extensions might depend on this as well...
            configurator.name(dataSourceName);

            configurator.addQualifier().annotation(DotNames.NAMED).addValue("value", dataSourceName).done();
            configurator.addQualifier().annotation(DataSource.class).addValue("value", dataSourceName).done();
        }

        syntheticBeanBuildItemBuildProducer.produce(configurator.done());

        jdbcDataSource.produce(new JdbcDataSourceBuildItem(dataSourceName,
                entry.getValue().resolvedDbKind,
                entry.getValue().isDefault));
    }
}
 
Example 23
Source Project: quarkus   Source File: AgroalCounter.java    License: Apache License 2.0 4 votes vote down vote up
public void setDataSource(AgroalDataSource dataSource) {
    this.dataSource = dataSource;
}
 
Example 24
Source Project: quarkus   Source File: AgroalDataSourceReplacement.java    License: Apache License 2.0 4 votes vote down vote up
@Substitute
static AgroalDataSource from(AgroalDataSourceConfiguration configuration, AgroalDataSourceListener... listeners)
        throws SQLException {
    return new DataSource(configuration, listeners);
}
 
Example 25
public TenantConnectionProvider(String tenantId, AgroalDataSource dataSource) {
    super(dataSource);
    this.tenantId = tenantId;
}
 
Example 26
Source Project: quarkus   Source File: QuarkusConnectionProvider.java    License: Apache License 2.0 4 votes vote down vote up
public QuarkusConnectionProvider(final AgroalDataSource dataSource) {
    this.dataSource = dataSource;
}
 
Example 27
@Override
public void close(DataSource dataSource) throws SQLException {
  if (dataSource instanceof AgroalDataSource) {
    ((AgroalDataSource) dataSource).close();
  }
}
 
Example 28
Source Project: quarkus   Source File: DataSources.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Meant to be used from recorders that create synthetic beans that need access to {@code Datasource}.
 * In such using {@code Arc.container.instance(DataSource.class)} is not possible because
 * {@code Datasource} is itself a synthetic bean.
 * <p>
 * This method relies on the fact that {@code DataSources} should - given the same input -
 * always return the same {@code AgroalDataSource} no matter how many times it is invoked
 * (which makes sense because {@code DataSource} is a {@code Singleton} bean).
 * <p>
 * This method is thread-safe
 */
public static AgroalDataSource fromName(String dataSourceName) {
    return Arc.container().instance(DataSources.class).get()
            .getDataSource(dataSourceName);
}