Skip to content

Commit f9fd034

Browse files
kunli2joanvrknutwannheden
authored
Update JavaTemplate for rewrite8.0 (#366)
* 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]>
1 parent 5b38d5e commit f9fd034

File tree

37 files changed

+380
-315
lines changed

37 files changed

+380
-315
lines changed

src/main/java/org/openrewrite/java/spring/AutowiredFieldIntoConstructorParameterVisitor.java

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -165,15 +165,27 @@ public J visitBlock(Block block, ExecutionContext p) {
165165
+ classDecl.getSimpleName() + "(" + typeFqn.getClassName() + " " + fieldName + ") {\n"
166166
+ "this." + fieldName + " = " + fieldName + ";\n"
167167
+ "}\n"
168-
).context(getCursor());
168+
).contextSensitive();
169169
FullyQualified fq = TypeUtils.asFullyQualified(type.getType());
170170
if (fq != null) {
171171
template.imports(fq.getFullyQualifiedName());
172172
maybeAddImport(fq);
173173
}
174174
Optional<Statement> firstMethod = block.getStatements().stream().filter(MethodDeclaration.class::isInstance).findFirst();
175-
return firstMethod.map(statement -> (J) block.withTemplate(template.build(), getCursor(), statement.getCoordinates().before()))
176-
.orElseGet(() -> block.withTemplate(template.build(), getCursor(), block.getCoordinates().lastStatement()));
175+
176+
return firstMethod.map(statement ->
177+
(J) template.build()
178+
.apply(getCursor(),
179+
statement.getCoordinates().before()
180+
)
181+
)
182+
.orElseGet(() ->
183+
template.build()
184+
.apply(
185+
getCursor(),
186+
block.getCoordinates().lastStatement()
187+
)
188+
);
177189
}
178190
}
179191
}
@@ -205,12 +217,24 @@ public MethodDeclaration visitMethodDeclaration(MethodDeclaration method, Execut
205217
String paramsStr = Stream.concat(params.stream()
206218
.map(s -> "#{}"), Stream.of(methodType + " " + fieldName)).collect(Collectors.joining(", "));
207219

208-
JavaTemplate.Builder paramsTemplate = JavaTemplate.builder(paramsStr).context(getCursor());
209-
md = md.withTemplate(paramsTemplate.build(), getCursor(), md.getCoordinates().replaceParameters(), params.toArray());
220+
md = JavaTemplate.builder(paramsStr)
221+
.contextSensitive()
222+
.build()
223+
.apply(
224+
getCursor(),
225+
md.getCoordinates().replaceParameters(),
226+
params.toArray()
227+
);
228+
updateCursor(md);
210229

211-
JavaTemplate.Builder statementTemplate = JavaTemplate.builder("this." + fieldName + " = " + fieldName + ";").context(getCursor());
212230
//noinspection ConstantConditions
213-
md = md.withTemplate(statementTemplate.build(), getCursor(), md.getBody().getCoordinates().lastStatement());
231+
md = JavaTemplate.builder("this." + fieldName + " = " + fieldName + ";")
232+
.contextSensitive()
233+
.build()
234+
.apply(
235+
getCursor(),
236+
md.getBody().getCoordinates().lastStatement()
237+
);
214238
}
215239
return md;
216240
}

src/main/java/org/openrewrite/java/spring/DeleteSpringProperty.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@
3232
public class DeleteSpringProperty extends Recipe {
3333

3434
@Option(displayName = "Property key",
35-
description = "The property key to delete. Supports glob expressions",
36-
example = "management.endpoint.configprops.*")
35+
description = "The property key to delete. Supports glob expressions",
36+
example = "management.endpoint.configprops.*")
3737
String propertyKey;
3838

3939
@Override
@@ -58,10 +58,10 @@ public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) {
5858
public @Nullable Tree visit(@Nullable Tree t, ExecutionContext ctx) {
5959
if (t instanceof Yaml.Documents) {
6060
t = new org.openrewrite.yaml.DeleteProperty(propertyKey, false, true)
61-
.getVisitor().visitNonNull(t, ctx);
61+
.getVisitor().visitNonNull(t, ctx);
6262
} else if (t instanceof Properties.File) {
6363
t = new DeleteProperty(propertyKey, true)
64-
.getVisitor().visitNonNull(t, ctx);
64+
.getVisitor().visitNonNull(t, ctx);
6565
}
6666
return t;
6767
}

src/main/java/org/openrewrite/java/spring/amqp/UseTlsAmqpConnectionString.java

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -106,10 +106,10 @@ public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) {
106106
public Tree visit(@Nullable Tree t, ExecutionContext ctx) {
107107
if (t instanceof Yaml.Documents && sourcePathMatches(((SourceFile) t).getSourcePath(), ctx)) {
108108
t = new UseTlsAmqpConnectionStringYaml(actualPropertyKey, oldPort, port, actualTlsPropertyKey, pathExpressions)
109-
.getVisitor().visit(t, ctx);
109+
.getVisitor().visit(t, ctx);
110110
} else if (t instanceof Properties.File && sourcePathMatches(((SourceFile) t).getSourcePath(), ctx)) {
111111
t = new UseTlsAmqpConnectionStringProperties(actualPropertyKey, oldPort, port, actualTlsPropertyKey, pathExpressions)
112-
.getVisitor().visit(t, ctx);
112+
.getVisitor().visit(t, ctx);
113113
}
114114
return t;
115115
}
@@ -195,7 +195,8 @@ public Yaml.Mapping.Entry visitMappingEntry(Yaml.Mapping.Entry entry, ExecutionC
195195
if (updatedAmqpUrl != amqpUrl) {
196196
updated = true;
197197
connectionStrings[i] = updatedAmqpUrl.toString();
198-
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", "false", null, null).getVisitor());
198+
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", "false", null, null)
199+
.getVisitor());
199200
}
200201
} else {
201202
// hostname:port(/virtualhost)
@@ -208,8 +209,10 @@ public Yaml.Mapping.Entry visitMappingEntry(Yaml.Mapping.Entry entry, ExecutionC
208209
if (!updatedConnectionString.equals(connectionString)) {
209210
updated = true;
210211
connectionStrings[i] = updatedConnectionString;
211-
doAfterVisit(new AddSpringProperty(tlsPropertyKey, "true", null, pathExpressions).getVisitor());
212-
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", null, null, null).getVisitor());
212+
doAfterVisit(new AddSpringProperty(tlsPropertyKey, "true", null, pathExpressions)
213+
.getVisitor());
214+
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", null, null, null)
215+
.getVisitor());
213216
}
214217
}
215218
}
@@ -290,7 +293,8 @@ public Properties.Entry visitEntry(Properties.Entry entry, ExecutionContext ctx)
290293
if (updatedAmqpUrl != amqpUrl) {
291294
updated = true;
292295
connectionStrings[i] = updatedAmqpUrl.toString();
293-
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", "false", null, null).getVisitor());
296+
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", "false", null, null)
297+
.getVisitor());
294298
}
295299
} else {
296300
// hostname:port(/virtualhost)
@@ -303,8 +307,10 @@ public Properties.Entry visitEntry(Properties.Entry entry, ExecutionContext ctx)
303307
if (!updatedConnectionString.equals(connectionString)) {
304308
updated = true;
305309
connectionStrings[i] = updatedConnectionString;
306-
doAfterVisit(new AddSpringProperty(tlsPropertyKey, "true", null, pathExpressions).getVisitor());
307-
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", null, null, null).getVisitor());
310+
doAfterVisit(new AddSpringProperty(tlsPropertyKey, "true", null, pathExpressions)
311+
.getVisitor());
312+
doAfterVisit(new ChangeSpringPropertyValue(tlsPropertyKey, "true", null, null, null)
313+
.getVisitor());
308314
}
309315
}
310316
}

src/main/java/org/openrewrite/java/spring/batch/MigrateItemWriterWrite.java

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -74,22 +74,23 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, Ex
7474
// updated automatically. Since parameters usages do not have their type updated, must replace the whole
7575
// method to ensure that type info is accurate / List import can potentially be removed
7676
// See: https://github.com/openrewrite/rewrite/issues/2819
77-
m = m.withTemplate(
78-
JavaTemplate.builder("#{}\n #{} void write(#{} Chunk<#{}> #{}) throws Exception #{}")
79-
.context(getCursor())
80-
.javaParser(JavaParser.fromJavaVersion()
81-
.classpathFromResources(ctx, "spring-batch-core-5.+", "spring-batch-infrastructure-5.+"))
82-
.imports("org.springframework.batch.item.Chunk")
83-
.build(),
77+
78+
m = JavaTemplate.builder("#{}\n #{} void write(#{} Chunk<#{}> #{}) throws Exception #{}")
79+
.contextSensitive()
80+
.javaParser(JavaParser.fromJavaVersion()
81+
.classpathFromResources(ctx, "spring-batch-core-5.+", "spring-batch-infrastructure-5.+"))
82+
.imports("org.springframework.batch.item.Chunk")
83+
.build()
84+
.apply(
8485
getCursor(),
8586
m.getCoordinates().replace(),
8687
annotationsWithOverride,
8788
m.getModifiers().stream()
88-
.map(J.Modifier::toString)
89-
.collect(Collectors.joining(" ")),
89+
.map(J.Modifier::toString)
90+
.collect(Collectors.joining(" ")),
9091
parameter.getModifiers().stream()
91-
.map(J.Modifier::toString)
92-
.collect(Collectors.joining(" ")),
92+
.map(J.Modifier::toString)
93+
.collect(Collectors.joining(" ")),
9394
chunkTypeParameter,
9495
paramName,
9596
m.getBody() == null ? "" : m.getBody().print(getCursor()));

src/main/java/org/openrewrite/java/spring/batch/MigrateJobBuilderFactory.java

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -61,17 +61,18 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
6161

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

64-
return method.withTemplate(JavaTemplate
65-
.builder("new JobBuilder(#{any(java.lang.String)}, jobRepository)")
66-
.context(getCursor())
67-
.javaParser(JavaParser.fromJavaVersion()
68-
.classpathFromResources(ctx, "spring-batch-core-5.+"))
69-
.imports("org.springframework.batch.core.repository.JobRepository",
70-
"org.springframework.batch.core.job.builder.JobBuilder")
71-
.build(),
64+
return JavaTemplate
65+
.builder("new JobBuilder(#{any(java.lang.String)}, jobRepository)")
66+
.contextSensitive()
67+
.javaParser(JavaParser.fromJavaVersion()
68+
.classpathFromResources(ctx, "spring-batch-core-5.+"))
69+
.imports("org.springframework.batch.core.repository.JobRepository",
70+
"org.springframework.batch.core.job.builder.JobBuilder")
71+
.build().apply(
7272
getCursor(),
7373
method.getCoordinates().replace(),
74-
method.getArguments().get(0));
74+
method.getArguments().get(0)
75+
);
7576
}
7677
return super.visitMethodInvocation(method, ctx);
7778
}
@@ -132,15 +133,15 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl
132133

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

143-
md = md.withTemplate(paramsTemplate, getCursor(), md.getCoordinates().replaceParameters(), params.toArray());
144+
md = paramsTemplate.apply(getCursor(), md.getCoordinates().replaceParameters(), params.toArray());
144145

145146
maybeRemoveImport("org.springframework.batch.core.configuration.annotation.JobBuilderFactory");
146147
maybeAddImport("org.springframework.batch.core.repository.JobRepository");

src/main/java/org/openrewrite/java/spring/batch/ReplaceSupportClassWithItsInterface.java

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,25 +64,27 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl,
6464
if (cd.getExtends() != null
6565
&& TypeUtils.isOfClassType(cd.getExtends().getType(), fullyQualifiedClassName)) {
6666
cd = cd.withExtends(null);
67+
updateCursor(cd);
6768
// This is an interesting one... JobExecutionListenerSupport implements
6869
// JobExecutionListener
6970
// remove the super type from the class type to prevent a stack-overflow
7071
// exception when the JavaTemplate visits class type.
7172
JavaType.Class type = (JavaType.Class) cd.getType();
7273
if (type != null) {
7374
cd = cd.withType(type.withSupertype(null));
75+
updateCursor(cd);
7476
}
7577

76-
cd = cd.withTemplate(
77-
JavaTemplate
78-
.builder(JavaType.ShallowClass.build(fullyQualifiedInterfaceName).getClassName())
79-
.imports(fullyQualifiedInterfaceName)
80-
.javaParser(JavaParser.fromJavaVersion().classpath("spring-batch"))
81-
.build(),
78+
cd = JavaTemplate
79+
.builder(JavaType.ShallowClass.build(fullyQualifiedInterfaceName).getClassName())
80+
.imports(fullyQualifiedInterfaceName)
81+
.javaParser(JavaParser.fromJavaVersion().classpath("spring-batch"))
82+
.build()
83+
.apply(
8284
getCursor(),
83-
cd.getCoordinates().addImplementsClause());
84-
cd = (J.ClassDeclaration) new RemoveSuperStatementVisitor().visitNonNull(cd, ctx,
85-
getCursor());
85+
cd.getCoordinates().addImplementsClause()
86+
);
87+
cd = (J.ClassDeclaration) new RemoveSuperStatementVisitor().visitNonNull(cd, ctx, getCursor());
8688
maybeRemoveImport(fullyQualifiedClassName);
8789
maybeAddImport(fullyQualifiedInterfaceName);
8890
}

src/main/java/org/openrewrite/java/spring/boot2/AddConfigurationAnnotationIfBeansPresent.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,13 +62,14 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex
6262

6363
private J.ClassDeclaration addConfigurationAnnotation(J.ClassDeclaration c) {
6464
maybeAddImport(FQN_CONFIGURATION);
65-
JavaTemplate template = JavaTemplate.builder("@" + CONFIGURATION_SIMPLE_NAME)
66-
.imports(FQN_CONFIGURATION)
67-
.javaParser(JavaParser.fromJavaVersion().dependsOn("package " + CONFIGURATION_PACKAGE
68-
+ "; public @interface " + CONFIGURATION_SIMPLE_NAME + " {}"))
69-
.build();
70-
return c.withTemplate(template, getCursor(),
71-
c.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
65+
return JavaTemplate.builder("@" + CONFIGURATION_SIMPLE_NAME)
66+
.imports(FQN_CONFIGURATION)
67+
.javaParser(JavaParser.fromJavaVersion().dependsOn("package " + CONFIGURATION_PACKAGE
68+
+ "; public @interface " + CONFIGURATION_SIMPLE_NAME + " {}"))
69+
.build().apply(
70+
getCursor(),
71+
c.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName))
72+
);
7273
}
7374
});
7475
}

0 commit comments

Comments
 (0)