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

Migrate doAfterSuccessOrError to tap #9

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ dependencies {
recipeDependencies {
parserClasspath("org.reactivestreams:reactive-streams:1.0.4")
parserClasspath("io.projectreactor:reactor-core:3.4.39")
parserClasspath("io.projectreactor:reactor-core:3.5.20")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* 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.reactive.reactor;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.FindMethods;
import org.openrewrite.java.tree.*;

import java.util.List;
import java.util.stream.Collectors;

public class ReactorDoAfterSuccessOrErrorToTap extends Recipe {

private static final MethodMatcher DO_AFTER_SUCCESS_OR_ERROR = new MethodMatcher("reactor.core.publisher.Mono doAfterSuccessOrError(..)");

@Override
public String getDisplayName() {
return "Replace `doAfterSuccessOrError` calls with `tap` operator";
}

@Override
public String getDescription() {
return "As of reactor-core 3.5 the `doAfterSuccessOrError` method is removed, this recipe replaces it with the `tap` operator.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new FindMethods("reactor.core.publisher.Mono doAfterSuccessOrError(..)", false), new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = super.visitMethodInvocation(method, ctx);
if (DO_AFTER_SUCCESS_OR_ERROR.matches(mi)) {
JavaType.FullyQualified monoType = TypeUtils.asFullyQualified(((JavaType.Parameterized) mi.getMethodType().getReturnType()).getTypeParameters().get(0));
List<J.VariableDeclarations> doAfterSuccessOrErrorLambdaParams = ((J.Lambda) mi.getArguments().get(0)).getParameters().getParameters().stream().map(J.VariableDeclarations.class::cast).collect(Collectors.toList());
String template = "#{any()}.tap(() -> new DefaultSignalListener<>() {\n" +
" @Override\n" +
" public void doFinally(SignalType terminationType) {\n" +
" // this will be replaced\n" +
" }\n" +
"\n" +
" @Override\n" +
" public void doOnNext(#{any()} " + doAfterSuccessOrErrorLambdaParams.get(0).getVariables().get(0).getSimpleName() + ") {\n" +
" // this will be replaced\n" +
" }\n" +
"\n" +
" @Override\n" +
" public void doOnError(Throwable " + doAfterSuccessOrErrorLambdaParams.get(1).getVariables().get(0).getSimpleName() + ") {\n" +
" // this will be replaced\n" +
" }\n" +
" }\n" +
");";
J.MethodInvocation replacement = JavaTemplate
.builder(template)
.contextSensitive()
.imports("reactor.core.observability.DefaultSignalListener", "reactor.core.publisher.Mono", "reactor.core.publisher.SignalType")
.doAfterVariableSubstitution(System.out::println)
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "reactor-core-3.5.+"))
.build()
.apply(getCursor(), mi.getCoordinates().replace(),
mi.getSelect(),
TypeTree.build(monoType.getClassName()).withType(monoType));

// These are the statements of the `doAfterSuccessOrError` BiConsumer lambda body
List<Statement> doAfterSuccesOrErrorStatements = ((J.Block) ((J.Lambda) mi.getArguments().get(0)).getBody()).getStatements();
mi = replacement.withArguments(ListUtils.map(replacement.getArguments(), arg -> {
if (arg instanceof J.Lambda && ((J.Lambda) arg).getBody() instanceof J.NewClass) {
arg = ((J.Lambda) arg).withBody(((J.NewClass) ((J.Lambda) arg).getBody()).withBody(((J.NewClass) ((J.Lambda) arg).getBody()).getBody().withStatements(ListUtils.map(((J.NewClass) ((J.Lambda) arg).getBody()).getBody().getStatements(), stmt -> {
// here we have access to the method declarations inside the `DefaultSignalListener` inside the tap operator
// We could check the `doAfterSuccessOrError` statements and based on if they use a certain identifier place them in the correct method's body
return stmt;
}))));
}
return arg;
}));
}
return mi;
}
});
}
}
Binary file not shown.
1 change: 1 addition & 0 deletions src/main/resources/META-INF/rewrite/reactor-3.5.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ recipeList:
- org.openrewrite.java.ChangeMethodName:
methodPattern: reactor.core.publisher.Mono deferWithContext(..)
newMethodName: deferContextual
- org.openrewrite.reactive.reactor.ReactorDoAfterSuccessOrErrorToTap
- org.openrewrite.java.ChangeMethodName:
methodPattern: reactor.core.scheduler.Schedulers elastic()
newMethodName: boundedElastic
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* 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.reactive.reactor;

import org.junit.jupiter.api.Test;
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

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

class ReactorDoAfterSuccessOrErrorToTapTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec
.parser(JavaParser.fromJavaVersion()
.classpathFromResources(new InMemoryExecutionContext(), "reactor-core-3.4", "reactive-streams"))
.recipe(new ReactorDoAfterSuccessOrErrorToTap());
}

@Test
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
void refactorSuccessfully() {
//language=java
rewriteRun(
java(
"""
import reactor.core.publisher.Mono;

class SomeClass {
void doSomething(Mono<String> mono){
mono.doAfterSuccessOrError((result, error) -> {
if (error != null) {
System.out.println("error" + error);
} else {
System.out.println("success" + result);
}
System.out.println("other logs");
Comment on lines +49 to +54
Copy link
Contributor

@timtebeek timtebeek Oct 9, 2024

Choose a reason for hiding this comment

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

Great start I think to split out commands in this way; let's add a few more variants like if (error == null), if (null == error), or separate ifs, no else, other statements before/interspersed. We're going for a bit of variety here, such that we don't overfit the recipe implementation to this one test. Then from there we can look across OSS projects that use doAfterSuccessOrError.

Copy link
Contributor Author

@Laurens-W Laurens-W Oct 9, 2024

Choose a reason for hiding this comment

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

I already ran a FindMethods across OSS and found none, but perhaps pattern reactor.core.publisher.Mono doAfterSuccessOrError(..) is too specific?

Will add more test variations!

}).subscribe();
}
}
""",
"""
import reactor.core.observability.DefaultSignalListener;
import reactor.core.publisher.Mono;
import reactor.core.publisher.SignalType;

class SomeClass {
void doSomething(Mono<String> mono) {
mono.tap(() -> new DefaultSignalListener<>() {
@Override
public void doFinally(SignalType terminationType) {
System.out.println("other logs");
}

@Override
public void doOnNext(String value) {
System.out.println("success" + value);
}

@Override
public void doOnError(Throwable error) {
System.out.println("error" + error);
}
}
).subscribe();
}
}
"""
)
);
}
}
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
Loading