-
Notifications
You must be signed in to change notification settings - Fork 129
Jax-RS to Spring MVC Recipe #903
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
Open
yasaswigadde
wants to merge
16
commits into
openrewrite:main
Choose a base branch
from
yasaswigadde:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,708
−147
Open
Changes from 2 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
b51b926
Jax-RS to Spring MVC Recipe
56fee71
Add license headers and apply formatter
timtebeek ad2cea2
Refactored for Java 8 Compatability
yasaswigadde 636c894
Merge branch 'main' into main
timtebeek e1eef05
Refactor - Minor Code Cleanup
yasaswigadde b2d27c4
Merge branch 'openrewrite:main' into main
yasaswigadde da5ec28
Merge branch 'openrewrite:main' into main
yasaswigadde 7be4343
Fixing Test Cases - Jax-RS to Spring MVC
yasaswigadde 4a2f617
Merge branch 'main' of https://github.com/yasaswigadde/rewrite-spring
yasaswigadde fb3b7a8
Minor Refactoring and Reformat
yasaswigadde 87519f7
Merge branch 'openrewrite:main' into main
yasaswigadde e6936c0
Merge branch 'main' of https://github.com/yasaswigadde/rewrite-spring
yasaswigadde c371ca4
Regenerate recipes.csv
timtebeek 92c78d3
Polish and regenerate type table
timtebeek df26dd8
Add missing preconditions
timtebeek 230a440
Merge branch 'main' into main
timtebeek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
290 changes: 290 additions & 0 deletions
290
src/main/java/org/openrewrite/java/spring/mvc/JaxrsToSpringmvcAnnotations.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,290 @@ | ||
| /* | ||
| * Copyright 2026 the original author or authors. | ||
| * <p> | ||
| * Licensed under the Moderne Source Available License (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://docs.moderne.io/licensing/moderne-source-available-license | ||
| * <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.java.spring.mvc; | ||
|
|
||
| import lombok.EqualsAndHashCode; | ||
| import lombok.Value; | ||
| import org.openrewrite.ExecutionContext; | ||
| import org.openrewrite.Recipe; | ||
| import org.openrewrite.TreeVisitor; | ||
| import org.openrewrite.java.*; | ||
| import org.openrewrite.java.tree.*; | ||
|
|
||
| import java.util.*; | ||
|
|
||
| @Value | ||
| @EqualsAndHashCode(callSuper = false) | ||
| public class JaxrsToSpringmvcAnnotations extends Recipe { | ||
|
|
||
| @Override | ||
| public String getDisplayName() { | ||
| return "Migrate jax-rs annotations to spring MVC annotations"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescription() { | ||
| return "Replaces all jax-rs annotations with Spring MVC annotations."; | ||
| } | ||
|
|
||
| @Override | ||
| public Set<String> getTags() { | ||
| return Set.of("Java", "Spring"); | ||
| } | ||
|
|
||
| private static final List<AnnotationMatcher> PATH_ANNOTATION_MATCHERS = List.of( | ||
yasaswigadde marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| new AnnotationMatcher("@jakarta.ws.rs.Path"), | ||
| new AnnotationMatcher("@javax.ws.rs.Path") | ||
| ); | ||
|
|
||
|
|
||
| private static final Map<String, String> ANNOTATION_MAPPING = Map.of( | ||
| "jakarta.ws.rs.GET", "GetMapping", | ||
| "jakarta.ws.rs.POST", "PostMapping", | ||
| "jakarta.ws.rs.PUT", "PutMapping", | ||
| "jakarta.ws.rs.DELETE", "DeleteMapping", | ||
| "javax.ws.rs.GET", "GetMapping", | ||
| "javax.ws.rs.POST", "PostMapping", | ||
| "javax.ws.rs.PUT", "PutMapping", | ||
| "javax.ws.rs.DELETE", "DeleteMapping" | ||
| ); | ||
|
|
||
| private static final Map<String, String> PARAM_ANNOTATION_MAPPING = Map.of( | ||
| "jakarta.ws.rs.QueryParam", "RequestParam", | ||
| "jakarta.ws.rs.FormParam", "RequestParam", | ||
| "jakarta.ws.rs.PathParam", "PathVariable", | ||
| "jakarta.ws.rs.HeaderParam", "RequestHeader", | ||
| "javax.ws.rs.QueryParam", "RequestParam", | ||
| "javax.ws.rs.FormParam", "RequestParam", | ||
| "javax.ws.rs.PathParam", "PathVariable", | ||
| "javax.ws.rs.HeaderParam", "RequestHeader" | ||
| ); | ||
|
|
||
| private static final String ANNOTATION_PREFIX = "org.springframework.web.bind.annotation."; | ||
|
|
||
| @Override | ||
| public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
| return new JavaIsoVisitor<ExecutionContext>() { | ||
|
|
||
| @Override | ||
| public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { | ||
| J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx); | ||
|
|
||
| List<String> annotationArgs = new ArrayList<>(); | ||
| List<Expression> args = new ArrayList<>(); | ||
| getArgumentsForRequestMappings(cd.getLeadingAnnotations(), annotationArgs, args); | ||
| if (annotationArgs.isEmpty()) { | ||
| return cd; | ||
| } | ||
| String annTemplate = "@RestController\n@RequestMapping(" + String.join(", ", annotationArgs) + ")"; | ||
|
|
||
| JavaCoordinates coordinates = cd.getCoordinates().addAnnotation((o1, o2) -> 1); | ||
| cd = JavaTemplate.builder(annTemplate) | ||
| .javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "spring-web")) | ||
| .imports("org.springframework.web.bind.annotation.RestController", | ||
| "org.springframework.web.bind.annotation.RequestMapping") | ||
| .build() | ||
| .apply(updateCursor(cd), coordinates, args.toArray()); | ||
| maybeAddImport("org.springframework.web.bind.annotation.RequestMapping"); | ||
| maybeAddImport("org.springframework.web.bind.annotation.RestController"); | ||
|
|
||
| return cd; | ||
| } | ||
|
|
||
| @Override | ||
| public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration md, ExecutionContext ctx) { | ||
| String jaxrsAnnotation = null; | ||
| for (String jaxrs : ANNOTATION_MAPPING.keySet()) { | ||
| Optional<J.Annotation> annOpt = md.getLeadingAnnotations().stream() | ||
| .filter(a -> TypeUtils.isOfClassType(a.getType(), jaxrs)) | ||
| .findFirst(); | ||
| if (annOpt.isPresent()) { | ||
| jaxrsAnnotation = jaxrs; | ||
| break; | ||
| } | ||
| } | ||
| if (jaxrsAnnotation == null) { | ||
| return md; | ||
| } | ||
| String springAnnotation = ANNOTATION_MAPPING.get(jaxrsAnnotation); | ||
| doAfterVisit(new RemoveAnnotationVisitor(new AnnotationMatcher("@" + jaxrsAnnotation))); | ||
| maybeRemoveImport(jaxrsAnnotation); | ||
|
|
||
| List<String> annotationArgs = new ArrayList<>(); | ||
| List<Expression> args = new ArrayList<>(); | ||
| Expression consumes = getArgumentsForRequestMappings(md.getLeadingAnnotations(), annotationArgs, args); | ||
| String annTemplate; | ||
| if (annotationArgs.isEmpty()) { | ||
| annTemplate = "@" + springAnnotation; | ||
| } else { | ||
| annTemplate = "@" + springAnnotation + "(" + String.join(", ", annotationArgs) + ")"; | ||
| } | ||
|
|
||
|
|
||
| JavaCoordinates coordinates = md.getCoordinates().addAnnotation((o1, o2) -> 1); | ||
| md = JavaTemplate.builder(annTemplate) | ||
| .javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "spring-web")) | ||
| .imports(ANNOTATION_PREFIX + springAnnotation) | ||
| .build() | ||
| .apply(updateCursor(md), coordinates, args.toArray()); | ||
| maybeAddImport(ANNOTATION_PREFIX + springAnnotation); | ||
|
|
||
| getCursor().putMessage("methodParams", md.getParameters()); | ||
| getCursor().putMessage("isPutOrPost", jaxrsAnnotation.endsWith("PUT") || jaxrsAnnotation.endsWith("POST")); | ||
| getCursor().putMessage("needRequestPart", isMultiPart(consumes)); | ||
| return super.visitMethodDeclaration(md, ctx); | ||
| } | ||
|
|
||
| @Override | ||
| public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations variableDecl, ExecutionContext ctx) { | ||
| J.VariableDeclarations vd = super.visitVariableDeclarations(variableDecl, ctx); | ||
|
|
||
| List<Statement> methodParams = getCursor().getNearestMessage("methodParams"); | ||
| if (methodParams == null || !methodParams.contains(vd)) { | ||
| return vd; | ||
| } | ||
|
|
||
| String springAnnotation = null; | ||
| Expression value = null; | ||
| Expression defaultValue = null; | ||
| boolean isPutOrPost = Boolean.TRUE.equals(getCursor().getNearestMessage("isPutOrPost")); | ||
| boolean needRequestPart = Boolean.TRUE.equals(getCursor().getNearestMessage("needRequestPart")); | ||
| boolean isContextParam = false; | ||
| for (J.Annotation ann : vd.getLeadingAnnotations()) { | ||
| String annType = ann.getType() != null ? ann.getType().toString() : ""; | ||
| if (PARAM_ANNOTATION_MAPPING.containsKey(annType)) { | ||
| springAnnotation = PARAM_ANNOTATION_MAPPING.get(annType); | ||
| value = getValueFromAnnotation(ann); | ||
| doAfterVisit(new RemoveAnnotationVisitor(new AnnotationMatcher("@" + annType))); | ||
| maybeRemoveImport(annType); | ||
| } else if (annType.equals("jakarta.ws.rs.DefaultValue") || annType.equals("javax.ws.rs.DefaultValue")) { | ||
| defaultValue = getValueFromAnnotation(ann); | ||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| doAfterVisit(new RemoveAnnotationVisitor(new AnnotationMatcher("@" + annType))); | ||
| maybeRemoveImport(annType); | ||
| } else if (annType.equals("jakarta.ws.rs.core.Context") || annType.equals("javax.ws.rs.core.Context")) { | ||
| isContextParam = true; | ||
| doAfterVisit(new RemoveAnnotationVisitor(new AnnotationMatcher("@" + annType))); | ||
| maybeRemoveImport(annType); | ||
| } | ||
| } | ||
|
|
||
| StringBuilder annBuilder = null; | ||
| List<Expression> args = new ArrayList<>(); | ||
| if (springAnnotation != null) { | ||
| args.add(value); | ||
| annBuilder = new StringBuilder("@" + springAnnotation + "("); | ||
| if (springAnnotation.equals("PathVariable")) { | ||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| annBuilder.append("#{any(String)})"); | ||
| } else { | ||
| if (defaultValue == null) { | ||
| annBuilder.append("value = #{any(String)}, required = false)"); | ||
| } else { | ||
| annBuilder.append("value = #{any(String)}, defaultValue = #{any()})"); | ||
| args.add(defaultValue); | ||
| } | ||
| } | ||
| } else if (!isContextParam && isPutOrPost) { | ||
| if (needRequestPart) { | ||
| springAnnotation = "RequestPart"; | ||
| } else { | ||
| springAnnotation = "RequestBody"; | ||
| } | ||
| annBuilder = new StringBuilder("@" + springAnnotation); | ||
| } | ||
| if (annBuilder != null) { | ||
| JavaCoordinates coordinates = vd.getCoordinates().addAnnotation((o1, o2) -> 1); | ||
| vd = JavaTemplate.builder(annBuilder.toString()) | ||
| .javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "spring-web")) | ||
| .imports(ANNOTATION_PREFIX + springAnnotation) | ||
| .build() | ||
| .apply(updateCursor(vd), coordinates, args.toArray()); | ||
| maybeAddImport(ANNOTATION_PREFIX + springAnnotation); | ||
| } | ||
|
|
||
| return vd; | ||
| } | ||
|
|
||
| private Expression getArgumentsForRequestMappings(List<J.Annotation> annotations, List<String> annotationArgs, List<Expression> args) { | ||
| Expression path = null; | ||
| Expression produces = null; | ||
| Expression consumes = null; | ||
|
|
||
| for (J.Annotation ann : annotations) { | ||
| String annType = ann.getType() != null ? ann.getType().toString() : ""; | ||
| if (annType.equals("jakarta.ws.rs.Path") || annType.equals("javax.ws.rs.Path")) { | ||
| path = getValueFromAnnotation(ann); | ||
| doAfterVisit(new RemoveAnnotationVisitor(new AnnotationMatcher("@" + annType))); | ||
| maybeRemoveImport(annType); | ||
| } else if (annType.equals("jakarta.ws.rs.Consumes") || annType.equals("javax.ws.rs.Consumes")) { | ||
| consumes = getValueFromAnnotation(ann); | ||
| doAfterVisit(new RemoveAnnotationVisitor(new AnnotationMatcher("@" + annType))); | ||
| maybeRemoveImport(annType); | ||
| } else if (annType.equals("jakarta.ws.rs.Produces") || annType.equals("javax.ws.rs.Produces")) { | ||
| produces = getValueFromAnnotation(ann); | ||
| doAfterVisit(new RemoveAnnotationVisitor(new AnnotationMatcher("@" + annType))); | ||
| maybeRemoveImport(annType); | ||
| } | ||
| } | ||
|
|
||
| if (path != null && produces == null && consumes == null) { | ||
| annotationArgs.add("#{any(String)}"); | ||
| args.add(path); | ||
| } else { | ||
| if (path != null) { | ||
| annotationArgs.add("value = #{any(String)}"); | ||
| args.add(path); | ||
| } | ||
| if (produces != null) { | ||
| annotationArgs.add("produces = #{any()}"); | ||
| args.add(produces); | ||
| } | ||
| if (consumes != null) { | ||
| annotationArgs.add("consumes = #{any()}"); | ||
| args.add(consumes); | ||
| } | ||
| } | ||
|
|
||
| return consumes; | ||
| } | ||
|
|
||
| private Expression getValueFromAnnotation(J.Annotation ann) { | ||
| if (ann.getArguments() == null || ann.getArguments().isEmpty()) { | ||
| return null; | ||
| } | ||
| Expression arg = ann.getArguments().get(0); | ||
| if (arg instanceof J.Assignment assign) { | ||
| return assign.getAssignment(); | ||
| } else { | ||
| return arg; | ||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| private boolean isMultiPart(Expression consumes) { | ||
| if (consumes == null) { | ||
| return false; | ||
| } | ||
| if (consumes instanceof J.NewArray arr) { | ||
| if (arr.getInitializer().size() == 1) { | ||
| consumes = arr.getInitializer().get(0); | ||
| } else { | ||
| return false; | ||
| } | ||
| } | ||
| return consumes.toString().toLowerCase().contains("multipart"); | ||
| } | ||
|
|
||
| }; | ||
| } | ||
| } | ||
84 changes: 84 additions & 0 deletions
84
src/main/java/org/openrewrite/java/spring/mvc/JaxrsToSpringmvcMediaType.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| /* | ||
| * Copyright 2026 the original author or authors. | ||
| * <p> | ||
| * Licensed under the Moderne Source Available License (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://docs.moderne.io/licensing/moderne-source-available-license | ||
| * <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.java.spring.mvc; | ||
|
|
||
| import lombok.EqualsAndHashCode; | ||
| import lombok.Value; | ||
| import org.openrewrite.ExecutionContext; | ||
| import org.openrewrite.Recipe; | ||
| import org.openrewrite.TreeVisitor; | ||
| import org.openrewrite.java.ChangeType; | ||
| import org.openrewrite.java.JavaIsoVisitor; | ||
| import org.openrewrite.java.JavaParser; | ||
| import org.openrewrite.java.JavaTemplate; | ||
| import org.openrewrite.java.tree.J; | ||
| import org.openrewrite.java.tree.JavaCoordinates; | ||
|
|
||
| import java.util.Set; | ||
|
|
||
| @Value | ||
| @EqualsAndHashCode(callSuper = false) | ||
| public class JaxrsToSpringmvcMediaType extends Recipe { | ||
|
|
||
| @Override | ||
| public String getDisplayName() { | ||
| return "Migrate jax-rs MediaType to spring MVC MediaType"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescription() { | ||
yasaswigadde marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return "Replaces all jax-rs MediaType with Spring MVC MediaType."; | ||
| } | ||
|
|
||
| @Override | ||
| public Set<String> getTags() { | ||
| return Set.of("Java", "Spring"); | ||
| } | ||
|
|
||
| @Override | ||
| public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
| return new JavaIsoVisitor<ExecutionContext>() { | ||
|
|
||
| @Override | ||
| public J.CompilationUnit visitCompilationUnit(J.CompilationUnit compilationUnit, ExecutionContext ctx) { | ||
| doAfterVisit(new ChangeType("javax.ws.rs.core.MediaType", "org.springframework.http.MediaType", true).getVisitor()); | ||
| doAfterVisit(new ChangeType("jakarta.ws.rs.core.MediaType", "org.springframework.http.MediaType", true).getVisitor()); | ||
| return super.visitCompilationUnit(compilationUnit, ctx); | ||
| } | ||
|
|
||
| @Override | ||
| public J.FieldAccess visitFieldAccess(J.FieldAccess fieldAccess, ExecutionContext ctx) { | ||
| String typeName = fieldAccess.getTarget().getType() != null ? fieldAccess.getTarget().getType().toString() : ""; | ||
| if (typeName.equals("javax.ws.rs.core.MediaType") || typeName.equals("jakarta.ws.rs.core.MediaType")) { | ||
timtebeek marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| maybeRemoveImport(typeName); | ||
| maybeAddImport("org.springframework.http.MediaType"); | ||
|
|
||
| String field = fieldAccess.getName().getSimpleName(); | ||
| String newField = field.endsWith("_TYPE") ? field.substring(0, field.length() - "_TYPE".length()) : field + "_VALUE"; | ||
| JavaCoordinates coordinates = fieldAccess.getCoordinates().replace(); | ||
| return JavaTemplate.builder("MediaType.#{}") | ||
| .javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "spring-web")) | ||
| .imports("org.springframework.http.MediaType") | ||
| .build() | ||
| .apply(getCursor(), coordinates, newField); | ||
| } | ||
| return super.visitFieldAccess(fieldAccess, ctx); | ||
| } | ||
|
|
||
| }; | ||
| } | ||
|
|
||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.