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

Migrate @SwaggerDefinition to @OpenAPIDefinition #25

Merged
merged 9 commits into from
Jan 1, 2025
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
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-engine:latest.release")

testRuntimeOnly("io.swagger:swagger-annotations:1.6.13")
testRuntimeOnly("jakarta.ws.rs:jakarta.ws.rs-api:3.1.0")

testRuntimeOnly("org.gradle:gradle-tooling-api:latest.release")
}
45 changes: 45 additions & 0 deletions src/main/java/org/openrewrite/openapi/swagger/AnnotationUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.openapi.swagger;
SiBorea marked this conversation as resolved.
Show resolved Hide resolved
SiBorea marked this conversation as resolved.
Show resolved Hide resolved

import lombok.experimental.UtilityClass;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;

import java.util.HashMap;
import java.util.Map;

import static java.util.Collections.emptyMap;

@UtilityClass
class AnnotationUtils {
public static Map<String, Expression> extractAnnotationArgumentAssignments(J.Annotation annotation) {
if (annotation.getArguments() == null ||
annotation.getArguments().isEmpty() ||
annotation.getArguments().get(0) instanceof J.Empty) {
return emptyMap();
}
Map<String, Expression> map = new HashMap<>();
for (Expression expression : annotation.getArguments()) {
if (expression instanceof J.Assignment) {
J.Assignment a = (J.Assignment) expression;
String simpleName = ((J.Identifier) a.getVariable()).getSimpleName();
map.put(simpleName, a.getAssignment());
}
}
return map;
}
}
69 changes: 26 additions & 43 deletions src/main/java/org/openrewrite/openapi/swagger/MigrateApiToTag.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,9 @@
import org.openrewrite.java.tree.J;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.Collections.emptyMap;
import static java.util.Comparator.comparing;
import static java.util.Objects.requireNonNull;

Expand All @@ -42,31 +40,33 @@ public class MigrateApiToTag extends Recipe {
private static final String FQN_TAGS = "io.swagger.v3.oas.annotations.tags.Tags";

@Language("java")
private static final String TAGS_CLASS = "package io.swagger.v3.oas.annotations.tags;\n" +
"import java.lang.annotation.ElementType;\n" +
"import java.lang.annotation.Retention;\n" +
"import java.lang.annotation.RetentionPolicy;\n" +
"import java.lang.annotation.Target;\n" +
"@Target({ElementType.METHOD, ElementType.TYPE, ElementType.ANNOTATION_TYPE})\n" +
"@Retention(RetentionPolicy.RUNTIME)\n" +
"public @interface Tags {\n" +
" Tag[] value() default {};\n" +
"}";
private static final String TAGS_CLASS =
"package io.swagger.v3.oas.annotations.tags;\n" +
"import java.lang.annotation.ElementType;\n" +
"import java.lang.annotation.Retention;\n" +
"import java.lang.annotation.RetentionPolicy;\n" +
"import java.lang.annotation.Target;\n" +
"@Target({ElementType.METHOD, ElementType.TYPE, ElementType.ANNOTATION_TYPE})\n" +
"@Retention(RetentionPolicy.RUNTIME)\n" +
"public @interface Tags {\n" +
" Tag[] value() default {};\n" +
"}";

@Language("java")
private static final String TAG_CLASS = "package io.swagger.v3.oas.annotations.tags;\n" +
"import java.lang.annotation.ElementType;\n" +
"import java.lang.annotation.Repeatable;\n" +
"import java.lang.annotation.Retention;\n" +
"import java.lang.annotation.RetentionPolicy;\n" +
"import java.lang.annotation.Target;\n" +
"@Target({ElementType.METHOD, ElementType.TYPE, ElementType.ANNOTATION_TYPE})\n" +
"@Retention(RetentionPolicy.RUNTIME)\n" +
"@Repeatable(Tags.class)\n" +
"public @interface Tag {\n" +
" String name();\n" +
" String description() default \"\";\n" +
"}";
private static final String TAG_CLASS =
"package io.swagger.v3.oas.annotations.tags;\n" +
"import java.lang.annotation.ElementType;\n" +
"import java.lang.annotation.Repeatable;\n" +
"import java.lang.annotation.Retention;\n" +
"import java.lang.annotation.RetentionPolicy;\n" +
"import java.lang.annotation.Target;\n" +
"@Target({ElementType.METHOD, ElementType.TYPE, ElementType.ANNOTATION_TYPE})\n" +
"@Retention(RetentionPolicy.RUNTIME)\n" +
"@Repeatable(Tags.class)\n" +
"public @interface Tag {\n" +
" String name();\n" +
" String description() default \"\";\n" +
"}";

@Override
public String getDisplayName() {
Expand All @@ -89,7 +89,7 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
public J.@Nullable Annotation visitAnnotation(J.Annotation annotation, ExecutionContext ctx) {
J.Annotation ann = super.visitAnnotation(annotation, ctx);
if (apiMatcher.matches(ann)) {
Map<String, Expression> annotationArgumentAssignments = extractAnnotationArgumentAssignments(ann);
Map<String, Expression> annotationArgumentAssignments = AnnotationUtils.extractAnnotationArgumentAssignments(ann);
if (annotationArgumentAssignments.get("tags") != null) {
// Remove @Api and add @Tag or @Tags at class level
getCursor().putMessageOnFirstEnclosing(J.ClassDeclaration.class, FQN_API, annotationArgumentAssignments);
Expand All @@ -102,23 +102,6 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
return ann;
}

private Map<String, Expression> extractAnnotationArgumentAssignments(J.Annotation apiAnnotation) {
if (apiAnnotation.getArguments() == null ||
apiAnnotation.getArguments().isEmpty() ||
apiAnnotation.getArguments().get(0) instanceof J.Empty) {
return emptyMap();
}
Map<String, Expression> map = new HashMap<>();
for (Expression expression : apiAnnotation.getArguments()) {
if (expression instanceof J.Assignment) {
J.Assignment a = (J.Assignment) expression;
String simpleName = ((J.Identifier) a.getVariable()).getSimpleName();
map.put(simpleName, a.getAssignment());
}
}
return map;
}

@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.openapi.swagger;

import org.jspecify.annotations.Nullable;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.*;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MigrateSwaggerDefinitionToOpenAPIDefinition extends Recipe {

private static final String FQN_SWAGGER_DEFINITION = "io.swagger.annotations.SwaggerDefinition";
private static final String FQN_OPENAPI_DEFINITION = "io.swagger.v3.oas.annotations.OpenAPIDefinition";
private static final String FQN_SERVER = "io.swagger.v3.oas.annotations.servers.Server";

@Override
public String getDisplayName() {
return "Migrate from `@SwaggerDefinition` to `@OpenAPIDefinition`";
}

@Override
public String getDescription() {
return "Migrate from `@SwaggerDefinition` to `@OpenAPIDefinition`.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(
new UsesType<>(FQN_SWAGGER_DEFINITION, false),
new JavaIsoVisitor<ExecutionContext>() {
private final AnnotationMatcher annotationMatcher = new AnnotationMatcher(FQN_SWAGGER_DEFINITION);

@Override
public J.@Nullable Annotation visitAnnotation(J.Annotation annotation, ExecutionContext ctx) {
J.Annotation ann = super.visitAnnotation(annotation, ctx);

if (annotationMatcher.matches(ann)) {
Map<String, Expression> args = AnnotationUtils.extractAnnotationArgumentAssignments(ann);

StringBuilder tpl = new StringBuilder("@OpenAPIDefinition(\n");
List<Expression> tplArgs = new ArrayList<>();
List<String> parts = new ArrayList<>();

Expression basePath = args.get("basePath");
Expression host = args.get("host");
Expression schemes = args.get("schemes");
String servers = "";
if (basePath != null && host != null && schemes != null) {
tpl.append("servers = {\n");
if (schemes instanceof J.FieldAccess) {
servers += "@Server(url = \"" + ((J.FieldAccess) schemes).getSimpleName().toLowerCase() + "://" + host + basePath + "\")";
} else if (schemes instanceof J.NewArray) {
for (Expression scheme : ((J.NewArray) schemes).getInitializer()) {
if (!servers.isEmpty()) {
servers += ",\n";
}
String schemeName = ((J.FieldAccess) scheme).getSimpleName().toLowerCase();
servers += "@Server(url = \"" + schemeName + "://" + host + basePath + "\")";
}
}
servers += "\n}";
parts.add(servers);
}

args.remove("basePath");
args.remove("host");
args.remove("schemes");
args.remove("produces");
args.remove("consumes");
for (Map.Entry<String, Expression> arg : args.entrySet()) {
parts.add(arg.getKey() + " = #{any()}");
tplArgs.add(arg.getValue());
}
tpl.append(String.join(",\n", parts));
tpl.append("\n)");

ann = JavaTemplate.builder(tpl.toString())
.imports(FQN_OPENAPI_DEFINITION, FQN_SERVER)
.javaParser(JavaParser.fromJavaVersion().classpath("swagger-annotations"))
.build()
.apply(updateCursor(ann), ann.getCoordinates().replace(), tplArgs.toArray());
maybeRemoveImport(FQN_SWAGGER_DEFINITION);
maybeAddImport(FQN_OPENAPI_DEFINITION, false);
maybeAddImport(FQN_SERVER, false);
ann = maybeAutoFormat(annotation, ann, ctx);
}

doAfterVisit(new RemoveUnusedImports().getVisitor());
return ann;
}
}
);
}
}
4 changes: 4 additions & 0 deletions src/main/resources/META-INF/rewrite/swagger-2.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ recipeList:
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: io.swagger.annotations.Tag
newFullyQualifiedTypeName: io.swagger.v3.oas.annotations.tags.Tag
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: io.swagger.annotations.Info
newFullyQualifiedTypeName: io.swagger.v3.oas.annotations.info.Info
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: springfox.documentation.annotations.ApiIgnore
newFullyQualifiedTypeName: io.swagger.v3.oas.annotations.Hidden
Expand All @@ -53,6 +56,7 @@ recipeList:
- org.openrewrite.openapi.swagger.MigrateApiParamToParameter
- org.openrewrite.openapi.swagger.MigrateApiModelPropertyToSchema
- org.openrewrite.openapi.swagger.MigrateApiModelToSchema
- org.openrewrite.openapi.swagger.MigrateSwaggerDefinitionToOpenAPIDefinition

# todo add swagger-core to common-dependencies

Expand Down
Loading
Loading