Skip to content

Commit

Permalink
Update JavaTemplate for rewrite8.0 (#366)
Browse files Browse the repository at this point in the history
* Update javaTemplate

* revert some change

* fix ConditionalOnBeanAnyNestedCondition

* fix OutputCaptureExtension

* fix AutowiredFieldIntoConstructorParameterVisitor

* fix MigrateMvcConfigureAdapter

* fixed indentation

* revert to fix UpgradeExplicitSpringBootDependencies

* fix AddSetUseTrailingSlashMatch

* removed comment

* fix ReplaceSupportClassWithItsInterface

* changed new Cursor to updateCursor

* TODO: disabled tests temporally until dependency updated

* Fix failing `WebSecurityConfigurerAdapterTest`

* fix UpdateRequestCache

---------

Co-authored-by: joanvr <[email protected]>
Co-authored-by: Knut Wannheden <[email protected]>
  • Loading branch information
3 people authored Jun 1, 2023
1 parent 5b38d5e commit f9fd034
Show file tree
Hide file tree
Showing 37 changed files with 380 additions and 315 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -165,15 +165,27 @@ public J visitBlock(Block block, ExecutionContext p) {
+ classDecl.getSimpleName() + "(" + typeFqn.getClassName() + " " + fieldName + ") {\n"
+ "this." + fieldName + " = " + fieldName + ";\n"
+ "}\n"
).context(getCursor());
).contextSensitive();
FullyQualified fq = TypeUtils.asFullyQualified(type.getType());
if (fq != null) {
template.imports(fq.getFullyQualifiedName());
maybeAddImport(fq);
}
Optional<Statement> firstMethod = block.getStatements().stream().filter(MethodDeclaration.class::isInstance).findFirst();
return firstMethod.map(statement -> (J) block.withTemplate(template.build(), getCursor(), statement.getCoordinates().before()))
.orElseGet(() -> block.withTemplate(template.build(), getCursor(), block.getCoordinates().lastStatement()));

return firstMethod.map(statement ->
(J) template.build()
.apply(getCursor(),
statement.getCoordinates().before()
)
)
.orElseGet(() ->
template.build()
.apply(
getCursor(),
block.getCoordinates().lastStatement()
)
);
}
}
}
Expand Down Expand Up @@ -205,12 +217,24 @@ public MethodDeclaration visitMethodDeclaration(MethodDeclaration method, Execut
String paramsStr = Stream.concat(params.stream()
.map(s -> "#{}"), Stream.of(methodType + " " + fieldName)).collect(Collectors.joining(", "));

JavaTemplate.Builder paramsTemplate = JavaTemplate.builder(paramsStr).context(getCursor());
md = md.withTemplate(paramsTemplate.build(), getCursor(), md.getCoordinates().replaceParameters(), params.toArray());
md = JavaTemplate.builder(paramsStr)
.contextSensitive()
.build()
.apply(
getCursor(),
md.getCoordinates().replaceParameters(),
params.toArray()
);
updateCursor(md);

JavaTemplate.Builder statementTemplate = JavaTemplate.builder("this." + fieldName + " = " + fieldName + ";").context(getCursor());
//noinspection ConstantConditions
md = md.withTemplate(statementTemplate.build(), getCursor(), md.getBody().getCoordinates().lastStatement());
md = JavaTemplate.builder("this." + fieldName + " = " + fieldName + ";")
.contextSensitive()
.build()
.apply(
getCursor(),
md.getBody().getCoordinates().lastStatement()
);
}
return md;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
public class DeleteSpringProperty extends Recipe {

@Option(displayName = "Property key",
description = "The property key to delete. Supports glob expressions",
example = "management.endpoint.configprops.*")
description = "The property key to delete. Supports glob expressions",
example = "management.endpoint.configprops.*")
String propertyKey;

@Override
Expand All @@ -58,10 +58,10 @@ public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) {
public @Nullable Tree visit(@Nullable Tree t, ExecutionContext ctx) {
if (t instanceof Yaml.Documents) {
t = new org.openrewrite.yaml.DeleteProperty(propertyKey, false, true)
.getVisitor().visitNonNull(t, ctx);
.getVisitor().visitNonNull(t, ctx);
} else if (t instanceof Properties.File) {
t = new DeleteProperty(propertyKey, true)
.getVisitor().visitNonNull(t, ctx);
.getVisitor().visitNonNull(t, ctx);
}
return t;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,10 @@ public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) {
public Tree visit(@Nullable Tree t, ExecutionContext ctx) {
if (t instanceof Yaml.Documents && sourcePathMatches(((SourceFile) t).getSourcePath(), ctx)) {
t = new UseTlsAmqpConnectionStringYaml(actualPropertyKey, oldPort, port, actualTlsPropertyKey, pathExpressions)
.getVisitor().visit(t, ctx);
.getVisitor().visit(t, ctx);
} else if (t instanceof Properties.File && sourcePathMatches(((SourceFile) t).getSourcePath(), ctx)) {
t = new UseTlsAmqpConnectionStringProperties(actualPropertyKey, oldPort, port, actualTlsPropertyKey, pathExpressions)
.getVisitor().visit(t, ctx);
.getVisitor().visit(t, ctx);
}
return t;
}
Expand Down Expand Up @@ -195,7 +195,8 @@ public Yaml.Mapping.Entry visitMappingEntry(Yaml.Mapping.Entry entry, ExecutionC
if (updatedAmqpUrl != amqpUrl) {
updated = true;
connectionStrings[i] = updatedAmqpUrl.toString();
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", "false", null, null).getVisitor());
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", "false", null, null)
.getVisitor());
}
} else {
// hostname:port(/virtualhost)
Expand All @@ -208,8 +209,10 @@ public Yaml.Mapping.Entry visitMappingEntry(Yaml.Mapping.Entry entry, ExecutionC
if (!updatedConnectionString.equals(connectionString)) {
updated = true;
connectionStrings[i] = updatedConnectionString;
doAfterVisit(new AddSpringProperty(tlsPropertyKey, "true", null, pathExpressions).getVisitor());
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", null, null, null).getVisitor());
doAfterVisit(new AddSpringProperty(tlsPropertyKey, "true", null, pathExpressions)
.getVisitor());
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", null, null, null)
.getVisitor());
}
}
}
Expand Down Expand Up @@ -290,7 +293,8 @@ public Properties.Entry visitEntry(Properties.Entry entry, ExecutionContext ctx)
if (updatedAmqpUrl != amqpUrl) {
updated = true;
connectionStrings[i] = updatedAmqpUrl.toString();
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", "false", null, null).getVisitor());
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", "false", null, null)
.getVisitor());
}
} else {
// hostname:port(/virtualhost)
Expand All @@ -303,8 +307,10 @@ public Properties.Entry visitEntry(Properties.Entry entry, ExecutionContext ctx)
if (!updatedConnectionString.equals(connectionString)) {
updated = true;
connectionStrings[i] = updatedConnectionString;
doAfterVisit(new AddSpringProperty(tlsPropertyKey, "true", null, pathExpressions).getVisitor());
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", null, null, null).getVisitor());
doAfterVisit(new AddSpringProperty(tlsPropertyKey, "true", null, pathExpressions)
.getVisitor());
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", null, null, null)
.getVisitor());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,22 +74,23 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, Ex
// updated automatically. Since parameters usages do not have their type updated, must replace the whole
// method to ensure that type info is accurate / List import can potentially be removed
// See: https://github.com/openrewrite/rewrite/issues/2819
m = m.withTemplate(
JavaTemplate.builder("#{}\n #{} void write(#{} Chunk<#{}> #{}) throws Exception #{}")
.context(getCursor())
.javaParser(JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "spring-batch-core-5.+", "spring-batch-infrastructure-5.+"))
.imports("org.springframework.batch.item.Chunk")
.build(),

m = JavaTemplate.builder("#{}\n #{} void write(#{} Chunk<#{}> #{}) throws Exception #{}")
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "spring-batch-core-5.+", "spring-batch-infrastructure-5.+"))
.imports("org.springframework.batch.item.Chunk")
.build()
.apply(
getCursor(),
m.getCoordinates().replace(),
annotationsWithOverride,
m.getModifiers().stream()
.map(J.Modifier::toString)
.collect(Collectors.joining(" ")),
.map(J.Modifier::toString)
.collect(Collectors.joining(" ")),
parameter.getModifiers().stream()
.map(J.Modifier::toString)
.collect(Collectors.joining(" ")),
.map(J.Modifier::toString)
.collect(Collectors.joining(" ")),
chunkTypeParameter,
paramName,
m.getBody() == null ? "" : m.getBody().print(getCursor()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,18 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)

doAfterVisit(new MigrateJobBuilderFactory.RemoveJobBuilderFactoryVisitor(clazz, enclosingMethod));

return method.withTemplate(JavaTemplate
.builder("new JobBuilder(#{any(java.lang.String)}, jobRepository)")
.context(getCursor())
.javaParser(JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "spring-batch-core-5.+"))
.imports("org.springframework.batch.core.repository.JobRepository",
"org.springframework.batch.core.job.builder.JobBuilder")
.build(),
return JavaTemplate
.builder("new JobBuilder(#{any(java.lang.String)}, jobRepository)")
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "spring-batch-core-5.+"))
.imports("org.springframework.batch.core.repository.JobRepository",
"org.springframework.batch.core.job.builder.JobBuilder")
.build().apply(
getCursor(),
method.getCoordinates().replace(),
method.getArguments().get(0));
method.getArguments().get(0)
);
}
return super.visitMethodInvocation(method, ctx);
}
Expand Down Expand Up @@ -132,15 +133,15 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl

JavaTemplate paramsTemplate = JavaTemplate
.builder(params.stream().map(p -> "#{}").collect(Collectors.joining(", ")))
.context(getCursor())
.contextSensitive()
.imports("org.springframework.batch.core.repository.JobRepository",
"org.springframework.batch.core.job.builder.JobBuilder",
"org.springframework.batch.core.Step")
.javaParser(JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "spring-batch-core-5.+"))
.build();

md = md.withTemplate(paramsTemplate, getCursor(), md.getCoordinates().replaceParameters(), params.toArray());
md = paramsTemplate.apply(getCursor(), md.getCoordinates().replaceParameters(), params.toArray());

maybeRemoveImport("org.springframework.batch.core.configuration.annotation.JobBuilderFactory");
maybeAddImport("org.springframework.batch.core.repository.JobRepository");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,25 +64,27 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl,
if (cd.getExtends() != null
&& TypeUtils.isOfClassType(cd.getExtends().getType(), fullyQualifiedClassName)) {
cd = cd.withExtends(null);
updateCursor(cd);
// This is an interesting one... JobExecutionListenerSupport implements
// JobExecutionListener
// remove the super type from the class type to prevent a stack-overflow
// exception when the JavaTemplate visits class type.
JavaType.Class type = (JavaType.Class) cd.getType();
if (type != null) {
cd = cd.withType(type.withSupertype(null));
updateCursor(cd);
}

cd = cd.withTemplate(
JavaTemplate
.builder(JavaType.ShallowClass.build(fullyQualifiedInterfaceName).getClassName())
.imports(fullyQualifiedInterfaceName)
.javaParser(JavaParser.fromJavaVersion().classpath("spring-batch"))
.build(),
cd = JavaTemplate
.builder(JavaType.ShallowClass.build(fullyQualifiedInterfaceName).getClassName())
.imports(fullyQualifiedInterfaceName)
.javaParser(JavaParser.fromJavaVersion().classpath("spring-batch"))
.build()
.apply(
getCursor(),
cd.getCoordinates().addImplementsClause());
cd = (J.ClassDeclaration) new RemoveSuperStatementVisitor().visitNonNull(cd, ctx,
getCursor());
cd.getCoordinates().addImplementsClause()
);
cd = (J.ClassDeclaration) new RemoveSuperStatementVisitor().visitNonNull(cd, ctx, getCursor());
maybeRemoveImport(fullyQualifiedClassName);
maybeAddImport(fullyQualifiedInterfaceName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,14 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex

private J.ClassDeclaration addConfigurationAnnotation(J.ClassDeclaration c) {
maybeAddImport(FQN_CONFIGURATION);
JavaTemplate template = JavaTemplate.builder("@" + CONFIGURATION_SIMPLE_NAME)
.imports(FQN_CONFIGURATION)
.javaParser(JavaParser.fromJavaVersion().dependsOn("package " + CONFIGURATION_PACKAGE
+ "; public @interface " + CONFIGURATION_SIMPLE_NAME + " {}"))
.build();
return c.withTemplate(template, getCursor(),
c.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
return JavaTemplate.builder("@" + CONFIGURATION_SIMPLE_NAME)
.imports(FQN_CONFIGURATION)
.javaParser(JavaParser.fromJavaVersion().dependsOn("package " + CONFIGURATION_PACKAGE
+ "; public @interface " + CONFIGURATION_SIMPLE_NAME + " {}"))
.build().apply(
getCursor(),
c.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName))
);
}
});
}
Expand Down
Loading

0 comments on commit f9fd034

Please sign in to comment.