Skip to content
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

Use avaje spi for service validation when available #456

Merged
merged 3 commits into from
Jun 24, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;

import io.avaje.http.generator.core.APContext;
import io.avaje.http.generator.core.ClientPrism;
import io.avaje.http.generator.core.ControllerReader;
import io.avaje.http.generator.core.ImportPrism;
Expand Down Expand Up @@ -44,14 +45,15 @@ public SourceVersion getSupportedSourceVersion() {
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
this.processingEnv = processingEnv;
APContext.init(processingEnv);
ProcessingContext.init(processingEnv, new ClientPlatformAdapter(), false);
this.componentWriter = new SimpleComponentWriter(metaData);
useJsonB = ProcessingContext.useJsonb();
}

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment round) {
ProcessingContext.findModule(annotations, round);
APContext.setProjectModuleElement(annotations, round);
final var platform = platform();
if (!(platform instanceof ClientPlatformAdapter)) {
setPlatform(new ClientPlatformAdapter());
Expand Down Expand Up @@ -107,7 +109,8 @@ protected String writeClientAdapter(ControllerReader reader) throws IOException
private void initialiseComponent() {
metaData.initialiseFullName();
if (!metaData.all().isEmpty()) {
ProcessingContext.validateModule(metaData.fullName());
ProcessingContext.addClientComponent(metaData.fullName());
ProcessingContext.validateModule();
}
try {
componentWriter.init();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.ElementFilter;

import io.avaje.prism.GenerateAPContext;
import io.avaje.prism.GenerateModuleInfoReader;

@GenerateAPContext
@GenerateModuleInfoReader
@SupportedOptions({"useJavax", "useSingleton", "instrumentRequests","disableDirectWrites"})
public abstract class BaseProcessor extends AbstractProcessor {

Expand All @@ -42,6 +47,7 @@ public Set<String> getSupportedAnnotationTypes() {
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
APContext.init(processingEnv);
ProcessingContext.init(processingEnv, providePlatformAdapter());
}

Expand All @@ -51,7 +57,7 @@ public synchronized void init(ProcessingEnvironment processingEnv) {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment round) {
var pathElements = round.getElementsAnnotatedWith(typeElement(PathPrism.PRISM_TYPE));

APContext.setProjectModuleElement(annotations, round);
if (contextPathString == null) {
contextPathString =
ElementFilter.modulesIn(pathElements).stream()
Expand Down Expand Up @@ -79,6 +85,7 @@ public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment

if (round.processingOver()) {
writeOpenAPI();
ProcessingContext.validateModule();
}
return false;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
package io.avaje.http.generator.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.ModuleElement;
Expand All @@ -31,6 +26,7 @@
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;

import io.avaje.http.generator.core.ModuleInfoReader.Provides;
import io.avaje.http.generator.core.openapi.DocContext;

public final class ProcessingContext {
Expand All @@ -53,8 +49,9 @@ private static final class Ctx {
private final boolean instrumentAllMethods;
private final boolean disableDirectWrites;
private final boolean javalin6;
private ModuleElement module;
private final boolean spiPresent = APContext.typeElement("io.avaje.spi.internal.ServiceProcessor") != null;
private boolean validated;
private String clientFQN;

Ctx(ProcessingEnvironment env, PlatformAdapter adapter, boolean generateOpenAPI) {
readAdapter = adapter;
Expand Down Expand Up @@ -146,7 +143,12 @@ public static JavaFileObject createWriter(String cls, Element origin) throws IOE

/** Create a file writer for the META-INF services file. */
public static FileObject createMetaInfWriter(String target) throws IOException {
return CTX.get().filer.createResource(StandardLocation.CLASS_OUTPUT, "", target);
var serviceFile =
CTX.get().spiPresent
? target.replace("META-INF/services/", "META-INF/generated-services/")
: target;

return filer().createResource(StandardLocation.CLASS_OUTPUT, "", serviceFile);
}

public static JavaFileObject createWriter(String cls) throws IOException {
Expand Down Expand Up @@ -175,7 +177,7 @@ public static List<ExecutableElement> superMethods(Element element, String metho
.filter(type -> !type.toString().contains("java.lang.Object"))
.map(superType -> {
final var superClass = (TypeElement) types.asElement(superType);
for (final ExecutableElement method : ElementFilter.methodsIn(CTX.get().elementUtils.getAllMembers(superClass))) {
for (final var method : ElementFilter.methodsIn(CTX.get().elementUtils.getAllMembers(superClass))) {
if (method.getSimpleName().contentEquals(methodName)) {
return method;
}
Expand Down Expand Up @@ -231,45 +233,33 @@ public static boolean isAssignable2Interface(String type, String superType) {
static Stream<String> superTypes(Element element) {
final Types types = CTX.get().typeUtils;
return types.directSupertypes(element.asType()).stream()
.filter(type -> !type.toString().contains("java.lang.Object"))
.map(superType -> (TypeElement) types.asElement(superType))
.flatMap(e -> Stream.concat(superTypes(e), Stream.of(e)))
.map(Object::toString);
}

public static void findModule(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (CTX.get().module == null) {
CTX.get().module =
annotations.stream()
.map(roundEnv::getElementsAnnotatedWith)
.flatMap(Collection::stream)
.findAny()
.map(ProcessingContext::getModuleElement)
.orElse(null);
}
.filter(type -> !type.toString().contains("java.lang.Object"))
.map(superType -> (TypeElement) types.asElement(superType))
.flatMap(e -> Stream.concat(superTypes(e), Stream.of(e)))
.map(Object::toString);
}

public static void validateModule(String fqn) {
var module = CTX.get().module;
public static void validateModule() {
var module = APContext.getProjectModuleElement();
if (module != null && !CTX.get().validated && !module.isUnnamed()) {

CTX.get().validated = true;
try (var inputStream =
CTX.get()
.filer
.getResource(StandardLocation.SOURCE_PATH, "", "module-info.java")
.toUri()
.toURL()
.openStream();
var reader = new BufferedReader(new InputStreamReader(inputStream))) {

var noProvides = reader.lines().map(s -> {
if (s.contains("io.avaje.http.api.javalin") && !s.contains("static")) {
logWarn("io.avaje.http.api.javalin only contains SOURCE retention annotations. It should added as `requires static`");
}
return s;
})
try (var bufferedReader = APContext.getModuleInfoReader()) {
var reader = new ModuleInfoReader(module, bufferedReader);
reader.requires().forEach(r -> {
if (!r.isStatic() && r.getDependency().getQualifiedName().contentEquals("io.avaje.http.api.javalin")) {
logWarn(module, "io.avaje.http.api.javalin only contains SOURCE retention annotations. It should added as `requires static`");
}
});
var fqn = CTX.get().clientFQN;
if (CTX.get().spiPresent || fqn == null) {
return;
}
var noProvides = reader.provides().stream()
.filter(p -> "io.avaje.http.client.HttpClient.GeneratedComponent".equals(p.service()))
.map(Provides::implementations)
.flatMap(List::stream)
.noneMatch(s -> s.contains(fqn));

if (noProvides && !buildPluginAvailable()) {
logError(module, "Missing `provides io.avaje.http.client.HttpClient.GeneratedComponent with %s;`", fqn);
}
Expand Down Expand Up @@ -309,4 +299,8 @@ private static boolean resourceExists(String relativeName) {
return false;
}
}

public static void addClientComponent(String clientFQN) {
CTX.get().clientFQN = clientFQN;
}
}
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<nexus.staging.autoReleaseAfterClose>true</nexus.staging.autoReleaseAfterClose>
<swagger.version>2.2.22</swagger.version>
<jackson.version>2.14.2</jackson.version>
<avaje.prisms.version>1.24</avaje.prisms.version>
<avaje.prisms.version>1.25</avaje.prisms.version>
<module-info.shade>${project.build.directory}${file.separator}module-info.shade</module-info.shade>
</properties>

Expand Down