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 ReplaceAWTGetPeerMethod in Java 11 Migration #524

Merged
merged 24 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
61abfb8
getPeer() recipe
AnuRam123 Aug 1, 2024
f60b422
updated with fixes
AnuRam123 Aug 5, 2024
3c0e764
small updates
AnuRam123 Aug 5, 2024
6a4a5fa
Merge branch 'main' into recipe_detectAWTGetPeerMethod
ranuradh Aug 5, 2024
1bb77d2
Apply suggestions from code review
timtebeek Aug 5, 2024
3d1de0a
Apply suggestions from code review
timtebeek Aug 5, 2024
deb96c3
Apply formatter & order imports
timtebeek Aug 6, 2024
4e63d90
Align before and after code blocks again
timtebeek Aug 6, 2024
1d16fc4
updated recipe name, updated tests and formatted code
AnuRam123 Aug 6, 2024
1e26b14
removing extra file commit and test update
AnuRam123 Aug 6, 2024
1883f5d
adding comments, Test file cleanup
AnuRam123 Aug 6, 2024
c30aefb
Demonstrate the need for `super.visitControlParentheses(cp, ctx)`
timtebeek Aug 7, 2024
d1b97da
Only override `visitBinary` and `visitInstanceOf`
timtebeek Aug 7, 2024
6764297
Update src/test/java/org/openrewrite/java/migrate/ReplaceAWTGetPeerMe…
timtebeek Aug 7, 2024
b28d9bb
update to code and adding missing arguments to .yml
AnuRam123 Aug 8, 2024
94bc136
Merge branch 'main' into recipe_detectAWTGetPeerMethod
ranuradh Aug 8, 2024
5679678
right format for java-version.yml
AnuRam123 Aug 8, 2024
46b0c86
Merge branch 'main' into recipe_detectAWTGetPeerMethod
timtebeek Aug 9, 2024
13be5af
Remove import after instanceof replacement
timtebeek Aug 9, 2024
99801ef
Also handle flipped case
timtebeek Aug 9, 2024
694e592
Replace `checkClassNameIsEqualToFQCN` with TypeUtils
timtebeek Aug 9, 2024
e8247db
Remove duplication in arguments
timtebeek Aug 9, 2024
d2cce4f
Document options and shorten description
timtebeek Aug 9, 2024
e00a481
fixed small typo in description
AnuRam123 Aug 9, 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
Expand Up @@ -23,6 +23,7 @@
import org.openrewrite.xml.XmlVisitor;
import org.openrewrite.xml.tree.Xml;

import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toMap;
Expand Down
117 changes: 117 additions & 0 deletions src/main/java/org/openrewrite/java/migrate/DetectAWTGetPeerMethod.java
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.java.migrate;

import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
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.ChangeMethodName;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;

@Value
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor(access = AccessLevel.PACKAGE) // For tests
class DetectAWTGetPeerMethod extends Recipe {
ranuradh marked this conversation as resolved.
Show resolved Hide resolved
String methodPatternGetPeer;
String methodUpdateIsDisplayable;
String className;
String methodUpdateIsLightweight;

@Override
public String getDisplayName() {
return "Replace `getPeer()` method";
}

@Override
public String getDescription() {
return " All methods that refer to types defined in the java.awt.peer package are removed in Java 11. "
+ "This recipe replaces the use of getPeer() method in the java.awt.Component, java.awt.Font, and java.awt.MenuComponent classes and direct known subclasse."
+ "The occurrence of `(component.getPeer() != null) { .. }` is replaced with `(component.isDisplayable())` "
+ "and the occurrence of `(component.getPeer() instanceof LightweightPeer)` "
+ "is replaced with `(component.isLightweight())`.";
}

@JsonCreator
public DetectAWTGetPeerMethod() {
this.methodPatternGetPeer = "java.awt.* getPeer()";
this.methodUpdateIsDisplayable = "java.awt.* isDisplayable()";
this.className = "java.awt.peer.LightweightPeer";
this.methodUpdateIsLightweight = "java.awt.* isLightweight()";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesMethod<>(methodPatternGetPeer), new JavaVisitor<ExecutionContext>() {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
@Override
public <T extends J> J.ControlParentheses<T> visitControlParentheses(J.ControlParentheses<T> cp, ExecutionContext ctx) {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
Expression ifCExp = (Expression) cp.getTree();
//Check if there is a Binary or an instanceOf inside the paranthesis
if (!(ifCExp instanceof J.Binary) && !(ifCExp instanceof J.InstanceOf)) {
return cp;
}
if (ifCExp instanceof J.Binary) {
J.Binary binaryCondition = (J.Binary) ifCExp;
//check if(x.getPeer() != null)
if (binaryCondition.getLeft() instanceof J.MethodInvocation && binaryCondition.getRight() instanceof J.Literal && binaryCondition.getOperator().name().equals("NotEqual")) {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
J.MethodInvocation mi = (J.MethodInvocation) binaryCondition.getLeft();
J.Literal lt = (J.Literal) binaryCondition.getRight();
if (mi.getName().getSimpleName().equals("getPeer") && lt.getValueSource().equals("null")) {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
mi = (J.MethodInvocation) new ChangeMethodName(methodPatternGetPeer, "isDisplayable", true, null
).getVisitor().visit(mi, ctx);
mi = (J.MethodInvocation) new ChangeMethodInvocationReturnType(methodUpdateIsDisplayable, "boolean").getVisitor().visit(mi, ctx);
return cp.withTree((T) mi);
}
}
} else if (ifCExp instanceof J.InstanceOf) {
J.InstanceOf instanceOfVar = (J.InstanceOf) ifCExp;
if ((instanceOfVar.getExpression() instanceof J.MethodInvocation)) {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
J.MethodInvocation mi = ((J.MethodInvocation) instanceOfVar.getExpression());
if (mi.getName().getSimpleName().equals("getPeer") && checkClassNameIsEqualToFQCN(instanceOfVar)) {
mi = (J.MethodInvocation) new ChangeMethodName(methodPatternGetPeer, "isLightweight", true, null
).getVisitor().visit(mi, ctx);
mi = (J.MethodInvocation) new ChangeMethodInvocationReturnType(methodUpdateIsLightweight, "boolean").getVisitor().visit(mi, ctx);
return cp.withTree((T) mi);
}
}
}
return cp;
}
});
}

private boolean checkClassNameIsEqualToFQCN(J.InstanceOf instOf) {
if (instOf.getClazz() instanceof J.Identifier) {
J.Identifier id = (J.Identifier) instOf.getClazz();
return ((JavaType.Class) id.getType()).getFullyQualifiedName().toString().equals(className);
} else if (instOf.getClazz() instanceof J.FieldAccess) {
J.FieldAccess fid = (J.FieldAccess) instOf.getClazz();
return ((JavaType.Class) fid.getType()).getFullyQualifiedName().toString().equals(className);
} else {
return false;
}
}
}
4 changes: 2 additions & 2 deletions src/main/resources/META-INF/rewrite/java-version-11.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ recipeList:
- org.openrewrite.java.migrate.RemovedPolicy
- org.openrewrite.java.migrate.ReferenceCloneMethod
- org.openrewrite.java.migrate.ThreadStopDestroy

- org.openrewrite.java.migrate.DetectAWTGetPeerMethod
---
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.java.migrate.UpgradeBuildToJava11
Expand Down Expand Up @@ -281,4 +281,4 @@ recipeList:
fullyQualifiedTargetTypeName: java.nio.file.Path
- org.openrewrite.java.ChangeMethodName:
methodPattern: java.nio.file.Path get(..)
newMethodName: of
newMethodName: of
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* 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;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

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

class DetectAWTGetPeerMethodTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new DetectAWTGetPeerMethod(
"com.test.Component1 getPeer()",
"com.test.Component1 isDisplayable()",
"com.test.TestDummy",
"com.test.Component1 isLightweight()"))
.parser(JavaParser.fromJavaVersion()
//language=java
.dependsOn(
"""
package com.test;
public class Component1 {
public String getPeer() {
return "x";
}
public boolean getPeer1() {
return true;
}
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
public boolean isDisplayable() {
return true;
}
public boolean isLightweight() {
return true;
}
}
""",
"""
package com.test;
public class TestDummy {
}
"""
));
}


@DocumentExample
@Test
void instanceAndGetPeerMethod() {
rewriteRun(
//language=java
java(
"""
package com.test;
class Test extends TestDummy {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
public void foo() {
Test t1 = new Test();
Component1 c = new Component1();
if (c.getPeer() instanceof com.test.TestDummy) {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
}
if (c.getPeer() instanceof TestDummy) {
}
Component1 y = new Component1();
if (y.getPeer() != null) {
}
}
}
""",
"""
package com.test;
public class Test extends TestDummy {
public static void main(String args[]) {
Test t1 = new Test();
Component1 c = new Component1();
if (c.isLightweight()) {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
}
if (c.isLightweight()) {
}
Component1 y = new Component1();
if (y.isDisplayable()) {
}
}
}
"""
)
);
}
}
Loading