Skip to content

Commit

Permalink
Merge pull request #4764 from jGauravGupta/FISH-56
Browse files Browse the repository at this point in the history
FISH-56 OpenAPI document doesn't use @Schema when class is in jar dependency of the project
  • Loading branch information
MattGill98 authored Jul 7, 2020
2 parents c04ac26 + 1bcbbd2 commit ecb2017
Show file tree
Hide file tree
Showing 5 changed files with 197 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ public interface ApiContext {
*/
boolean isApplicationType(String type);

/**
* @param type any class, not null
* @return true, if the give type is a filtered class for OpenAPI metadata processing
* otherwise false
*/
boolean isAllowedType(Type type);

/**
* @param type any class, not null
* @return type, if the give type is a known type in this context, else null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,10 @@
import fish.payara.microprofile.openapi.impl.model.util.ModelUtils;
import fish.payara.microprofile.openapi.impl.visitor.OpenApiWalker;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import static java.util.Collections.singleton;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
Expand Down Expand Up @@ -124,6 +126,8 @@ public class ApplicationProcessor implements OASProcessor, ApiVisitor {

private final ClassLoader appClassLoader;

private OpenApiWalker apiWalker;

public ApplicationProcessor(ApplicationInfo appInfo) {
this(appInfo.getTypes(), filterTypes(appInfo), appInfo.getAppClassLoader());
}
Expand Down Expand Up @@ -158,7 +162,7 @@ private static Set<Type> filterTypes(ApplicationInfo appInfo) {
@Override
public OpenAPI process(OpenAPI api, OpenApiConfiguration config) {
if (config == null || !config.getScanDisable()) {
ApiWalker apiWalker = new OpenApiWalker(
this.apiWalker = new OpenApiWalker(
api,
allTypes,
config == null ? allowedTypes : config.getValidClasses(allowedTypes),
Expand Down Expand Up @@ -1083,17 +1087,28 @@ private boolean insertObjectReference(ApiContext context, Reference<?> referee,
}

if (referenceClass != null && referenceClass instanceof ExtensibleType) {
final AnnotationModel schemaAnnotation
= AnnotationInfo.valueOf((ExtensibleType) referenceClass)
.getAnnotation(Schema.class);
ExtensibleType referenceClassType = (ExtensibleType) referenceClass;
final AnnotationModel schemaAnnotation = AnnotationInfo.valueOf(referenceClassType)
.getAnnotation(Schema.class);
if (schemaAnnotation != null) {
String schemaName = schemaAnnotation.getValue("name", String.class);

if (schemaName == null || schemaName.isEmpty()) {
schemaName = ModelUtils.getSimpleName(referenceClassName);
}
// Set the reference name
referee.setRef(schemaName == null || schemaName.isEmpty() ? ModelUtils.getSimpleName(referenceClassName) : schemaName);
referee.setRef(schemaName);

org.eclipse.microprofile.openapi.models.media.Schema schema = context.getApi().getComponents().getSchemas().get(schemaName);
if (schema == null) {
// Create the schema
if (context.isAllowedType(referenceClassType)) {
visitSchema(schemaAnnotation, referenceClass, context);
} else {
apiWalker.processAnnotations(singleton(referenceClassType), Schema.class, this::visitSchema);
}
}

// Create the schema
visitSchema(schemaAnnotation, referenceClass, context);
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
package fish.payara.microprofile.openapi.impl.visitor;

import fish.payara.microprofile.openapi.api.visitor.ApiContext;
import java.util.Set;
import org.eclipse.microprofile.openapi.models.OpenAPI;
import org.eclipse.microprofile.openapi.models.Operation;
import org.glassfish.hk2.classmodel.reflect.Type;
Expand All @@ -52,17 +53,19 @@ public class OpenApiContext implements ApiContext {
private final OpenAPI api;
private final String path;
private final Operation operation;
private final Set<Type> allowedTypes;

public OpenApiContext(Types allTypes, ClassLoader appClassLoader, OpenAPI api, String path, Operation operation) {
public OpenApiContext(Types allTypes, Set<Type> allowedTypes, ClassLoader appClassLoader, OpenAPI api, String path, Operation operation) {
this.allTypes = allTypes;
this.allowedTypes = allowedTypes;
this.api = api;
this.path = path;
this.operation = operation;
this.appClassLoader = appClassLoader;
}

public OpenApiContext(Types allTypes, ClassLoader appClassLoader, OpenAPI api, String path) {
this(allTypes, appClassLoader, api, path, null);
public OpenApiContext(Types allTypes, Set<Type> allowedTypes, ClassLoader appClassLoader, OpenAPI api, String path) {
this(allTypes, allowedTypes, appClassLoader, api, path, null);
}

@Override
Expand All @@ -80,6 +83,10 @@ public Operation getWorkingOperation() {
return operation;
}

public boolean isAllowedType(Type type) {
return allowedTypes.contains(type);
}

@Override
public boolean isApplicationType(String type) {
return allTypes.getBy(type) != null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,67 +127,72 @@ public OpenApiWalker(OpenAPI api, Types allTypes, Set<Type> allowedTypes, ClassL

@Override
public void accept(ApiVisitor visitor) {
processAnnotations(allowedTypes, visitor);
}

public void processAnnotations(Set<Type> types, ApiVisitor visitor) {
// OpenAPI necessary annotations
processAnnotations(OpenAPIDefinition.class, visitor::visitOpenAPI);
processAnnotations(types, OpenAPIDefinition.class, visitor::visitOpenAPI);

// JAX-RS methods
processAnnotations(GET.class, visitor::visitGET);
processAnnotations(POST.class, visitor::visitPOST);
processAnnotations(PUT.class, visitor::visitPUT);
processAnnotations(DELETE.class, visitor::visitDELETE);
processAnnotations(HEAD.class, visitor::visitHEAD);
processAnnotations(OPTIONS.class, visitor::visitOPTIONS);
processAnnotations(PATCH.class, visitor::visitPATCH);
processAnnotations(types, GET.class, visitor::visitGET);
processAnnotations(types, POST.class, visitor::visitPOST);
processAnnotations(types, PUT.class, visitor::visitPUT);
processAnnotations(types, DELETE.class, visitor::visitDELETE);
processAnnotations(types, HEAD.class, visitor::visitHEAD);
processAnnotations(types, OPTIONS.class, visitor::visitOPTIONS);
processAnnotations(types, PATCH.class, visitor::visitPATCH);

// JAX-RS parameters
processAnnotations(QueryParam.class, visitor::visitQueryParam);
processAnnotations(PathParam.class, visitor::visitPathParam);
processAnnotations(HeaderParam.class, visitor::visitHeaderParam);
processAnnotations(CookieParam.class, visitor::visitCookieParam);
processAnnotations(FormParam.class, visitor::visitFormParam);
processAnnotations(types, QueryParam.class, visitor::visitQueryParam);
processAnnotations(types, PathParam.class, visitor::visitPathParam);
processAnnotations(types, HeaderParam.class, visitor::visitHeaderParam);
processAnnotations(types, CookieParam.class, visitor::visitCookieParam);
processAnnotations(types, FormParam.class, visitor::visitFormParam);

// All other OpenAPI annotations
processAnnotations(Schema.class, visitor::visitSchema);
processAnnotations(Server.class, visitor::visitServer, Servers.class);
processAnnotations(Servers.class, visitor::visitServers, Server.class);
processAnnotations(Extensions.class, visitor::visitExtensions, Extension.class);
processAnnotations(Extension.class, visitor::visitExtension, Extensions.class);
processAnnotations(Operation.class, visitor::visitOperation);
processAnnotations(Callback.class, visitor::visitCallback, Callbacks.class);
processAnnotations(Callbacks.class, visitor::visitCallbacks, Callback.class);
processAnnotations(APIResponse.class, visitor::visitAPIResponse, APIResponses.class);
processAnnotations(APIResponses.class, visitor::visitAPIResponses, APIResponse.class);
processAnnotations(Parameters.class, visitor::visitParameters, Parameter.class);
processAnnotations(Parameter.class, visitor::visitParameter, Parameters.class);
processAnnotations(ExternalDocumentation.class, visitor::visitExternalDocumentation);
processAnnotations(Tag.class, visitor::visitTag, Tags.class);
processAnnotations(Tags.class, visitor::visitTags, Tag.class);
processAnnotations(SecurityScheme.class, visitor::visitSecurityScheme, SecuritySchemes.class);
processAnnotations(SecuritySchemes.class, visitor::visitSecuritySchemes, SecurityScheme.class);
processAnnotations(SecurityRequirement.class, visitor::visitSecurityRequirement, SecurityRequirements.class);
processAnnotations(SecurityRequirements.class, visitor::visitSecurityRequirements, SecurityRequirement.class);
processAnnotations(types, Schema.class, visitor::visitSchema);
processAnnotations(types, Server.class, visitor::visitServer, Servers.class);
processAnnotations(types, Servers.class, visitor::visitServers, Server.class);
processAnnotations(types, Extensions.class, visitor::visitExtensions, Extension.class);
processAnnotations(types, Extension.class, visitor::visitExtension, Extensions.class);
processAnnotations(types, Operation.class, visitor::visitOperation);
processAnnotations(types, Callback.class, visitor::visitCallback, Callbacks.class);
processAnnotations(types, Callbacks.class, visitor::visitCallbacks, Callback.class);
processAnnotations(types, APIResponse.class, visitor::visitAPIResponse, APIResponses.class);
processAnnotations(types, APIResponses.class, visitor::visitAPIResponses, APIResponse.class);
processAnnotations(types, Parameters.class, visitor::visitParameters, Parameter.class);
processAnnotations(types, Parameter.class, visitor::visitParameter, Parameters.class);
processAnnotations(types, ExternalDocumentation.class, visitor::visitExternalDocumentation);
processAnnotations(types, Tag.class, visitor::visitTag, Tags.class);
processAnnotations(types, Tags.class, visitor::visitTags, Tag.class);
processAnnotations(types, SecurityScheme.class, visitor::visitSecurityScheme, SecuritySchemes.class);
processAnnotations(types, SecuritySchemes.class, visitor::visitSecuritySchemes, SecurityScheme.class);
processAnnotations(types, SecurityRequirement.class, visitor::visitSecurityRequirement, SecurityRequirements.class);
processAnnotations(types, SecurityRequirements.class, visitor::visitSecurityRequirements, SecurityRequirement.class);

// JAX-RS response types
processAnnotations(Produces.class, visitor::visitProduces);
processAnnotations(Consumes.class, visitor::visitConsumes);
processAnnotations(types, Produces.class, visitor::visitProduces);
processAnnotations(types, Consumes.class, visitor::visitConsumes);

// OpenAPI response types
processAnnotations(RequestBody.class, visitor::visitRequestBody);
processAnnotations(types, RequestBody.class, visitor::visitRequestBody);
//redo schema, now all others have been to ensure sub-schemas work
processAnnotations(Schema.class, visitor::visitSchema);
processAnnotations(types, Schema.class, visitor::visitSchema);
}

@SafeVarargs
private final <A extends Annotation, E extends AnnotatedElement> void processAnnotations(
Class<A> annotationClass, VisitorFunction<AnnotationModel, E> annotationFunction,
public final <A extends Annotation, E extends AnnotatedElement> void processAnnotations(
Set<Type> types,
Class<A> annotationClass,
VisitorFunction<AnnotationModel, E> annotationFunction,
Class<? extends Annotation>... alternatives) {

for (Type type : allowedTypes) {
if(type instanceof ClassModel) {
processAnnotation((ClassModel)type, annotationClass, annotationFunction, alternatives);
for (Type type : types) {
if (type instanceof ClassModel) {
processAnnotation((ClassModel) type, annotationClass, annotationFunction, alternatives);
}
}

}

@SafeVarargs
Expand All @@ -196,7 +201,7 @@ private final <A extends Annotation, E extends AnnotatedElement> void processAnn
Class<? extends Annotation>... alternatives) {
AnnotationInfo annotations = AnnotationInfo.valueOf(annotatedClass);
processAnnotation(annotatedClass, annotationClass, annotationFunction, annotations,
new OpenApiContext(allTypes, appClassLoader, api, getResourcePath(annotatedClass, resourceMapping)), alternatives);
new OpenApiContext(allTypes, allowedTypes, appClassLoader, api, getResourcePath(annotatedClass, resourceMapping)), alternatives);

for (final FieldModel field : annotatedClass.getFields()) {
if (annotations.isAnnotationPresent(annotationClass, field)) {
Expand All @@ -206,7 +211,7 @@ private final <A extends Annotation, E extends AnnotatedElement> void processAnn
|| annotationClass == QueryParam.class) {
// NB. if fields are annotated as Param all methods have it
for (MethodModel method : annotatedClass.getMethods()) {
OpenApiContext context = new OpenApiContext(allTypes, appClassLoader, api,
OpenApiContext context = new OpenApiContext(allTypes, allowedTypes, appClassLoader, api,
getResourcePath(method, resourceMapping),
getOperation(method, api, resourceMapping));
if (context.getWorkingOperation() != null) {
Expand All @@ -216,13 +221,13 @@ private final <A extends Annotation, E extends AnnotatedElement> void processAnn
}
} else {
processAnnotation(field, annotationClass, annotationFunction, annotations,
new OpenApiContext(allTypes, appClassLoader, api, null), alternatives);
new OpenApiContext(allTypes, allowedTypes, appClassLoader, api, null), alternatives);
}
}
}

for (final MethodModel method : annotatedClass.getMethods()) {
OpenApiContext context = new OpenApiContext(allTypes, appClassLoader, api,
OpenApiContext context = new OpenApiContext(allTypes, allowedTypes, appClassLoader, api,
getResourcePath(method, resourceMapping),
getOperation(method, api, resourceMapping));
processAnnotation(method, annotationClass, annotationFunction, annotations, context, alternatives);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) [2020] Payara Foundation and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://github.com/payara/Payara/blob/master/LICENSE.txt
* See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* The Payara Foundation designates this particular file as subject to the "Classpath"
* exception as provided by the Payara Foundation in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package fish.payara.microprofile.openapi.test.app.application;

import com.fasterxml.jackson.databind.JsonNode;
import fish.payara.microprofile.openapi.impl.visitor.OpenApiWalker;
import fish.payara.microprofile.openapi.test.app.OpenApiApplicationTest;
import fish.payara.microprofile.openapi.test.util.JsonUtils;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;

/**
* Testcase for Github issue #4334 where @Schema annotation not scanned if class
* file exist in external jar.
*
* In this test case {@link OpenApiWalker#allTypes} include TestApplication,
* ExternalSchemaExampleTest, and Student classes. And the
* {@link OpenApiWalker#allowedTypes} include TestApplication, and
* ExternalSchemaExampleTest classes. The {@link StudentDTO} class is dynamically
* picked from {@link OpenApiWalker#allTypes} for the Schema annotation scanning
* from metadata processor..
*
*/
@Path("/students")
public class ExternalSchemaExampleTest extends OpenApiApplicationTest {

@GET
@APIResponse(
description = "Get the Student information",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = StudentDTO.class)
)
)
public StudentDTO getStudent() {
return new StudentDTO();
}

@Test
public void fieldSchemaExampleIsRendered() {
JsonNode nameProperties = JsonUtils.path(getOpenAPIJson(), "components.schemas.Student.properties.name");
assertNotNull(nameProperties);
assertEquals("string", nameProperties.get("type").textValue());
assertEquals("the student name", nameProperties.get("description").textValue());
assertEquals("cuba", nameProperties.get("example").textValue());
}
}

@Schema(name = "Student", description = "POJO that represents a Student.")
class StudentDTO {

@Schema(name = "name", description = "the student name", example = "cuba")
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

0 comments on commit ecb2017

Please sign in to comment.