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

Recipe AddSerialAnnotationToserialVersionUID #247

Merged
merged 10 commits into from
Jul 13, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* 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.staticanalysis;

import org.jetbrains.annotations.NotNull;
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
import org.openrewrite.ExecutionContext;
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.TreeVisitingPrinter;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Statement;
import org.openrewrite.java.tree.TypeUtils;

import java.time.Duration;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.UnaryOperator;

public class AddSerialAnnotationToserialVersionUID extends Recipe {



@Override
@NotNull
public String getDisplayName() {
System.out.println("Entering getDisplayName");
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
return "Add @Serial annotation to serialVersionUID";
}

@Override
@NotNull
public String getDescription() {
System.out.println("Entering getDescription");
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
return "Add a @Serial annotation above a serialVersionUID attribute identifier line.";
}

@Override
@NotNull
public Duration getEstimatedEffortPerOccurrence() {
System.out.println("Entering getEstimatedEffortPerOccurrence");
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
return Duration.ofMinutes(1);
}

@Override
@NotNull
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new JavaIsoVisitor<ExecutionContext>() {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved

@Override
@NotNull
public J.MethodDeclaration visitMethodDeclaration(J.@NotNull MethodDeclaration method, @NotNull ExecutionContext ctx) {
// Anonymous classes are not of interest
System.out.println("Entering visitMethodDeclaration Anonymous classes are not of interest");
return method;
}

@Override
@NotNull
public J.VariableDeclarations visitVariableDeclarations(J.@NotNull VariableDeclarations multiVariable, @NotNull ExecutionContext ctx) {
// Anonymous classes are not of interest
System.out.println("Entering visitVariableDeclarations (plural with an s) Anonymous classes are not of interest");
return multiVariable;
}

@Override
@NotNull
public J.ClassDeclaration visitClassDeclaration(J.@NotNull ClassDeclaration classDecl, @NotNull ExecutionContext ctx) {
System.out.println("\n\nEntering visitClassDeclaration");
System.out.println(TreeVisitingPrinter.printTree(getCursor()));

System.out.println("BEFORE calling 'super.visitClassDeclaration'");
J.ClassDeclaration c = super.visitClassDeclaration(classDecl, ctx);
System.out.println("AFTER calling 'super.visitClassDeclaration'");
if (c.getKind() != J.ClassDeclaration.Kind.Type.Class) {
return c;
}

AtomicBoolean needsSerialAnnotation = new AtomicBoolean(false);
c = c.withBody(c.getBody().withStatements(ListUtils.map(c.getBody().getStatements(), new UnaryOperator<Statement>() {
@Override
public Statement apply(Statement s) {
if (!(s instanceof J.VariableDeclarations)) {
return s;
}
J.VariableDeclarations varDecls = (J.VariableDeclarations) s;
// Yes I know deprecated: varDecls.getAllAnnotations()
List<J.Annotation> allAnnotations = varDecls.getAllAnnotations();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed elsewhere we've already adopted the annotation service; you'll want to look into that before we merge.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will be corrected if I still need it with the new approach visitVariableDeclarations() approach.

long count = allAnnotations.stream().count();
System.out.println("Nr of annotations: " + count);

timtebeek marked this conversation as resolved.
Show resolved Hide resolved
AtomicBoolean hasSerialAnnotation = new AtomicBoolean(false);
for (J.Annotation annotation : allAnnotations) {
String simpleName = annotation.getSimpleName();
System.out.println("Annotation name: " + simpleName);
if (simpleName.equals("Serial")) {
hasSerialAnnotation.set(true);
}
}


for (J.VariableDeclarations.NamedVariable v : varDecls.getVariables()) {
System.out.println("Variable: " + v.getSimpleName());
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
if ("serialVersionUID".equals(v.getSimpleName())) {

JavaType type = v.getType();

if (type instanceof JavaType.Primitive) {
if (TypeUtils.asPrimitive(v.getType()) == JavaType.Primitive.Long) {
if (hasSerialAnnotation.get()) {
System.out.println("Found serialVersionUID WITH @Serial annotation");
needsSerialAnnotation.set(false);
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
} else {
System.out.println("Found serialVersionUID");
needsSerialAnnotation.set(true);
}
return s;
}
}
}
}
return s;
}
})));
if (needsSerialAnnotation.get()) {
System.out.println("needsSerialAnnotation TRUE: " + needsSerialAnnotation.get());
c = JavaTemplate.apply("@Serial", getCursor(), c.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
// It HAS to be added. This method seems to be the easiest way to do it. Does NOT work
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
maybeAddImport("java.io.Serial");
} else {
System.out.println("needsSerialAnnotation FALSE: " + needsSerialAnnotation.get());
}
System.out.println("I believe this is the very end of all processing\n\n");
return c;
}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* 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.staticanalysis;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;

class AddSerialAnnotationToserialVersionUIDTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new AddSerialAnnotationToserialVersionUID());
}

@Test
void serialAnnotationAlreadyPresent() {
rewriteRun(
//language=java
java(
"""
import java.io.Serializable;
import java.io.Serial;

public class Example implements Serializable {
String var1 = "first variable";
@Serial
private static final long serialVersionUID = 1L;
int var3 = 666;
}
"""
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
)
);
}

@Disabled
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
@Test
void addSerialAnnotation() {
rewriteRun(
//language=java
java(
"""
import java.io.Serializable;
import java.io.Serial;

public class Example implements Serializable {
String var1 = "first variable";
private static final long serialVersionUID = 1L;
int var3 = 666;
}
""",
"""
import java.io.Serializable;
import java.io.Serial;

public class Example implements Serializable {
String var1 = "first variable";
@Serial
private static final long serialVersionUID = 1L;
int var3 = 666;
String wolvie = "wolverine";
}
"""
)
);
}


// Borowed from AddSerialVersionUidToSerializableTest of recipe AddSerialVersionUidToSerializableTest
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
@Disabled
@Test
void methodDeclarationsAreNotVisited() {
rewriteRun(
//language=java
java(
"""
import java.io.Serializable;

public class Example implements Serializable {
private String fred;
private int numberOfFreds;
void doSomething() {
long serialVersionUID = 1L;
}
}
"""
)
);
}

// Borowed from AddSerialVersionUidToSerializableTest of recipe AddSerialVersionUidToSerializableTest
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
@Disabled
@Test
void serializableInnerClass() {
rewriteRun(
//language=java
java(
"""
import java.io.Serializable;
public class Outer implements Serializable {
public static class Inner implements Serializable {
}
}
""",
"""
import java.io.Serializable;
public class Outer implements Serializable {
private static final long serialVersionUID = 1;
public static class Inner implements Serializable {
private static final long serialVersionUID = 1;
}
}
"""
)
);
}

}
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
timtebeek marked this conversation as resolved.
Show resolved Hide resolved