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,117 @@
/*
* 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.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.lang.NonNull;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.search.UsesJavaVersion;
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
public String getDisplayName() {
return "Add `@Serial` annotation to `serialVersionUID`";
}

@Override
public String getDescription() {
return "Annotation any `serialVersionUID` fields with `@Serial` to indicate it's part of the serialization mechanism.";
}

@Override
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(1);
}

@Override
@NonNull
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(
new UsesJavaVersion<>(14),
new JavaIsoVisitor<ExecutionContext>() {
@Override
@NonNull
public J.ClassDeclaration visitClassDeclaration(J.@NonNull ClassDeclaration classDecl, @NonNull ExecutionContext ctx) {
J.ClassDeclaration c = super.visitClassDeclaration(classDecl, ctx);
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();
long count = allAnnotations.stream().count();
AtomicBoolean hasSerialAnnotation = new AtomicBoolean(false);
for (J.Annotation annotation : allAnnotations) {
String simpleName = annotation.getSimpleName();
if (simpleName.equals("Serial")) {
hasSerialAnnotation.set(true);
}
}


for (J.VariableDeclarations.NamedVariable v : varDecls.getVariables()) {
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()) {
needsSerialAnnotation.set(false);
} else {
needsSerialAnnotation.set(true);
}
return s;
}
}
}
}
return s;
}
})));
if (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
maybeAddImport("java.io.Serial");
}
return c;
}
}
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* 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.DocumentExample;
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;

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

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

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;

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

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

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

@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;
class Outer implements Serializable {
private static final long serialVersionUID = 1;
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
Loading