Skip to content

Make OpenAPI javadocs inheritable #135

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

Merged
merged 8 commits into from
Jan 17, 2023
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 @@ -5,6 +5,7 @@
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

Expand Down Expand Up @@ -60,6 +61,7 @@ public class MethodReader {

private final PathSegments pathSegments;
private final boolean hasValid;
private final List<ExecutableElement> superMethods;

MethodReader(ControllerReader bean, ExecutableElement element, ExecutableType actualExecutable, ProcessingContext ctx) {
this.ctx = ctx;
Expand All @@ -69,18 +71,48 @@ public class MethodReader {
this.actualParams = (actualExecutable == null) ? null : actualExecutable.getParameterTypes();
this.isVoid = element.getReturnType().getKind() == TypeKind.VOID;
this.methodRoles = Util.findRoles(element);
this.javadoc = Javadoc.parse(ctx.docComment(element));
this.produces = produces(bean);
this.apiResponses = getApiResponses();
initWebMethodViaAnnotation();

this.superMethods =
ctx.getSuperMethods(element.getEnclosingElement(), element.getSimpleName().toString());

superMethods.stream().forEach(m -> methodRoles.addAll(Util.findRoles(m)));

this.apiResponses = getApiResponses();
this.javadoc =
Optional.of(Javadoc.parse(ctx.docComment(element)))
.filter(Predicate.not(Javadoc::isEmpty))
.orElseGet(
() ->
superMethods.stream()
.map(e -> Javadoc.parse(ctx.docComment(e)))
.filter(Predicate.not(Javadoc::isEmpty))
.findFirst()
.orElse(Javadoc.parse("")));

if (isWebMethod()) {
Annotation jakartaValidAnnotation = null;

Class<Annotation> jakartaValidAnnotation;
try {
jakartaValidAnnotation = findAnnotation(jakartaValidAnnotation());
jakartaValidAnnotation = jakartaValidAnnotation();
} catch (final ClassNotFoundException e) {
// ignore
jakartaValidAnnotation = null;
}
this.hasValid = findAnnotation(Valid.class) != null || jakartaValidAnnotation != null;

final var jakartaAnnotation = jakartaValidAnnotation;

this.hasValid =
findAnnotation(Valid.class) != null
|| (jakartaValidAnnotation != null && findAnnotation(jakartaValidAnnotation) != null)
|| superMethods.stream()
.map(
e ->
findAnnotation(Valid.class, e) != null
|| (jakartaAnnotation != null
&& findAnnotation(jakartaAnnotation, e) != null))
.anyMatch(b -> b);

this.pathSegments = PathSegments.parse(Util.combinePath(bean.path(), webMethodPath));
} else {
this.hasValid = false;
Expand Down Expand Up @@ -149,19 +181,35 @@ private List<OpenAPIResponse> getApiResponses() {
.map(OpenAPIResponses::value)
.flatMap(Arrays::stream);

return Stream.concat(container, Arrays.stream(element.getAnnotationsByType(OpenAPIResponse.class)))
.collect(Collectors.toList());
final var methodResponses =
Stream.concat(
container, Arrays.stream(element.getAnnotationsByType(OpenAPIResponse.class)));

final var superMethodResponses =
superMethods.stream()
.flatMap(
m ->
Stream.concat(
Optional.ofNullable(findAnnotation(OpenAPIResponses.class, m)).stream()
.map(OpenAPIResponses::value)
.flatMap(Arrays::stream),
Arrays.stream(m.getAnnotationsByType(OpenAPIResponse.class))));

return Stream.concat(methodResponses, superMethodResponses).collect(Collectors.toList());
}

public <A extends Annotation> A findAnnotation(Class<A> type) {
A annotation = element.getAnnotation(type);

return findAnnotation(type, element);
}

public <A extends Annotation> A findAnnotation(Class<A> type, ExecutableElement elem) {
final var annotation = elem.getAnnotation(type);
if (annotation != null) {
return annotation;
}

return bean.findMethodAnnotation(type, element);
return bean.findMethodAnnotation(type, elem);
}

private List<String> addTagsToList(Element element, List<String> list) {
Expand All @@ -179,8 +227,9 @@ private List<String> addTagsToList(Element element, List<String> list) {
}

public List<String> tags() {
List<String> tags = new ArrayList<>();
tags = addTagsToList(element, tags);
final var tags = addTagsToList(element, new ArrayList<>());
superMethods.forEach(e -> addTagsToList(e, tags));

return addTagsToList(element.getEnclosingElement(), tags);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
package io.avaje.http.generator.core;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
Expand Down Expand Up @@ -115,6 +120,25 @@ public TypeMirror asMemberOf(DeclaredType declaredType, Element element) {
return types.asMemberOf(declaredType, element);
}

public List<ExecutableElement> getSuperMethods(Element element, String methodName) {

return types.directSupertypes(element.asType()).stream()
.filter(t -> !t.toString().contains("java.lang.Object"))
.map(
superType -> {
final var superClass = (TypeElement) types.asElement(superType);
for (final ExecutableElement method :
ElementFilter.methodsIn(elements.getAllMembers(superClass))) {
if (method.getSimpleName().contentEquals(methodName)) {
return method;
}
}
return null;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}

public PlatformAdapter platform() {
return readAdapter;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,12 @@ public String getReturnDescription() {
public boolean isDeprecated() {
return deprecated;
}

public boolean isEmpty() {
return summary.isBlank()
&& description.isBlank()
&& params.isEmpty()
&& returnDescription.isBlank()
&& !deprecated;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package org.example.myapp.web.test;

import io.avaje.http.api.Get;
import io.avaje.http.api.MediaType;
import io.avaje.http.api.OpenAPIResponse;
import io.avaje.http.api.Path;
import io.avaje.http.api.Produces;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.tags.Tag;

@Path("javalin")
@OpenAPIDefinition(
info =
@Info(
title = "Example service showing off the Path extension method of controller",
description = ""))
public interface HealthController {
/**
* Standard Get
*
* @return a health check
*/
@Get("/health")
@Produces(MediaType.TEXT_PLAIN)
@Tag(name = "tag1", description = "it's somethin")
@OpenAPIResponse(responseCode = "500", type = ErrorResponse.class)
String health();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.example.myapp.web.test;

import io.avaje.http.api.Controller;

@Controller
public class HealthControllerImpl implements HealthController {

@Override
public String health() {

return "this feels like a picnic *chew*";
}
}
35 changes: 35 additions & 0 deletions tests/test-javalin-jsonb/src/main/resources/public/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
"version" : ""
},
"tags" : [
{
"name" : "tag1",
"description" : "it's somethin"
},
{
"name" : "tag1",
"description" : "this is added to openapi tags"
Expand Down Expand Up @@ -764,6 +768,37 @@
"deprecated" : true
}
},
"/javalin/health" : {
"get" : {
"tags" : [
"tag1"
],
"summary" : "Standard Get",
"description" : "",
"responses" : {
"500" : {
"description" : "a health check",
"content" : {
"text/plain" : {
"schema" : {
"$ref" : "#/components/schemas/ErrorResponse"
}
}
}
},
"200" : {
"description" : "a health check",
"content" : {
"text/plain" : {
"schema" : {
"type" : "string"
}
}
}
}
}
}
},
"/openapi/get" : {
"get" : {
"tags" : [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
Expand Down Expand Up @@ -155,12 +156,47 @@ public void testOpenAPIGeneration() throws Exception {

final var mapper = new ObjectMapper();
final var expectedOpenApiJson =
mapper.readTree(new File("src/test/java/io/avaje/http/generator/expectedOpenApi.json"));
mapper.readTree(new File("src/test/resources/expectedOpenApi.json"));
final var generatedOpenApi = mapper.readTree(new File("openapi.json"));

assert expectedOpenApiJson.equals(generatedOpenApi);
}

@Test
public void testInheritableOpenAPIGeneration() throws Exception {
final var source = Paths.get("src").toAbsolutePath().toString();
// OpenAPIController
final var files = getSourceFiles(source);

final List<JavaFileObject> openAPIController = new ArrayList<>(2);
for (final var file : files) {
if (file.isNameCompatible("HealthController", Kind.SOURCE)
|| file.isNameCompatible("HealthControllerImpl", Kind.SOURCE))
openAPIController.add(file);
}
final var compiler = ToolProvider.getSystemJavaCompiler();

final var task =
compiler.getTask(
new PrintWriter(System.out),
null,
null,
List.of("--release=11"),
null,
openAPIController);
task.setProcessors(List.of(new JavalinProcessor(false), new Processor()));

assertThat(task.call()).isTrue();

final var mapper = new ObjectMapper();
final var expectedOpenApiJson =
mapper.readTree(new File("src/test/resources/expectedInheritedOpenApi.json"));
final var generatedOpenApi = mapper.readTree(new File("openapi.json"));

assert expectedOpenApiJson.equals(generatedOpenApi);
}


private Iterable<JavaFileObject> getSourceFiles(String source) throws Exception {
final var compiler = ToolProvider.getSystemJavaCompiler();
final var files = compiler.getStandardFileManager(null, null, null);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"openapi" : "3.0.1",
"info" : {
"title" : "Example service showing off the Path extension method of controller",
"version" : ""
},
"tags" : [
{
"name" : "tag1",
"description" : "it's somethin"
}
],
"paths" : {
"/javalin/health" : {
"get" : {
"tags" : [
"tag1"
],
"summary" : "Standard Get",
"description" : "",
"responses" : {
"500" : {
"description" : "a health check",
"content" : {
"text/plain" : {
"schema" : {
"$ref" : "#/components/schemas/ErrorResponse"
}
}
}
},
"200" : {
"description" : "a health check",
"content" : {
"text/plain" : {
"schema" : {
"type" : "string"
}
}
}
}
}
}
}
},
"components" : {
"schemas" : {
"ErrorResponse" : {
"type" : "object",
"properties" : {
"id" : {
"type" : "string"
},
"text" : {
"type" : "string"
}
}
}
}
}
}