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

feat(openapi): interfaces properly generated #6497

Merged
merged 1 commit into from
Oct 25, 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 @@ -98,7 +98,7 @@ func processProtobufOneof(_ *generator.Context, pkg *types.Package, t *types.Typ
// Ensure it's exported
t.Members[memberIndex].Type.Name.Name = publicInterfaceName(m.Type.Name.Name)
//// Add comment tag to the referenced type and mark it as an interface
//t.Members[memberIndex].Type.CommentLines = append(m.Type.CommentLines, "+k8s:openapi-gen=x-kubernetes-fabric8-type:interface")
t.Members[memberIndex].Type.CommentLines = append(m.Type.CommentLines, "+k8s:openapi-gen=x-kubernetes-fabric8-type:interface")
// Add comment tag to the current type to mark it as it has fields that are interfaces (useful for the OpenAPI Java generator)
t.CommentLines = addOrAppend(t.CommentLines, "+k8s:openapi-gen=x-kubernetes-fabric8-interface-fields:", m.Name)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2015 Red Hat, Inc.
*
* 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
*
* http://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 io.fabric8.kubernetes.schema.generator.model;

import io.fabric8.kubernetes.schema.generator.ImportManager;
import io.fabric8.kubernetes.schema.generator.ImportOrderComparator;
import io.fabric8.kubernetes.schema.generator.schema.SchemaUtils;
import io.swagger.v3.oas.models.media.Schema;
import lombok.Getter;

import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

@Getter
public class ClassInformation implements ImportManager {

private final Set<String> imports;
private final String packageName;
private final boolean isInterface;
private final JsonSubTypes jsonSubTypes;

ClassInformation(SchemaUtils schemaUtils, Map.Entry<String, Schema<?>> clazz) {
imports = new TreeSet<>(new ImportOrderComparator());
final var classKey = clazz.getKey();
final var classSchema = clazz.getValue();
packageName = schemaUtils.toModelPackage(classKey.substring(0, classKey.lastIndexOf('.')));
isInterface = SchemaUtils.isInterface(classSchema);
if (isInterface) {
addImport("com.fasterxml.jackson.annotation.JsonSubTypes");
addImport("com.fasterxml.jackson.annotation.JsonTypeInfo");
addImport("com.fasterxml.jackson.databind.annotation.JsonTypeResolver");
jsonSubTypes = new JsonSubTypes(classSchema);
} else {
jsonSubTypes = null;
}
}

boolean isEditable() {
return !isInterface();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright (C) 2015 Red Hat, Inc.
*
* 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
*
* http://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 io.fabric8.kubernetes.schema.generator.model;

import io.fabric8.kubernetes.schema.generator.schema.SchemaUtils;
import io.swagger.v3.oas.models.media.Schema;
import lombok.Getter;

import java.util.List;

@Getter
public class JsonSubTypes {

private final List<String> subTypes;

JsonSubTypes(Schema<?> classSchema) {
this.subTypes = SchemaUtils.interfaceImplementation(classSchema);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ void generate() {

private void processTemplate(TemplateContext ret) {
ret.put("emptySpace", " "); // TODO: remove after generator migration, current workaround so that models match with jsonschema2pojo

ret.addAllImports(initDefaultImports());
if (ret.getApiVersion() != null) {
ret.addImport("io.fabric8.kubernetes.model.annotation.Version");
Expand Down Expand Up @@ -130,35 +129,45 @@ private void processTemplate(TemplateContext ret) {
deserializer = "com.fasterxml.jackson.databind.JsonDeserializer.None.class";
}
ret.put("classJsonDeserializeUsing", deserializer);
ret.addImport("com.fasterxml.jackson.annotation.JsonInclude");
ret.put("classJsonInclude", "NON_NULL");
if (!ret.getClassInformation().isInterface()) {
ret.addImport("com.fasterxml.jackson.annotation.JsonPropertyOrder");
ret.put("propertyOrder", SchemaUtils.propertyOrder(ret.getClassSchema()));
ret.addImport("lombok.ToString");
ret.put("lombokToString", true);
ret.addImport("lombok.EqualsAndHashCode");
ret.put("lombokEqualsAndHashCode", true);
ret.addImport("lombok.experimental.Accessors");
ret.put("lombokAccessors", true);
}
ret.put("package", ret.getPackageName());
if (settings.isGenerateJavadoc()) {
ret.put("hasDescription", !sanitizeDescription(ret.getClassSchema().getDescription()).trim().isEmpty());
ret.put("description", sanitizeDescription(ret.getClassSchema().getDescription()));
}
ret.addImport("com.fasterxml.jackson.annotation.JsonInclude");
ret.put("classJsonInclude", "NON_NULL");
ret.put("classInterface", ret.isInterface() ? "interface" : "class");
ret.put("classInterface", ret.getClassInformation().isInterface() ? "interface" : "class");
ret.put("className", ret.getClassSimpleName());
ret.put("implementsExtends", ret.isInterface() ? "extends" : "implements");
ret.put("implementsExtends", ret.getClassInformation().isInterface() ? "extends" : "implements");
ret.put("implementedInterfaces", resolveImplementedInterfaces(ret));
final List<Map<String, Object>> templateFields = templateFields(ret);
ret.put("fields", templateFields);
if (!templateFields.isEmpty()) {
ret.put("hasFields", true);
ret.addImport("com.fasterxml.jackson.annotation.JsonProperty");
}
ret.put("propertyOrder", SchemaUtils.propertyOrder(ret.getClassSchema()));
ret.put("editable", ret.getClassInformation().isEditable());
ret.put("builderPackage", settings.getBuilderPackage());
if (!ret.isInterface() && settings.isAddBuildableReferences()) {
if (!ret.getClassInformation().isInterface() && settings.isAddBuildableReferences()) {
ret.put("buildable", false);
ret.addImport("io.sundr.builder.annotations.Buildable");
ret.addImport("io.sundr.builder.annotations.BuildableReference");
ret.put("buildableReferences", buildableReferences(ret, templateFields));
} else if (!ret.isInterface()) {
} else if (!ret.getClassInformation().isInterface()) {
ret.addImport("io.sundr.builder.annotations.Buildable");
ret.put("buildable", true);
}
if (!ret.getSchemaProperties().containsKey("additionalProperties") && !ret.isInterface()) {
if (!ret.getSchemaProperties().containsKey("additionalProperties") && !ret.getClassInformation().isInterface()) {
ret.put("additionalProperties", true);
ret.addImport("java.util.LinkedHashMap");
ret.addImport("java.util.Map");
Expand Down Expand Up @@ -255,8 +264,8 @@ private Path resolvePackageDirectory(TemplateContext templateContext) {

private String resolveImplementedInterfaces(TemplateContext templateContext) {
final StringBuilder implementedInterfaces = new StringBuilder();
// Editable (all classes except interfaces)
if (!templateContext.isInterface()) {
if (templateContext.getClassInformation().isEditable()) {
templateContext.addImport("com.fasterxml.jackson.annotation.JsonIgnore");
templateContext.addImport(settings.getBuilderPackage() + "." + "Editable");
implementedInterfaces.append("Editable<").append(templateContext.getClassSimpleName()).append("Builder>");
implementedInterfaces.append(" , "); // TODO: weird comma introduced by jsonschema2pojo
Expand Down Expand Up @@ -333,12 +342,7 @@ private void writeFile(TemplateContext context, String fileContents) {
private static Set<String> initDefaultImports() {
return new HashSet<>(Arrays.asList(
"javax.annotation.Generated",
"com.fasterxml.jackson.annotation.JsonIgnore",
"com.fasterxml.jackson.annotation.JsonPropertyOrder",
"com.fasterxml.jackson.databind.annotation.JsonDeserialize",
"lombok.EqualsAndHashCode",
"lombok.ToString",
"lombok.experimental.Accessors"));
"com.fasterxml.jackson.databind.annotation.JsonDeserialize"));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,48 +18,44 @@
import io.fabric8.kubernetes.schema.generator.ApiVersion;
import io.fabric8.kubernetes.schema.generator.GeneratorSettings;
import io.fabric8.kubernetes.schema.generator.ImportManager;
import io.fabric8.kubernetes.schema.generator.ImportOrderComparator;
import io.fabric8.kubernetes.schema.generator.schema.SchemaUtils;
import io.swagger.v3.oas.models.media.Schema;
import lombok.Getter;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

@Getter
final class TemplateContext implements ImportManager {

private final String classKey;
private final Schema<?> classSchema;
private final ApiVersion apiVersion;
private final String packageName;
private final ClassInformation classInformation;
// TODO: Move to ClassInformation
private final boolean inRootPackage;
private final String classSimpleName;
private final String className;
private final boolean isInterface;
private final boolean hasMetadata;
private final String kubernetesListType;
private final Map<String, Object> context;
private final Set<String> imports;

TemplateContext(GeneratorSettings settings, Map.Entry<String, Schema<?>> clazz) {
final SchemaUtils schemaUtils = new SchemaUtils(settings);
classKey = clazz.getKey();
classSchema = clazz.getValue();
apiVersion = settings.getApiVersions().get(classKey);
packageName = schemaUtils.toModelPackage(classKey.substring(0, classKey.lastIndexOf('.')));
inRootPackage = packageName.equals(settings.getPackageName());
classInformation = new ClassInformation(schemaUtils, clazz);
inRootPackage = getClassInformation().getPackageName().equals(settings.getPackageName());
classSimpleName = SchemaUtils.refToClassName(classKey);
className = packageName + "." + classSimpleName;
isInterface = SchemaUtils.isInterface(classSchema);
imports = new TreeSet<>(new ImportOrderComparator());
className = getClassInformation().getPackageName() + "." + classSimpleName;
kubernetesListType = apiVersion == null ? null : schemaUtils.kubernetesListType(this, classSchema);
hasMetadata = apiVersion != null && kubernetesListType == null && schemaUtils.isHasMetadata(classSchema);
context = new HashMap<>();
context.put("imports", imports);
context.put("imports", classInformation.getImports());
context.put("classInformation", classInformation);
}

void put(String key, Object value) {
Expand All @@ -74,6 +70,16 @@ boolean isNamespaced() {
return getApiVersion() != null && getApiVersion().isNamespaced();
}

@Override
public String getPackageName() {
return getClassInformation().getPackageName();
}

@Override
public Collection<String> getImports() {
return getClassInformation().getImports();
}

@Override
public boolean hasSimpleClassName(String className) {
// If the provided class name matches the current class simple name it means that we'll need the fully
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,14 @@
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SchemaUtils {

Expand Down Expand Up @@ -270,6 +272,16 @@ public static Set<String> interfaceFields(Schema<?> schema) {
return Collections.emptySet();
}

public static List<String> interfaceImplementation(Schema<?> schema) {
if (schema.getExtensions() != null && schema.getExtensions().containsKey("x-kubernetes-fabric8-implementation")) {
return Stream.of(schema.getExtensions().get("x-kubernetes-fabric8-implementation").toString().split(","))
.map(SchemaUtils::refToClassName)
.sorted()
.collect(Collectors.toList());
}
return Collections.emptyList();
}

public static boolean isArray(Schema<?> schema) {
return schema instanceof ArraySchema;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,28 @@
{{#classJsonInclude}}
@JsonInclude(JsonInclude.Include.{{.}})
{{/classJsonInclude}}
@JsonPropertyOrder({
{{#propertyOrder}}
@JsonPropertyOrder({
{{#isEmpty}}

{{/isEmpty}}
{{#properties}}
"{{.}}"{{^-last}},{{/-last}}
{{/properties}}
{{/propertyOrder}}
})
{{/propertyOrder}}
{{#lombokToString}}
@ToString
{{/lombokToString}}
{{#lombokEqualsAndHashCode}}
@EqualsAndHashCode
{{/lombokEqualsAndHashCode}}
{{#lombokAccessors}}
@Accessors(prefix = {
"_",
""
})
{{/lombokAccessors}}
{{#buildable}}
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = "{{builderPackage}}")
{{/buildable}}
Expand All @@ -59,4 +65,13 @@
{{#group}}
{{.}}
{{/group}}
{{#classInformation.jsonSubTypes}}
@JsonTypeResolver(io.fabric8.kubernetes.model.jackson.UnwrappedTypeResolverBuilder.class)
@JsonSubTypes({
{{#subTypes}}
@JsonSubTypes.Type({{.}}.class),
{{/subTypes}}
})
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
{{/classInformation.jsonSubTypes}}
@Generated("jsonschema2pojo")
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
}

{{/fields}}
{{#editable}}
@JsonIgnore
public {{className}}Builder edit() {
return new {{className}}Builder(this);
Expand All @@ -58,6 +59,7 @@
return edit();
}

{{/editable}}
{{#additionalProperties}}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
Expand Down Expand Up @@ -116,8 +117,8 @@ void kubernetesListType_podList() {

@Test
void context() {
assertEquals(1, templateContext.getContext().size());
assertEquals(new HashSet<>(Collections.singletonList("imports")), templateContext.getContext().keySet());
assertEquals(2, templateContext.getContext().size());
assertEquals(new HashSet<>(List.of("imports", "classInformation")), templateContext.getContext().keySet());
}

@Test
Expand Down
Loading