Skip to content

Add V1GetterToV2 Recipe #5260

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

Merged
merged 3 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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,97 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.migration.internal.recipe;

import static software.amazon.awssdk.migration.internal.utils.SdkTypeUtils.isV2ModelClass;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.migration.internal.utils.NamingUtils;

@SdkInternalApi
public class V1GetterToV2 extends Recipe {
@Override
public String getDisplayName() {
return "V1 Getter to V2";
}

@Override
public String getDescription() {
return "Transforms V1 getter to fluent getter in V2.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new V1GetterToV2Visitor();
}

private static class V1GetterToV2Visitor extends JavaIsoVisitor<ExecutionContext> {

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext executionContext) {
method = super.visitMethodInvocation(method, executionContext);

JavaType selectType;

Expression select = method.getSelect();

if (select == null || select.getType() == null) {
return method;
}
selectType = select.getType();

String methodName = method.getSimpleName();
JavaType.FullyQualified fullyQualified = TypeUtils.asFullyQualified(selectType);

if (!shouldChangeGetter(fullyQualified)) {
return method;
}

if (NamingUtils.isGetter(methodName)) {
methodName = NamingUtils.removeGet(methodName);
}

JavaType.Method methodType = method.getMethodType();

if (methodType != null) {
methodType = methodType.withName(methodName)
.withReturnType(selectType);

if (fullyQualified != null) {
methodType = methodType.withDeclaringType(fullyQualified);
}

method = method.withName(method.getName()
.withSimpleName(methodName)
.withType(methodType))
.withMethodType(methodType);
}

return method;
}

private static boolean shouldChangeGetter(JavaType.FullyQualified selectType) {
return isV2ModelClass(selectType);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ public static String removeSet(String name) {
return removePrefix(name, "set");
}

public static String removeGet(String name) {
return removePrefix(name, "get");
}

private static String removePrefix(String name, String prefix) {
if (StringUtils.isBlank(name)) {
return name;
Expand All @@ -53,4 +57,8 @@ public static boolean isWither(String name) {
public static boolean isSetter(String name) {
return !StringUtils.isBlank(name) && name.startsWith("set");
}

public static boolean isGetter(String name) {
return !StringUtils.isBlank(name) && name.startsWith("get");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,5 @@ recipeList:
# At this point, all classes should be changed to v2 equivalents
- software.amazon.awssdk.migration.recipe.V1BuilderVariationsToV2Builder
- software.amazon.awssdk.migration.recipe.NewClassToBuilderPattern
- software.amazon.awssdk.migration.recipe.NewClassToStaticFactory
- software.amazon.awssdk.migration.recipe.NewClassToStaticFactory
- software.amazon.awssdk.migration.internal.recipe.V1GetterToV2
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package software.amazon.awssdk.migration.recipe;

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

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.openrewrite.java.Java8Parser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;
import software.amazon.awssdk.migration.internal.recipe.V1GetterToV2;

public class V1GetterToV2Test implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec.recipes(new ChangeSdkType(), new NewClassToBuilderPattern(), new V1GetterToV2());
spec.parser(Java8Parser.builder().classpath("sqs",
"aws-java-sdk-sqs",
"sqs",
"sdk-core"));
}

@Test
@EnabledOnJre({JRE.JAVA_8})
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we write test cases something similar to

public void asyncClientClassAwsJson() {
AsyncClientClass asyncClientClass = createAsyncClientClass(awsJsonServiceModels(), false);
assertThat(asyncClientClass, generatesTo("test-aws-json-async-client-class.java"));
AsyncClientClass sraAsyncClientClass = createAsyncClientClass(awsJsonServiceModels(), true);
assertThat(sraAsyncClientClass, generatesTo("sra/test-aws-json-async-client-class.java"));
?

The benefits of this are

  1. Easy to read the output files as resource.java files
  2. Reusable for other test cases too, in the main test case we can just say
        assertThat(fluentGetterSetterMigrator, transformsTo("no-getter-setter-api.java"));

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Copy link
Contributor

Choose a reason for hiding this comment

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

In that case I guess its fine.
Thanks for sharing this.
Will check with @zoewangg if we can move the Hardcoded code to a resourceFiles via a refactoring PR

spec -> spec.parser(Java8Parser.builder().classpath("aws-java-sdk-sqs")),
            java(StringContentFromResourceFile

void v1ModelClassGetter_isRewrittenToFluent() {
rewriteRun(
java(
"import com.amazonaws.services.sqs.AmazonSQS;\n"
+ "import com.amazonaws.services.sqs.AmazonSQSClient;\n"
+ "import com.amazonaws.services.sqs.model.ReceiveMessageRequest;\n"
+ "import com.amazonaws.services.sqs.model.ReceiveMessageResult;\n"
+ "import com.amazonaws.services.sqs.model.Message;\n"
+ "\n"
+ "public class SqsExample {\n"
+ " public static void main(String[] args) {\n"
+ " AmazonSQS sqs = new AmazonSQSClient();\n"
+ " ReceiveMessageRequest request = new ReceiveMessageRequest().withQueueUrl(\"url\");\n"
+ " ReceiveMessageResult receiveMessage = sqs.receiveMessage(request);\n"
+ " List<Message> messages = receiveMessage.getMessages();\n"
+ " }\n"
+ "}\n",
"import software.amazon.awssdk.services.sqs.SqsClient;\n"
+ "import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;\n"
+ "import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse;\n"
+ "import software.amazon.awssdk.services.sqs.model.Message;\n"
+ "\n"
+ "public class SqsExample {\n"
+ " public static void main(String[] args) {\n"
+ " SqsClient sqs = SqsClient.builder().build();\n"
+ " ReceiveMessageRequest request = ReceiveMessageRequest.builder().queueUrl(\"url\").build();\n"
+ " ReceiveMessageResponse receiveMessage = sqs.receiveMessage(request);\n"
+ " List<Message> messages = receiveMessage.messages();\n"
+ " }\n"
+ "}"
)
);
}

@Test
@EnabledOnJre({JRE.JAVA_8})
void nonV1ModelClass_shouldNotChangeGetter() {
rewriteRun(
java(
"import java.util.Locale;\n"
+ "\n"
+ "public class NonV1ModelClassExample {\n"
+ " public static void main(String[] args) {\n"
+ " Locale locale = Locale.getDefault();\n"
+ " String path = System.getenv(\"PATH\");\n"
+ " String className = String.class.getName();\n"
+ " }\n"
+ "}\n",
"import java.util.Locale;\n"
+ "\n"
+ "public class NonV1ModelClassExample {\n"
+ " public static void main(String[] args) {\n"
+ " Locale locale = Locale.getDefault();\n"
+ " String path = System.getenv(\"PATH\");\n"
+ " String className = String.class.getName();\n"
+ " }\n"
+ "}"
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public static void main(String... args) {
.queueNamePrefix("MyQueue-")
.nextToken("token").build();
ListQueuesResponse listQueuesResult = sqs.listQueues(request);
String token = listQueuesResult.nextToken();
System.out.println(listQueuesResult);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public static void main(String... args) {
.withQueueNamePrefix("MyQueue-")
.withNextToken("token");
ListQueuesResult listQueuesResult = sqs.listQueues(request);
String token = listQueuesResult.getNextToken();
System.out.println(listQueuesResult);
}

Expand Down
Loading