Skip to content
Open
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
Expand Up @@ -33,6 +33,7 @@ public class URLConstructorsToNewURI extends Recipe {
private static final String URL_FQN = "java.net.URL";
private static final MethodMatcher methodMatcherThreeArg = new MethodMatcher(URL_FQN + " <constructor>(java.lang.String, java.lang.String, java.lang.String)");
private static final MethodMatcher methodMatcherFourArg = new MethodMatcher(URL_FQN + " <constructor>(java.lang.String, java.lang.String, int, java.lang.String)");
private static final MethodMatcher methodMatcherFiveArg = new MethodMatcher(URL_FQN + " <constructor>(java.lang.String, java.lang.String, int, java.lang.String, java.net.URLStreamHandler)");

@Getter
final String displayName = "Convert `new URL(String, ..)` to `new URI(String, ..).toURL()`";
Expand Down Expand Up @@ -73,6 +74,21 @@ public J visitNewClass(J.NewClass nc, ExecutionContext ctx) {
nc.getArguments().get(2),
nc.getArguments().get(3));
}
if (methodMatcherFiveArg.matches(nc)) {
JavaTemplate template = JavaTemplate.builder("URL.of(new URI(#{any(String)}, null, #{any(String)}, #{any(int)}, #{any(String)}, null, null), #{any(java.net.URLStreamHandler)})")
.imports(URI_FQN, URL_FQN)
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion())
.build();

maybeAddImport(URI_FQN);
return template.apply(getCursor(), nc.getCoordinates().replace(),
nc.getArguments().get(0),
nc.getArguments().get(1),
nc.getArguments().get(2),
nc.getArguments().get(3),
nc.getArguments().get(4));
}
return super.visitNewClass(nc, ctx);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,36 @@ public void defaults(RecipeSpec spec) {
spec.recipe(new URLConstructorsToNewURI());
}

@Test
void urlConstructorWithStreamHandler() {
rewriteRun(
//language=java
java(
"""
import java.net.URL;
import java.net.URLStreamHandler;

class Test {
URL url(String protocol, String host, int port, String file, URLStreamHandler handler) throws Exception {
return new URL(protocol, host, port, file, handler);
}
}
""",
"""
import java.net.URI;
import java.net.URL;
import java.net.URLStreamHandler;

class Test {
URL url(String protocol, String host, int port, String file, URLStreamHandler handler) throws Exception {
return URL.of(new URI(protocol, null, host, port, file, null, null), handler);
}
}
"""
)
);
}

@DocumentExample
@Test
void urlConstructor() {
Expand Down
Loading