-
Notifications
You must be signed in to change notification settings - Fork 80
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
Add Transient annotation to private accessor methods #425
Merged
Merged
Changes from 5 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
9d0ecdb
Initial implementation with test
evie-lau 7b13dc6
Polishing and add another test
evie-lau 8cb83a6
Check if the method return value is a field from the parent class
evie-lau 9c611b5
Merge branch 'main' into transientGetter
evie-lau e196629
Prevent applying annotation twice; add unhandled case
timtebeek 932ab06
Add test to show annotated field not changed again
timtebeek b975a34
Handle FieldAccess and Literal returns, add test for Literal
evie-lau a1092f7
Cleanup
evie-lau b0f9e2a
Merge branch 'main' into transientGetter
timtebeek 17c703c
Small improvements and comments
evie-lau c2a51b5
Merge branch 'main' into transientGetter
evie-lau 58893dd
Refactor, add test
evie-lau bf9dab1
Handle private accessor in inner class of an entity to match WAMT beh…
evie-lau ef81876
Fix test formatting
evie-lau 8720c86
Merge branch 'main' into transientGetter
evie-lau 2c72bf8
Merge branch 'main' into transientGetter
evie-lau 32a6cfe
Apply suggestions from code review
timtebeek f35e327
Merge branch 'main' into transientGetter
evie-lau f42384d
Add protected getter to test
evie-lau d0a9660
Check all returns in method for class field variables
evie-lau d6e3b11
Add complex logic test without field access
evie-lau 3479ecd
Refactor for efficiency
evie-lau 2613275
Add logic comments
evie-lau 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
106 changes: 106 additions & 0 deletions
106
...main/java/org/openrewrite/java/migrate/javax/AddTransientAnnotationToPrivateAccessor.java
This file contains 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,106 @@ | ||
/* | ||
* 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.java.migrate.javax; | ||
|
||
import lombok.EqualsAndHashCode; | ||
import lombok.Value; | ||
import org.openrewrite.ExecutionContext; | ||
import org.openrewrite.Preconditions; | ||
import org.openrewrite.Recipe; | ||
import org.openrewrite.TreeVisitor; | ||
import org.openrewrite.java.JavaIsoVisitor; | ||
import org.openrewrite.java.JavaParser; | ||
import org.openrewrite.java.JavaTemplate; | ||
import org.openrewrite.java.search.FindAnnotations; | ||
import org.openrewrite.java.search.UsesType; | ||
import org.openrewrite.java.tree.J; | ||
import org.openrewrite.java.tree.JavaType; | ||
|
||
import java.util.Comparator; | ||
|
||
@Value | ||
@EqualsAndHashCode(callSuper = false) | ||
public class AddTransientAnnotationToPrivateAccessor extends Recipe { | ||
|
||
@Override | ||
public String getDisplayName() { | ||
return "Private accessor methods must have a `@Transient` annotation"; | ||
} | ||
|
||
@Override | ||
public String getDescription() { | ||
return "According to the JPA 2.1 specification, when property access is used, the property accessor methods " + | ||
"must be public or protected. OpenJPA ignores any private accessor methods, whereas EclipseLink persists " + | ||
"those attributes. To ignore private accessor methods in EclipseLink, the methods must have a " + | ||
"`@Transient` annotation."; | ||
} | ||
|
||
|
||
@Override | ||
public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
return Preconditions.check( | ||
new UsesType<>("javax.persistence.Entity", true), | ||
new JavaIsoVisitor<ExecutionContext>() { | ||
@Override | ||
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { | ||
if (!FindAnnotations.find(classDecl, "javax.persistence.Entity").isEmpty()){ | ||
return super.visitClassDeclaration(classDecl, ctx); | ||
} | ||
// Exit if parent class is not tagged for JPA | ||
return classDecl; | ||
} | ||
|
||
@Override | ||
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration md, ExecutionContext ctx) { | ||
if (isPrivateAccessorMethodWithoutTransientAnnotation(md)) {// Add @Transient annotation | ||
maybeAddImport("javax.persistence.Transient"); | ||
return JavaTemplate.builder("@Transient") | ||
.contextSensitive() | ||
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "javax.persistence-api-2.2")) | ||
.imports("javax.persistence.Transient") | ||
.build() | ||
.apply(getCursor(), md.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName))); | ||
} | ||
return md; | ||
} | ||
|
||
private boolean isPrivateAccessorMethodWithoutTransientAnnotation(J.MethodDeclaration method) { | ||
return method.hasModifier(J.Modifier.Type.Private) | ||
&& method.getParameters().get(0) instanceof J.Empty | ||
&& method.getReturnTypeExpression().getType() != JavaType.Primitive.Void | ||
&& FindAnnotations.find(method, "javax.persistence.Transient").isEmpty() | ||
&& method.getBody().getStatements().get(0) instanceof J.Return | ||
&& methodReturnsFieldFromClass((J.Return) method.getBody().getStatements().get(0)); | ||
} | ||
|
||
/** | ||
* Check if the given method returns a field defined in the given class | ||
*/ | ||
private boolean methodReturnsFieldFromClass(J.Return returnStatement) { | ||
J.ClassDeclaration classDecl = getCursor().dropParentUntil(parent -> parent instanceof J.ClassDeclaration).getValue(); | ||
JavaType.Variable returnedVar = ((J.Identifier)returnStatement.getExpression()).getFieldType(); | ||
return classDecl.getBody().getStatements().stream() | ||
.filter(statement -> statement instanceof J.VariableDeclarations) | ||
.map(J.VariableDeclarations.class::cast) | ||
.map(J.VariableDeclarations::getVariables) | ||
.flatMap(vars -> vars.stream()) | ||
.map(var -> var.getName().getFieldType()) | ||
.anyMatch(var -> var.equals(returnedVar)); | ||
} | ||
} | ||
); | ||
} | ||
} | ||
evie-lau marked this conversation as resolved.
Show resolved
Hide resolved
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains 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
201 changes: 201 additions & 0 deletions
201
.../java/org/openrewrite/java/migrate/javax/AddTransientAnnotationToPrivateAccessorTest.java
This file contains 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,201 @@ | ||
/* | ||
* 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.java.migrate.javax; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import org.openrewrite.DocumentExample; | ||
import org.openrewrite.InMemoryExecutionContext; | ||
import org.openrewrite.java.JavaParser; | ||
import org.openrewrite.test.RecipeSpec; | ||
import org.openrewrite.test.RewriteTest; | ||
|
||
import static org.openrewrite.java.Assertions.java; | ||
|
||
class AddTransientAnnotationToPrivateAccessorTest implements RewriteTest { | ||
@Override | ||
public void defaults(RecipeSpec spec) { | ||
evie-lau marked this conversation as resolved.
Show resolved
Hide resolved
|
||
spec.parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(), "javax.persistence-api-2.2")) | ||
.recipe(new AddTransientAnnotationToPrivateAccessor()); | ||
} | ||
|
||
@DocumentExample | ||
@Test | ||
void addTransientToMethodReturningIdentifier() { | ||
//language=java | ||
rewriteRun( | ||
java( | ||
""" | ||
package entities; | ||
|
||
import javax.persistence.Entity; | ||
import javax.persistence.Id; | ||
|
||
@Entity | ||
public class PrivateAccessor { | ||
private int id; | ||
private int nonPersistentField; | ||
|
||
@Id | ||
public int getId() { | ||
return id; | ||
} | ||
|
||
private int getNonPersistentField() { | ||
return nonPersistentField; | ||
} | ||
} | ||
""", | ||
""" | ||
package entities; | ||
|
||
import javax.persistence.Entity; | ||
import javax.persistence.Id; | ||
import javax.persistence.Transient; | ||
|
||
@Entity | ||
public class PrivateAccessor { | ||
private int id; | ||
private int nonPersistentField; | ||
|
||
@Id | ||
public int getId() { | ||
return id; | ||
} | ||
|
||
@Transient | ||
private int getNonPersistentField() { | ||
return nonPersistentField; | ||
} | ||
} | ||
""" | ||
) | ||
); | ||
} | ||
|
||
@Test | ||
void addTransientToMethodReturningFieldAccess() { | ||
//language=java | ||
rewriteRun( | ||
java( | ||
""" | ||
package entities; | ||
|
||
import javax.persistence.Entity; | ||
import javax.persistence.Id; | ||
|
||
@Entity | ||
public class PrivateAccessor { | ||
private int id; | ||
private int nonPersistentField; | ||
|
||
@Id | ||
public int getId() { | ||
return id; | ||
} | ||
|
||
private int getNonPersistentField() { | ||
return this.nonPersistentField; | ||
} | ||
} | ||
""", | ||
""" | ||
package entities; | ||
|
||
import javax.persistence.Entity; | ||
import javax.persistence.Id; | ||
import javax.persistence.Transient; | ||
|
||
@Entity | ||
public class PrivateAccessor { | ||
private int id; | ||
private int nonPersistentField; | ||
|
||
@Id | ||
public int getId() { | ||
return id; | ||
} | ||
|
||
@Transient | ||
private int getNonPersistentField() { | ||
return this.nonPersistentField; | ||
} | ||
} | ||
""" | ||
) | ||
); | ||
} | ||
|
||
@Test | ||
void doNotChangePublicGetter() { | ||
//language=java | ||
rewriteRun( | ||
java( | ||
""" | ||
package entities; | ||
|
||
import javax.persistence.Entity; | ||
import javax.persistence.Id; | ||
|
||
@Entity | ||
public class PrivateAccessor { | ||
private int id; | ||
private int field; | ||
|
||
@Id | ||
public int getId() { | ||
return id; | ||
} | ||
|
||
public int getField() { | ||
return field; // Public method | ||
} | ||
} | ||
""" | ||
) | ||
); | ||
} | ||
|
||
|
||
@Test | ||
void doNotChangeVoidReturnType() { | ||
//language=java | ||
rewriteRun( | ||
java( | ||
""" | ||
package entities; | ||
|
||
import javax.persistence.Entity; | ||
import javax.persistence.Id; | ||
|
||
@Entity | ||
public class PrivateAccessor { | ||
private int id; | ||
private int field; | ||
|
||
@Id | ||
public int getId() { | ||
return id; | ||
} | ||
|
||
private void getField() { | ||
// void return type | ||
} | ||
} | ||
""" | ||
) | ||
); | ||
} | ||
} | ||
evie-lau marked this conversation as resolved.
Show resolved
Hide resolved
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure about matching on the field type here ; I'd expect we'd want to match that the identifier or accessed field name are the same as what's returned.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seemed like the Identifier sometimes had different object numbers when I was debugging, but getting it's FieldType object always matched up (which also contains the variable name).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the return expression can be a lot of things, but I imagine we'd only want to add an annotation when it's exactly an identifier or field access that references a field in the surrounding class; I think that were we were headed already right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For visual reference:
The J.Identifier object (
name
) didn't match up between the class's field Identifier and the method's returned Identifier.simpleName
andfieldType
were the highest level matches I found, and comparing the objects seemed like a better choice than comparing strings.