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

Add Transient annotation to private accessor methods #425

Merged
merged 23 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
9d0ecdb
Initial implementation with test
evie-lau Feb 22, 2024
7b13dc6
Polishing and add another test
evie-lau Feb 22, 2024
8cb83a6
Check if the method return value is a field from the parent class
evie-lau Feb 22, 2024
9c611b5
Merge branch 'main' into transientGetter
evie-lau Feb 23, 2024
e196629
Prevent applying annotation twice; add unhandled case
timtebeek Feb 24, 2024
932ab06
Add test to show annotated field not changed again
timtebeek Feb 24, 2024
b975a34
Handle FieldAccess and Literal returns, add test for Literal
evie-lau Feb 26, 2024
a1092f7
Cleanup
evie-lau Feb 26, 2024
b0f9e2a
Merge branch 'main' into transientGetter
timtebeek Feb 28, 2024
17c703c
Small improvements and comments
evie-lau Feb 28, 2024
c2a51b5
Merge branch 'main' into transientGetter
evie-lau Apr 10, 2024
58893dd
Refactor, add test
evie-lau Apr 10, 2024
bf9dab1
Handle private accessor in inner class of an entity to match WAMT beh…
evie-lau Apr 10, 2024
ef81876
Fix test formatting
evie-lau Apr 10, 2024
8720c86
Merge branch 'main' into transientGetter
evie-lau Apr 24, 2024
2c72bf8
Merge branch 'main' into transientGetter
evie-lau Apr 25, 2024
32a6cfe
Apply suggestions from code review
timtebeek Apr 26, 2024
f35e327
Merge branch 'main' into transientGetter
evie-lau Apr 27, 2024
f42384d
Add protected getter to test
evie-lau May 1, 2024
d0a9660
Check all returns in method for class field variables
evie-lau May 3, 2024
d6e3b11
Add complex logic test without field access
evie-lau May 3, 2024
3479ecd
Refactor for efficiency
evie-lau May 6, 2024
2613275
Add logic comments
evie-lau May 6, 2024
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
@@ -0,0 +1,126 @@
/*
* 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.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;

import java.util.*;
import java.util.stream.Collectors;

@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>() {
List<JavaType.Variable> classVars = new ArrayList<>();
@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
// Collect all class variables
classVars = classDecl.getBody().getStatements().stream()
.filter(J.VariableDeclarations.class::isInstance)
.map(J.VariableDeclarations.class::cast)
.map(J.VariableDeclarations::getVariables)
.flatMap(Collection::stream)
.map(var -> var.getName().getFieldType())
.filter(Objects::nonNull)
.collect(Collectors.toList());
return super.visitClassDeclaration(classDecl, ctx);
}

@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()
&& methodReturnsFieldFromClass(method);
}

/**
* Check if the given method returns a field defined in the parent class
*/
private boolean methodReturnsFieldFromClass(J.MethodDeclaration method) {
// Get all return values from method
List<JavaType.Variable> returns = new ArrayList<>();
JavaIsoVisitor<List<JavaType.Variable>> returnValueCollector = new JavaIsoVisitor<List<JavaType.Variable>>() {
@Override
public J.Return visitReturn(J.Return ret, List<JavaType.Variable> returnedVars) {
Expression expression = ret.getExpression();
JavaType.Variable returnedVar;
if (expression instanceof J.FieldAccess) { // ie: return this.field;
returnedVar = ((J.FieldAccess) expression).getName().getFieldType();
returnedVars.add(returnedVar);
} else if (expression instanceof J.Identifier) { // ie: return field;
returnedVar = ((J.Identifier) expression).getFieldType();
returnedVars.add(returnedVar);
} // last case should be null: do nothing and continue
return super.visitReturn(ret, returnedVars);
}
};
returnValueCollector.visitBlock(method.getBody(), returns);

// Check if any return values are a class field
return returns.stream().anyMatch(classVars::contains);
}
}
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ recipeList:
- org.openrewrite.java.migrate.javax.AddTableGenerator
- org.openrewrite.java.migrate.javax.AddTransientAnnotationToCollections
- org.openrewrite.java.migrate.javax.AddTransientAnnotationToEntity
- org.openrewrite.java.migrate.javax.AddTransientAnnotationToPrivateAccessor
- org.openrewrite.java.migrate.javax.RemoveEmbeddableId
- org.openrewrite.java.migrate.javax.RemoveTemporalAnnotation
- org.openrewrite.java.migrate.javax.UseJoinColumnForMapping
Expand Down
Loading