Skip to content

Guard AOT registration of PageModule #3034

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
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
7 changes: 6 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>3.2.3-SNAPSHOT</version>
<version>3.2.x-3033-SNAPSHOT</version>

<name>Spring Data Core</name>
<description>Core Spring concepts underpinning every Spring Data module.</description>
Expand Down Expand Up @@ -325,6 +325,11 @@
<version>${jmolecules-integration}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.springframework.aot.hint.TypeReference;
import org.springframework.data.web.config.SpringDataJacksonConfiguration.PageModule;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;

/**
* {@link RuntimeHintsRegistrar} providing hints for web usage.
Expand All @@ -32,7 +33,9 @@ class WebRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {

hints.reflection().registerType(TypeReference.of("org.springframework.data.domain.Unpaged"),
hint -> hint.onReachableType(PageModule.class));
if (ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader)) {
hints.reflection().registerType(TypeReference.of("org.springframework.data.domain.Unpaged"),
hint -> hint.onReachableType(PageModule.class));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.test.util;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.extension.ExtendWith;

/**
* Annotation used to exclude entries from the classpath.
* Simplified version of <a href="https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ClassPathExclusions.java">ClassPathExclusions</a>.
*
* @author Christoph Strobl
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@ExtendWith(ClassPathExclusionsExtension.class)
public @interface ClassPathExclusions {

/**
* One or more packages that should be excluded from the classpath.
*
* @return the excluded packages
*/
String[] packages();

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.test.util;

import java.lang.reflect.Method;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestPlan;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
import org.junit.platform.launcher.listeners.TestExecutionSummary;
import org.springframework.util.CollectionUtils;

/**
* Simplified version of <a href="https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java">ModifiedClassPathExtension</a>.
*
* @author Christoph Strobl
*/
class ClassPathExclusionsExtension implements InvocationInterceptor {

@Override
public void interceptBeforeAllMethod(Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
intercept(invocation, extensionContext);
}

@Override
public void interceptBeforeEachMethod(Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
intercept(invocation, extensionContext);
}

@Override
public void interceptAfterEachMethod(Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
intercept(invocation, extensionContext);
}

@Override
public void interceptAfterAllMethod(Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
intercept(invocation, extensionContext);
}

@Override
public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {
interceptMethod(invocation, invocationContext, extensionContext);
}

@Override
public void interceptTestTemplateMethod(Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
interceptMethod(invocation, invocationContext, extensionContext);
}

private void interceptMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {

if (isModifiedClassPathClassLoader(extensionContext)) {
invocation.proceed();
return;
}

Class<?> testClass = extensionContext.getRequiredTestClass();
Method testMethod = invocationContext.getExecutable();
PackageExcludingClassLoader modifiedClassLoader = PackageExcludingClassLoader.get(testClass, testMethod);
if (modifiedClassLoader == null) {
invocation.proceed();
return;
}
invocation.skip();
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(modifiedClassLoader);
try {
runTest(extensionContext.getUniqueId());
} finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
}

private void runTest(String testId) throws Throwable {

LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectUniqueId(testId)).build();
Launcher launcher = LauncherFactory.create();
TestPlan testPlan = launcher.discover(request);
SummaryGeneratingListener listener = new SummaryGeneratingListener();
launcher.registerTestExecutionListeners(listener);
launcher.execute(testPlan);
TestExecutionSummary summary = listener.getSummary();
if (!CollectionUtils.isEmpty(summary.getFailures())) {
throw summary.getFailures().get(0).getException();
}
}

private void intercept(Invocation<Void> invocation, ExtensionContext extensionContext) throws Throwable {
if (isModifiedClassPathClassLoader(extensionContext)) {
invocation.proceed();
return;
}
invocation.skip();
}

private boolean isModifiedClassPathClassLoader(ExtensionContext extensionContext) {
Class<?> testClass = extensionContext.getRequiredTestClass();
ClassLoader classLoader = testClass.getClassLoader();
return classLoader.getClass().getName().equals(PackageExcludingClassLoader.class.getName());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.test.util;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Stream;

import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.ClassUtils;

/**
* Simplified version of <a href="https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java">ModifiedClassPathClassLoader</a>.
*
* @author Christoph Strobl
*/
class PackageExcludingClassLoader extends URLClassLoader {

private final Set<String> excludedPackages;
private final ClassLoader junitLoader;

PackageExcludingClassLoader(URL[] urls, ClassLoader parent, Collection<String> excludedPackages,
ClassLoader junitClassLoader) {

super(urls, parent);
this.excludedPackages = Set.copyOf(excludedPackages);
this.junitLoader = junitClassLoader;
}

@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {

if (name.startsWith("org.junit") || name.startsWith("org.hamcrest")) {
return Class.forName(name, false, this.junitLoader);
}

String packageName = ClassUtils.getPackageName(name);
if (this.excludedPackages.contains(packageName)) {
throw new ClassNotFoundException(name);
}
return super.loadClass(name);
}

static PackageExcludingClassLoader get(Class<?> testClass, Method testMethod) {

List<String> excludedPackages = readExcludedPackages(testClass, testMethod);

if (excludedPackages.isEmpty()) {
return null;
}

ClassLoader testClassClassLoader = testClass.getClassLoader();
Stream<URL> urls = null;
if (testClassClassLoader instanceof URLClassLoader urlClassLoader) {
urls = Stream.of(urlClassLoader.getURLs());
} else {
urls = Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator))
.map(PackageExcludingClassLoader::toURL);
}

return new PackageExcludingClassLoader(urls.toArray(URL[]::new), testClassClassLoader.getParent(), excludedPackages,
testClassClassLoader);
}

private static List<String> readExcludedPackages(Class<?> testClass, Method testMethod) {

return Stream.of( //
AnnotatedElementUtils.findMergedAnnotation(testClass, ClassPathExclusions.class),
AnnotatedElementUtils.findMergedAnnotation(testMethod, ClassPathExclusions.class) //
).filter(Objects::nonNull) //
.map(ClassPathExclusions::packages) //
.collect(new CombingArrayCollector<String>());
}

private static URL toURL(String entry) {
try {
return new File(entry).toURI().toURL();
} catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}

private static class CombingArrayCollector<T> implements Collector<T[], List<T>, List<T>> {

@Override
public Supplier<List<T>> supplier() {
return ArrayList::new;
}

@Override
public BiConsumer<List<T>, T[]> accumulator() {
return (target, values) -> target.addAll(Arrays.asList(values));
}

@Override
public BinaryOperator<List<T>> combiner() {
return (r1, r2) -> {
r1.addAll(r2);
return r1;
};
}

@Override
public Function<List<T>, List<T>> finisher() {
return i -> (List<T>) i;
}

@Override
public Set<Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH));
}
}
}
Loading