Skip to content

Add ConstructorToFluent recipe #5145

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
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
18 changes: 18 additions & 0 deletions migration-tool/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,18 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<scope>test</scope>
<version>1.12.472</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.openrewrite</groupId>
<artifactId>rewrite-maven</artifactId>
Expand All @@ -89,6 +101,12 @@
<version>${junit5.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>utils</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
/*
* 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 com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.Tree;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JContainer;
import org.openrewrite.java.tree.JRightPadded;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Space;
import org.openrewrite.java.tree.TypeUtils;
import org.openrewrite.marker.Markers;
import software.amazon.awssdk.annotations.SdkInternalApi;

@SdkInternalApi
public class ConstructorToFluent extends Recipe {
private final String clzzFqcn;
private final List<String> parameterTypes;
private final List<String> fluentNames;

@JsonCreator
public ConstructorToFluent(@JsonProperty("clzzFqcn") String clzzFqcn,
@JsonProperty("parameterTypes") List<String> parameterTypes,
@JsonProperty("fluentNames") List<String> fluentNames) {
this.clzzFqcn = clzzFqcn;
this.parameterTypes = parameterTypes;
this.fluentNames = fluentNames;

if (fluentNames.size() != parameterTypes.size()) {
throw new IllegalArgumentException("parameterTypes and fluentNames must be the same length.");
}
}

@Override
public String getDisplayName() {
return "Moves constructor arguments to fluent setters";
}

@Override
public String getDescription() {
return "A recipe that takes constructor arguments and moves them to the specified fluent setters on the object.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
List<JavaType> paramJavaTypes = parameterTypes.stream()
.map(JavaType::buildType)
.collect(Collectors.toList());
return new Visitor(clzzFqcn, paramJavaTypes, fluentNames);
}

private static class Visitor extends JavaVisitor<ExecutionContext> {
private final JavaType.FullyQualified clzz;
private final List<JavaType> parameterTypes;
private final List<String> fluentNames;

Visitor(String clzz, List<JavaType> parameterTypes, List<String> fluentNames) {
this.clzz = TypeUtils.asFullyQualified(JavaType.buildType(clzz));
this.parameterTypes = parameterTypes;
this.fluentNames = fluentNames;
}

@Override
public J visitNewClass(J.NewClass newClass, ExecutionContext executionContext) {
JavaType.Method ctorType = newClass.getMethodType();

if (ctorType == null) {
return newClass;
}

if (!clzz.isAssignableFrom(ctorType.getDeclaringType())) {
return newClass;
}

List<JavaType> paramTypes = ctorType.getParameterTypes();

if (paramTypes.size() != this.parameterTypes.size()) {
return newClass;
}

for (int i = 0; i < parameterTypes.size(); ++i) {
JavaType expected = this.parameterTypes.get(i);
if (!TypeUtils.isAssignableTo(expected, paramTypes.get(i))) {
return newClass;
}
}

// Remove all the arguments from the constructor
List<Expression> arguments = newClass.getArguments();

ctorType = ctorType.withParameterTypes(Collections.emptyList())
.withParameterNames(Collections.emptyList());

newClass = newClass.withArguments(Collections.emptyList())
.withMethodType(ctorType);

JavaType.FullyQualified declaringType = ctorType.getDeclaringType();
Expression select = newClass;
for (int i = 0; i < parameterTypes.size(); ++i) {
JavaType paramType = parameterTypes.get(i);
String name = fluentNames.get(i);
// Note we don't preserve prefix so we don't end up with
// extra spaces after the opening paren like 'withFoo( arg)'
Expression argExpr = arguments.get(i).withPrefix(Space.EMPTY);

select = addWither(select, name, paramType, argExpr, declaringType);
}

return select;
}

private static J.MethodInvocation addWither(Expression select, String simpleName,
JavaType parameterType,
Expression paramExpr,
JavaType.FullyQualified declaringType) {
JavaType.Method methodType = new JavaType.Method(
null,
0L,
declaringType,
simpleName,
declaringType,
Collections.singletonList(simpleName),
Collections.singletonList(parameterType),
null,
null
);

J.Identifier witherId = new J.Identifier(
Tree.randomId(),
Space.EMPTY,
Markers.EMPTY,
Collections.emptyList(),
simpleName,
methodType,
null
);

return new J.MethodInvocation(
Tree.randomId(),
Space.EMPTY,
Markers.EMPTY,
JRightPadded.build(select),
null,
witherId,
JContainer.build(Collections.singletonList(JRightPadded.build(paramExpr))),
methodType
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
* 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.openrewrite.java.Assertions.java;

import java.util.Arrays;
import java.util.Collections;
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;

/**
* Recipe that remaps invocations of model constructors that take some members as constructor parameters, so that the
* parameters are specified using the fluent setter for the member instead.
*/
public class ConstructorToFluentTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec.parser(Java8Parser.builder().classpath(
"aws-java-sdk-s3",
"aws-java-sdk-core",
"s3",
"sdk-core"));
spec.recipe(new ConstructorToFluent("com.amazonaws.services.s3.model.GetObjectRequest",
Arrays.asList("java.lang.String", "java.lang.String"),
Arrays.asList("withBucketName", "withKey")));

}

@Test
public void newRecipe_listsNotMatch_throws() {
assertThatThrownBy(() -> new ConstructorToFluent("foo",
Collections.emptyList(),
Collections.singletonList("bar")))
.isInstanceOf(IllegalArgumentException.class);

assertThatThrownBy(() -> new ConstructorToFluent("foo",
Collections.singletonList("bar"),
Collections.emptyList()))
.isInstanceOf(IllegalArgumentException.class);
}



@Test
@EnabledOnJre({JRE.JAVA_8})
public void getObjectRequest_matchingCtorNotFound_doesNotRewrite() {
rewriteRun(
java("import com.amazonaws.services.s3.AmazonS3;\n"
+ "import com.amazonaws.services.s3.model.GetObjectRequest;\n"
+ "import com.amazonaws.services.s3.model.S3Object;\n"
+ "import com.amazonaws.services.s3.model.S3ObjectInputStream;\n"
+ "\n"
+ "public class S3Example {\n"
+ " public static void main(String[] args) {\n"
+ " AmazonS3 s3 = null;\n"
+ "\n"
+ " GetObjectRequest getObject = new GetObjectRequest(\"bucket\", \"key\", \"version\");\n"
+ "\n"
+ " S3Object object = s3.getObject(getObject);\n"
+ "\n"
+ " S3ObjectInputStream objectContent = object.getObjectContent();\n"
+ " }\n"
+ "}\n",
sourceSpecs -> {}
)
);
}

@Test
@EnabledOnJre({JRE.JAVA_8})
public void getObjectRequest_bucketKeyCtor_convertedToFluent() {
rewriteRun(
java(
"import com.amazonaws.services.s3.AmazonS3;\n"
+ "import com.amazonaws.services.s3.model.GetObjectRequest;\n"
+ "import com.amazonaws.services.s3.model.S3Object;\n"
+ "\n"
+ "public class S3Example {\n"
+ " public static void main(String[] args) {\n"
+ " AmazonS3 s3 = null;\n"
+ "\n"
+ " GetObjectRequest getObject = new GetObjectRequest(\"bucket\", \"key\");\n"
+ "\n"
+ " S3Object object = s3.getObject(getObject);\n"
+ " }\n"
+ "}\n",
"import com.amazonaws.services.s3.AmazonS3;\n"
+ "import com.amazonaws.services.s3.model.GetObjectRequest;\n"
+ "import com.amazonaws.services.s3.model.S3Object;\n"
+ "\n"
+ "public class S3Example {\n"
+ " public static void main(String[] args) {\n"
+ " AmazonS3 s3 = null;\n"
+ "\n"
+ " GetObjectRequest getObject = new GetObjectRequest().withBucketName(\"bucket\").withKey(\"key\");\n"
+ "\n"
+ " S3Object object = s3.getObject(getObject);\n"
+ " }\n"
+ "}"
)
);
}

// RequesterPays is a boolean primitive type, test to ensure the type matching can handle this
@Test
@EnabledOnJre({JRE.JAVA_8})
public void getObjectRequest_bucketKeyRequesterPays_convertedToFluent() {
rewriteRun(
spec -> spec.recipe(new ConstructorToFluent("com.amazonaws.services.s3.model.GetObjectRequest",
Arrays.asList("java.lang.String", "java.lang.String", "boolean"),
Arrays.asList("withBucketName", "withKey", "withRequesterPays"))),
java(
"import com.amazonaws.services.s3.AmazonS3;\n"
+ "import com.amazonaws.services.s3.model.GetObjectRequest;\n"
+ "import com.amazonaws.services.s3.model.S3Object;\n"
+ "\n"
+ "public class S3Example {\n"
+ " public static void main(String[] args) {\n"
+ " AmazonS3 s3 = null;\n"
+ "\n"
+ " GetObjectRequest getObject = new GetObjectRequest(\"bucket\", \"key\", false);\n"
+ "\n"
+ " S3Object object = s3.getObject(getObject);\n"
+ " }\n"
+ "}\n",
"import com.amazonaws.services.s3.AmazonS3;\n"
+ "import com.amazonaws.services.s3.model.GetObjectRequest;\n"
+ "import com.amazonaws.services.s3.model.S3Object;\n"
+ "\n"
+ "public class S3Example {\n"
+ " public static void main(String[] args) {\n"
+ " AmazonS3 s3 = null;\n"
+ "\n"
+ " GetObjectRequest getObject = new GetObjectRequest().withBucketName(\"bucket\").withKey(\"key\").withRequesterPays(false);\n"
+ "\n"
+ " S3Object object = s3.getObject(getObject);\n"
+ " }\n"
+ "}"
)
);
}
}