Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions module/spring-boot-jooq/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,16 @@ dependencies {
optional(project(":core:spring-boot-autoconfigure"))
optional(project(":module:spring-boot-r2dbc"))
optional("jakarta.xml.bind:jakarta.xml.bind-api")
optional("org.jooq:jooq-reactor-extensions")
optional("org.jetbrains.kotlinx:kotlinx-coroutines-reactive")
optional("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")

testCompileOnly("com.google.code.findbugs:jsr305")

testImplementation(project(":core:spring-boot-test"))
testImplementation(project(":module:spring-boot-flyway"))
testImplementation(project(":test-support:spring-boot-test-support"))
testImplementation("io.projectreactor:reactor-test")

testRuntimeOnly("ch.qos.logback:logback-classic")
testRuntimeOnly("com.h2database:h2")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,9 @@
package org.springframework.boot.jooq.autoconfigure;

import java.io.IOException;
import java.io.InputStream;

import javax.sql.DataSource;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import org.jooq.ConnectionProvider;
import org.jooq.DSLContext;
import org.jooq.ExecuteListenerProvider;
Expand All @@ -26,10 +17,6 @@
import org.jooq.impl.DefaultConfiguration;
import org.jooq.impl.DefaultDSLContext;
import org.jooq.impl.DefaultExecuteListenerProvider;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
Expand All @@ -43,11 +30,8 @@
import org.springframework.boot.transaction.autoconfigure.TransactionAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

/**
* {@link EnableAutoConfiguration Auto-configuration} for jOOQ.
Expand All @@ -56,6 +40,7 @@
* @author Michael Simons
* @author Dmytro Nosan
* @author Moritz Halbritter
* @author George Papadopoulos
* @since 4.0.0
*/
@AutoConfiguration(after = { DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class })
Expand Down Expand Up @@ -117,47 +102,7 @@ DefaultConfiguration jooqConfiguration(JooqProperties properties, ConnectionProv
@ConditionalOnProperty("spring.jooq.config")
@ConditionalOnMissingBean
Settings settings(JooqProperties properties) throws IOException {
if (!ClassUtils.isPresent("jakarta.xml.bind.JAXBContext", null)) {
throw new JaxbNotAvailableException();
}
Resource resource = properties.getConfig();
Assert.state(resource != null, "'resource' must not be null");
Assert.state(resource.exists(),
() -> "Resource %s set in spring.jooq.config does not exist".formatted(resource));
try (InputStream stream = resource.getInputStream()) {
return new JaxbSettingsLoader().load(stream);
}
}

/**
* Load {@link Settings} with <a href=
* "https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#jaxb-unmarshaller">
* XML External Entity Prevention</a>.
*/
private static final class JaxbSettingsLoader {

private Settings load(InputStream inputStream) {
try {
SAXParser parser = createParserFactory().newSAXParser();
Source source = new SAXSource(parser.getXMLReader(), new InputSource(inputStream));
JAXBContext context = JAXBContext.newInstance(Settings.class);
return context.createUnmarshaller().unmarshal(source, Settings.class).getValue();
}
catch (ParserConfigurationException | JAXBException | SAXException ex) {
throw new IllegalStateException("Failed to unmarshal settings", ex);
}
}

private SAXParserFactory createParserFactory()
throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setNamespaceAware(true);
factory.setXIncludeAware(false);
return factory;
}

return JooqUtils.loadSettings(properties);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright 2012-present the original author or authors.
*/

package org.springframework.boot.jooq.autoconfigure;

import kotlin.coroutines.CoroutineContext;
import kotlinx.coroutines.reactive.ContextInjector;
import kotlinx.coroutines.reactor.ReactorContext;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;

import org.springframework.util.ClassUtils;

/**
* Propagates a coroutine's Reactor context to jOOQ publishers.
*
* @author George Papadopoulos
* @since 4.2.0
*/
public final class JooqContextInjector implements ContextInjector {

private static final boolean reactorContextPresent = ClassUtils
.isPresent("kotlinx.coroutines.reactor.ReactorContext", JooqContextInjector.class.getClassLoader());

@Override
public <T> Publisher<T> injectCoroutineContext(Publisher<T> publisher, CoroutineContext coroutineContext) {
ReactorContext reactorContext = coroutineContext.get(ReactorContext.Key);
if (reactorContext == null) {
return publisher;
}
if (reactorContextPresent && publisher instanceof org.jooq.Publisher<?>) {
// Bridge with jooq:
// `Flux.from(publisher)` is jooq's documented way to turn its bridge
// `Publisher` into something Reactor-native.
// Though, wrapping alone only gets us a real Flux; the context still needs a
// path into jooq's internals.
// That path is the `SubscriberProvider` SPI, see `CoreSubscriberProvider`.
return Flux.from(publisher).contextWrite(reactorContext.getContext());
}
return publisher;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright 2012-present the original author or authors.
*/

package org.springframework.boot.jooq.autoconfigure;

import io.r2dbc.spi.ConnectionFactory;
import reactor.core.publisher.Mono;

import org.springframework.r2dbc.connection.ConnectionHolder;
import org.springframework.r2dbc.connection.R2dbcTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.reactive.TransactionSynchronizationManager;

/**
* Retains connections while jOOQ releases its per-statement connection handles.
*
* @author George Papadopoulos
*/
final class JooqR2dbcTransactionManager extends R2dbcTransactionManager {

JooqR2dbcTransactionManager(ConnectionFactory connectionFactory) {
super(connectionFactory);
}

@Override
protected Mono<Void> doBegin(TransactionSynchronizationManager synchronizationManager, Object transaction,
TransactionDefinition definition) {
return Mono.defer(() -> {
// Check if this is a new transaction or not.
// We have to invoke requested() only for new transactions
boolean hadConnectionHolder = synchronizationManager.hasResource(obtainConnectionFactory());
return super.doBegin(synchronizationManager, transaction, definition).doOnSuccess((unused) -> {
if (!hadConnectionHolder) {
ConnectionHolder holder = (ConnectionHolder) synchronizationManager
.getResource(obtainConnectionFactory());
if (holder != null) {
/*
* Jooq invokes create()/close() through `ConnectionFactory` per
* statement, rather than once for the whole transaction. But the
* reference-counted `ConnectionHolder` is 0-based. That means
* after the first statement (before committing the transaction)
* ConnectionHolder.released() is being invoked, which effectively
* drops the connection due to us reaching 0 references.
*
* To fix this we call ourselves the requested() function, which
* makes the counter to start from 1. No matching released() is
* needed because doCleanupAfterCompletion() unbinds and closes
* the connection directly at transaction end, bypassing the
* reference count entirely.
*/
holder.requested();
}
}
});
});
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Copyright 2012-present the original author or authors.
*/

package org.springframework.boot.jooq.autoconfigure;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import org.jooq.conf.Settings;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

/**
* Utilities for jOOQ configuration.
*
* @author George Papadopoulos
*/
final class JooqUtils {

private JooqUtils() {
}

static Settings loadSettings(JooqProperties properties) throws IOException {
if (!ClassUtils.isPresent("jakarta.xml.bind.JAXBContext", null)) {
throw new JaxbNotAvailableException();
}
Resource resource = properties.getConfig();
Assert.state(resource != null, "'resource' must not be null");
Assert.state(resource.exists(),
() -> "Resource %s set in spring.jooq.config does not exist".formatted(resource));
try (InputStream stream = resource.getInputStream()) {
return new JaxbSettingsLoader().load(stream);
}
}

/**
* Load {@link Settings} with <a href=
* "https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#jaxb-unmarshaller">
* XML External Entity Prevention</a>.
*/
private static final class JaxbSettingsLoader {

private Settings load(InputStream inputStream) {
try {
SAXParser parser = createParserFactory().newSAXParser();
Source source = new SAXSource(parser.getXMLReader(), new InputSource(inputStream));
JAXBContext context = JAXBContext.newInstance(Settings.class);
return context.createUnmarshaller().unmarshal(source, Settings.class).getValue();
}
catch (ParserConfigurationException | JAXBException | SAXException ex) {
throw new IllegalStateException("Failed to unmarshal settings", ex);
}
}

private SAXParserFactory createParserFactory()
throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setNamespaceAware(true);
factory.setXIncludeAware(false);
return factory;
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ class NoDslContextBeanFailureAnalyzer extends AbstractFailureAnalyzer<NoSuchBean
protected @Nullable FailureAnalysis analyze(Throwable rootFailure, NoSuchBeanDefinitionException cause) {
if (DSLContext.class.equals(cause.getBeanType()) && hasR2dbcAutoConfiguration()) {
return new FailureAnalysis(
"jOOQ has not been auto-configured as R2DBC has been auto-configured in favor of JDBC and jOOQ "
+ "auto-configuration does not yet support R2DBC. ",
"To use jOOQ with JDBC, exclude R2dbcAutoConfiguration. To use jOOQ with R2DBC, define your own "
+ "jOOQ configuration.",
"jOOQ has not been auto-configured for the application's R2DBC connection factory.",
"To use jOOQ with R2DBC, add org.jooq:jooq-reactor-extensions and ensure that a single "
+ "ConnectionFactory candidate is available, or define your own jOOQ configuration. "
+ "To use jOOQ with JDBC, exclude R2dbcAutoConfiguration.",
cause);
}
return null;
Expand Down
Loading