diff --git a/build.gradle.kts b/build.gradle.kts index 0030359f63..36d894e5b4 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -29,11 +29,6 @@ dependencies { implementation("org.openrewrite.recipe:rewrite-static-analysis:$rewriteVersion") implementation("org.openrewrite:rewrite-templating:$rewriteVersion") - implementation("commons-io:commons-io:2.+") - implementation("org.apache.commons:commons-lang3:3.+") - implementation("org.apache.maven.shared:maven-shared-utils:3.+") - implementation("org.codehaus.plexus:plexus-utils:3.+") - runtimeOnly("org.openrewrite:rewrite-java-8") runtimeOnly("org.openrewrite:rewrite-java-11") runtimeOnly("org.openrewrite:rewrite-java-17") @@ -52,8 +47,6 @@ dependencies { testImplementation("com.google.guava:guava:29.0-jre") - testImplementation("commons-codec:commons-codec:1.+") - testRuntimeOnly("com.fasterxml.jackson.datatype:jackson-datatype-jsr353") testRuntimeOnly("com.fasterxml.jackson.core:jackson-core") testRuntimeOnly("com.fasterxml.jackson.core:jackson-databind") diff --git a/src/main/java/org/openrewrite/java/migrate/MavenUtils.java b/src/main/java/org/openrewrite/java/migrate/MavenUtils.java deleted file mode 100644 index 4578aff04f..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/MavenUtils.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2021 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate; - -import org.openrewrite.SourceFile; -import org.openrewrite.maven.tree.MavenResolutionResult; -import org.openrewrite.xml.tree.Xml; - -public final class MavenUtils { - private MavenUtils() { - } - - public static boolean isMavenSource(SourceFile s) { - return s instanceof Xml.Document && s.getMarkers().findFirst(MavenResolutionResult.class).isPresent(); - } - - public static MavenResolutionResult getMavenModel(SourceFile s) { - return s.getMarkers().findFirst(MavenResolutionResult.class) - .orElseThrow(() -> new IllegalStateException("Source file does not have a maven model.")); - } -} diff --git a/src/main/java/org/openrewrite/java/migrate/apache/commons/codec/ApacheBase64ToJavaBase64.java b/src/main/java/org/openrewrite/java/migrate/apache/commons/codec/ApacheBase64ToJavaBase64.java deleted file mode 100644 index c20d7da84f..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/apache/commons/codec/ApacheBase64ToJavaBase64.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2021 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.codec; - -import org.openrewrite.ExecutionContext; -import org.openrewrite.Preconditions; -import org.openrewrite.Recipe; -import org.openrewrite.TreeVisitor; -import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.JavaTemplate; -import org.openrewrite.java.MethodMatcher; -import org.openrewrite.java.search.UsesType; -import org.openrewrite.java.tree.J; -import org.openrewrite.java.tree.JavaType; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -public class ApacheBase64ToJavaBase64 extends Recipe { - @Override - public String getDisplayName() { - return "Prefer `java.util.Base64`"; - } - - @Override - public String getDescription() { - return "Prefer the Java standard library's `java.util.Base64` over third-party usage of apache's `apache.commons.codec.binary.Base64`."; - } - - @Override - public Set getTags() { - return new HashSet<>(Arrays.asList("apache", "commons")); - } - - @Override - public TreeVisitor getVisitor() { - return Preconditions.check(new UsesType<>("org.apache.commons.codec.binary.Base64", false), new JavaIsoVisitor() { - private final MethodMatcher apacheEncodeToString = new MethodMatcher("org.apache.commons.codec.binary.Base64 encodeBase64String(byte[])"); - private final MethodMatcher apacheEncode64 = new MethodMatcher("org.apache.commons.codec.binary.Base64 encodeBase64(byte[])"); - private final MethodMatcher apacheDecode = new MethodMatcher("org.apache.commons.codec.binary.Base64 decodeBase64(..)"); - private final MethodMatcher apacheEncode64UrlSafe = new MethodMatcher("org.apache.commons.codec.binary.Base64 encodeBase64URLSafe(..)"); - private final MethodMatcher apacheEncode64UrlSafeString = new MethodMatcher("org.apache.commons.codec.binary.Base64 encodeBase64URLSafeString(..)"); - - @Override - public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) { - J.MethodInvocation mi = super.visitMethodInvocation(method, ctx); - String templatePrefix = null; - if (apacheEncodeToString.matches(mi)) { - String argType = mi.getArguments().get(0).getType() instanceof JavaType.Array ? "#{anyArray()}" : "#{any(String)}"; - templatePrefix = "Base64.getEncoder().encodeToString(" + argType + ")"; - } else if (apacheEncode64.matches(mi)) { - templatePrefix = "Base64.getEncoder().encode(#{anyArray()})"; - } else if (apacheDecode.matches(mi)) { - templatePrefix = "Base64.getDecoder().decode(#{any(String)})"; - } else if (apacheEncode64UrlSafe.matches(mi)) { - templatePrefix = "Base64.getUrlEncoder().withoutPadding().encode(#{anyArray()})"; - } else if (apacheEncode64UrlSafeString.matches(mi)) { - templatePrefix = "Base64.getUrlEncoder().withoutPadding().encodeToString(#{anyArray()})"; - } - if (templatePrefix != null) { - JavaTemplate t = JavaTemplate.builder(templatePrefix).imports("java.util.Base64").build(); - maybeRemoveImport("org.apache.commons.codec.binary.Base64"); - maybeAddImport("java.util.Base64"); - mi = t.apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0)); - } - return mi; - } - }); - } -} diff --git a/src/main/java/org/openrewrite/java/migrate/apache/commons/codec/package-info.java b/src/main/java/org/openrewrite/java/migrate/apache/commons/codec/package-info.java deleted file mode 100644 index f93a74b7d6..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/apache/commons/codec/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2021 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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. - */ -@NonNullApi -@NonNullFields -package org.openrewrite.java.migrate.apache.commons.codec; - -import org.openrewrite.internal.lang.NonNullApi; -import org.openrewrite.internal.lang.NonNullFields; diff --git a/src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheCommonsFileUtils.java b/src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheCommonsFileUtils.java deleted file mode 100644 index 55bd5a1673..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheCommonsFileUtils.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.io; - -import com.google.errorprone.refaster.annotation.AfterTemplate; -import com.google.errorprone.refaster.annotation.BeforeTemplate; -import org.apache.commons.io.FileUtils; -import org.openrewrite.java.template.RecipeDescriptor; - -import java.io.File; -import java.nio.file.Files; - -public class ApacheCommonsFileUtils { - @RecipeDescriptor( - name = "Replace `FileUtils.getFile(String...)` with JDK provided API", - description = "Replace Apache Commons `FileUtils.getFile(String... name)` with JDK provided API.") - public static class GetFile { - @BeforeTemplate - File before(String name) { - return FileUtils.getFile(name); - } - - @AfterTemplate - File after(String name) { - return new File(name); - } - } - -// NOTE: java: reference to compile is ambiguous; methods P3 & F3 match -// public static class Write { -// @BeforeTemplate -// void before(File file, CharSequence data, Charset cs) throws Exception { -// FileUtils.write(file, data, cs); -// } -// -// @AfterTemplate -// void after(File file, CharSequence data, Charset cs) throws Exception { -// Files.write(file.toPath(), Arrays.asList(data), cs); -// } -// } - - @RecipeDescriptor( - name = "Replace `FileUtils.writeStringToFile(File, String)` with JDK provided API", - description = "Replace Apache Commons `FileUtils.writeStringToFile(File file, String data)` with JDK provided API.") - @SuppressWarnings("deprecation") - public static class WriteStringToFile { - @BeforeTemplate - void before(File a, String s) throws Exception { - FileUtils.writeStringToFile(a, s); - } - - @AfterTemplate - void after(File a, String s) throws Exception { - Files.write(a.toPath(), s.getBytes()); - } - } -} diff --git a/src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheFileUtilsToJavaFiles.java b/src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheFileUtilsToJavaFiles.java deleted file mode 100644 index 17307ef6d6..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheFileUtilsToJavaFiles.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2021 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.io; - -import org.openrewrite.ExecutionContext; -import org.openrewrite.Preconditions; -import org.openrewrite.Recipe; -import org.openrewrite.TreeVisitor; -import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.JavaTemplate; -import org.openrewrite.java.MethodMatcher; -import org.openrewrite.java.search.UsesType; -import org.openrewrite.java.tree.J; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -public class ApacheFileUtilsToJavaFiles extends Recipe { - @Override - public String getDisplayName() { - return "Prefer `java.nio.file.Files`"; - } - - @Override - public String getDescription() { - return "Prefer the Java standard library's `java.nio.file.Files` over third-party usage of apache's `apache.commons.io.FileUtils`."; - } - - @Override - public Set getTags() { - return new HashSet<>(Arrays.asList("apache", "commons")); - } - - @Override - public TreeVisitor getVisitor() { - return Preconditions.check(new UsesType<>("org.apache.commons.io.FileUtils", false), new JavaIsoVisitor() { - private final MethodMatcher readFileToByteArrayMatcher = new MethodMatcher("org.apache.commons.io.FileUtils readFileToByteArray(java.io.File)"); - private final MethodMatcher readLinesToByteArrayMatcher = new MethodMatcher("org.apache.commons.io.FileUtils readLines(java.io.File)"); - private final MethodMatcher readLinesWithCharsetToByteArrayMatcher = new MethodMatcher("org.apache.commons.io.FileUtils readLines(java.io.File, java.nio.charset.Charset)"); - private final MethodMatcher readLinesWithCharsetIdToByteArrayMatcher = new MethodMatcher("org.apache.commons.io.FileUtils readLines(java.io.File, String)"); - - @Override - public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) { - J.CompilationUnit c = super.visitCompilationUnit(cu, ctx); - if (c != cu) { - maybeAddImport("java.nio.file.Files"); - maybeRemoveImport("org.apache.commons.io.FileUtils"); - } - return c; - } - - @Override - public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) { - J.MethodInvocation mi = super.visitMethodInvocation(method, ctx); - if (readFileToByteArrayMatcher.matches(mi)) { - return JavaTemplate.builder("Files.readAllBytes(#{any(java.io.File)}.toPath())") - .imports("java.nio.file.Files") - .build() - .apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0)); - } else if (readLinesToByteArrayMatcher.matches(mi)) { - return JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath())") - .imports("java.nio.file.Files") - .build() - .apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0)); - } else if (readLinesWithCharsetToByteArrayMatcher.matches(mi)) { - return JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath(), #{any(java.nio.charset.Charset)})") - .imports("java.nio.file.Files", "java.nio.charset.Charset") - .build() - .apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0), mi.getArguments().get(1)); - } else if (readLinesWithCharsetIdToByteArrayMatcher.matches(mi)) { - return JavaTemplate.builder("Files.readAllLines(#{any(java.io.File)}.toPath(), Charset.forName(#{any(String)}))") - .imports("java.nio.file.Files", "java.nio.charset.Charset") - .build() - .apply(updateCursor(mi), mi.getCoordinates().replace(), mi.getArguments().get(0), mi.getArguments().get(1)); - } - return mi; - } - }); - } -} diff --git a/src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheIOUtilsUseExplicitCharset.java b/src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheIOUtilsUseExplicitCharset.java deleted file mode 100644 index 3fa0a75e10..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/apache/commons/io/ApacheIOUtilsUseExplicitCharset.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.io; - -import lombok.EqualsAndHashCode; -import lombok.Value; -import org.openrewrite.*; -import org.openrewrite.internal.lang.Nullable; -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.UsesType; -import org.openrewrite.java.tree.J; - -import java.util.*; - -@Value -@EqualsAndHashCode(callSuper = false) -public class ApacheIOUtilsUseExplicitCharset extends Recipe { - - private static final Map MATCHER_TEMPLATES = new HashMap<>(); - // `IOUtils.toByteArray(java.lang.String)` is unique It's converted to String#getBytes() - private static final MethodMatcher STRING_GET_BYTES = new MethodMatcher("org.apache.commons.io.IOUtils toByteArray(java.lang.String)"); - - static { - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils copy(java.io.InputStream, java.io.Writer)"), "copy(#{any(java.io.InputStream)}, #{any(java.io.Writer)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils copy(java.io.Reader, java.io.OutputStream)"), "copy(#{any(java.io.InputStream)}, #{any(java.io.OutputStream)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils readLines(java.io.InputStream)"), "readLines(#{any(java.io.InputStream)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils toByteArray(java.io.Reader)"), "toByteArray(#{any(java.io.Reader)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils toCharArray(java.io.InputStream)"), "toCharArray(#{any(java.io.InputStream)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils toInputStream(java.lang.CharSequence)"), "toInputStream(#{any(java.lang.CharSequence)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils toInputStream(java.lang.String)"), "toInputStream(#{any(java.lang.String)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils toString(byte[])"), "toString(#{anyArray(byte)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils toString(java.io.InputStream)"), "toString(#{any(java.io.InputStream)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils toString(java.net.URI)"), "toString(#{any(java.net.URI)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils toString(java.net.URL)"), "toString(#{any(java.net.URL)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils write(byte[], java.io.Writer)"), "write(#{anyArray(byte)}, #{any(java.io.Writer)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils write(char[], java.io.OutputStream)"), "write(#{anyArray(char)}, #{any(java.io.OutputStream)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils write(java.lang.CharSequence, java.io.OutputStream)"), "write(#{any(java.lang.CharSequence)}, #{any(java.io.OutputStream)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils write(java.lang.String, java.io.OutputStream)"), "write(#{any(java.lang.String)}, #{any(java.io.OutputStream)}, StandardCharsets.#{})"); - MATCHER_TEMPLATES.put(new MethodMatcher("org.apache.commons.io.IOUtils write(java.lang.StringBuffer, java.io.OutputStream)"), "write(#{any(java.lang.StringBuffer)}, #{any(java.io.OutputStream)}, StandardCharsets.#{})"); - } - - @Option(displayName = "Default encoding", - description = "The default encoding to use, must be a standard charset.", - example = "UTF_8", - required = false) - @Nullable - String encoding; - - @Override - public String getDisplayName() { - return "Use IOUtils method that include their charset encoding"; - } - - @Override - public String getDescription() { - return "Use `IOUtils` method invocations that include the charset encoding instead of using the deprecated versions that do not include a charset encoding. (e.g. converts `IOUtils.readLines(inputStream)` to `IOUtils.readLines(inputStream, StandardCharsets.UTF_8)`."; - } - - @Override - public Set getTags() { - return new HashSet<>(Arrays.asList("apache", "commons")); - } - - @Override - public Validated validate() { - return super.validate().and(Validated.test("encoding", "Invalid encoding must be a standard Charset", - encoding, e -> e == null || e.matches("US_ASCII|ISO_8859_1|UTF_8|UTF_16BE|UTF_16LE|UTF_16"))); - } - - @Override - public TreeVisitor getVisitor() { - return Preconditions.check(new UsesType<>("org.apache.commons.io.IOUtils", false), new JavaIsoVisitor() { - private final JavaParser.Builder javaParser = JavaParser.fromJavaVersion().classpath("commons-io"); - - @Override - public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) { - J.MethodInvocation mi = super.visitMethodInvocation(method, ctx); - if (STRING_GET_BYTES.matches(mi)) { - mi = mi.withSelect(method.getArguments().get(0)); - //noinspection ConstantConditions - mi = mi.withMethodType(mi.getMethodType().withName("getBytes")); - mi = JavaTemplate.builder("#{any(String)}.getBytes(StandardCharsets.#{})}") - .javaParser(javaParser) - .imports("java.nio.charset.StandardCharsets") - .build() - .apply(updateCursor(mi), - mi.getCoordinates().replaceMethod(), - mi.getArguments().get(0), encoding == null ? "UTF_8" : encoding); - } else { - for (Map.Entry entry : MATCHER_TEMPLATES.entrySet()) { - if (entry.getKey().matches(mi)) { - List args = new ArrayList<>(mi.getArguments()); - args.add(encoding == null ? "UTF_8" : encoding); - mi = JavaTemplate.builder(entry.getValue()) - .contextSensitive() - .javaParser(javaParser) - .imports("java.nio.charset.StandardCharsets") - .build() - .apply(updateCursor(mi), - mi.getCoordinates().replaceMethod(), args.toArray()); - } - } - } - if (method != mi) { - maybeAddImport("java.nio.charset.StandardCharsets"); - } - return mi; - } - }); - } -} diff --git a/src/main/java/org/openrewrite/java/migrate/apache/commons/io/package-info.java b/src/main/java/org/openrewrite/java/migrate/apache/commons/io/package-info.java deleted file mode 100644 index 3222f06891..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/apache/commons/io/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2021 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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. - */ -@NonNullApi -@NonNullFields -package org.openrewrite.java.migrate.apache.commons.io; - -import org.openrewrite.internal.lang.NonNullApi; -import org.openrewrite.internal.lang.NonNullFields; diff --git a/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/ApacheCommonsStringUtils.java b/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/ApacheCommonsStringUtils.java deleted file mode 100644 index 1b1e8d4702..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/ApacheCommonsStringUtils.java +++ /dev/null @@ -1,703 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.lang; - -import com.google.errorprone.refaster.annotation.AfterTemplate; -import com.google.errorprone.refaster.annotation.BeforeTemplate; -import org.apache.commons.lang3.StringUtils; -import org.openrewrite.java.template.Matches; -import org.openrewrite.java.template.RecipeDescriptor; - -import java.util.Objects; - -@SuppressWarnings("ALL") -public class ApacheCommonsStringUtils { - - @RecipeDescriptor( - name = "Replace `StringUtils.abbreviate(String, int)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.abbreviate(String str, int maxWidth)` with JDK provided API.") - public static class Abbreviate { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s1, - @Matches(RepeatableArgumentMatcher.class) int width) { - return StringUtils.abbreviate(s1, width); - } - - @AfterTemplate - String after(String s, int width) { - return (s == null || s.length() <= width ? s : s.substring(0, width - 3) + "..."); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.capitalize(String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.capitalize(String str)` with JDK provided API.") - @SuppressWarnings("ConstantValue") - public static class Capitalize { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.capitalize(s); - } - - @AfterTemplate - String after(String s) { - return (s == null || s.isEmpty() || Character.isTitleCase(s.charAt(0)) ? s : Character.toTitleCase(s.charAt(0)) + s.substring(1)); - } - } - - //NOTE: The test for this recipe fails, I think it could be due to a `rewrite-templating` bug - //public static class Chomp { - // @BeforeTemplate - // String before(String s) { - // return StringUtils.chomp(s); - // } - - // @AfterTemplate - // String after(String s) { - // return (s == null ? null : (s.endsWith("\n") ? s.substring(0, s.length() - 1) : s)); - // } - //} - - // NOTE: fails with __P__. inserted - //public static class Chop { - // @BeforeTemplate - // String before(String s) { - // return StringUtils.chop(s); - // } - // - // @AfterTemplate - // String after(String s) { - // return (s == null ? - // null : s.length() < 2 ? - // "" : s.endsWith("\r\n") ? - // s.substring(0, s.length() - 2) : s.substring(0, s.length() - 1)); - // } - //} - - // NOTE: not sure if accurate replacement - //public static class Contains { - // @BeforeTemplate - // boolean before(String s, String search) { - // return StringUtils.contains(s, search); - // } - // - // @AfterTemplate - // boolean after(String s, String search) { - // return (s != null && search != null && s.contains(search)); - // } - //} - - // NOTE: Requires Java 9+ for s.chars() - //public static class CountMatchesChar { - // @BeforeTemplate - // int before(String s, char pattern) { - // return StringUtils.countMatches(s, pattern); - // } - // - // @AfterTemplate - // int after(String s, char pattern) { - // return (s == null || s.isEmpty() ? 0 : (int) s.chars().filter(c -> c == pattern).count()); - // } - //} - - @RecipeDescriptor( - name = "Replace `StringUtils.defaultString(String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.defaultString(String str)` with JDK provided API.") - public static class DefaultString { - @BeforeTemplate - String before(String s) { - return StringUtils.defaultString(s); - } - - @AfterTemplate - String after(String s) { - return Objects.toString(s, ""); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.defaultString(String, String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.defaultString(String str, String nullDefault)` with JDK provided API.") - public static class DefaultStringFallback { - @BeforeTemplate - String before(String s, String nullDefault) { - return StringUtils.defaultString(s, nullDefault); - } - - @AfterTemplate - String after(String s, String nullDefault) { - return Objects.toString(s, nullDefault); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.deleteWhitespace(String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.deleteWhitespace(String str)` with JDK provided API.") - public static class DeleteWhitespace { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.deleteWhitespace(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.replaceAll("\\s+", "")); - } - } - - // NOTE: unlikely to go over well due to added complexity - //public static class EndsWithIgnoreCase { - // @BeforeTemplate - // boolean before(String s, String suffix) { - // return StringUtils.endsWithIgnoreCase(s, suffix); - // } - // - // @AfterTemplate - // boolean after(String s, String suffix) { - // return (s == null && suffix == null || s != null && suffix != null && s.regionMatches(true, s.length() - suffix.length(), suffix, 0, suffix.length())); - // } - //} - - @RecipeDescriptor( - name = "Replace `StringUtils.equalsIgnoreCase(CharSequence, CharSequence)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.equalsIgnoreCase(CharSequence cs1, CharSequence cs2)` with JDK provided API.") - public static class EqualsIgnoreCase { - @BeforeTemplate - boolean before(@Matches(RepeatableArgumentMatcher.class) String s, - @Matches(RepeatableArgumentMatcher.class) String other) { - return StringUtils.equalsIgnoreCase(s, other); - } - - @AfterTemplate - boolean after(String s, String other) { - return (s == null ? other == null : s.equalsIgnoreCase(other)); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.equals(CharSequence, CharSequence)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.equals(CharSequence cs1, CharSequence cs2)` with JDK provided API.") - public static class Equals { - @BeforeTemplate - boolean before(String s, String other) { - return StringUtils.equals(s, other); - } - - @AfterTemplate - boolean after(String s, String other) { - return Objects.equals(s, other); - } - } - - // NOTE: unlikely to go over well due to added complexity - //public static class IndexOfAny { - // @BeforeTemplate - // int before(String s, String searchChars) { - // return StringUtils.indexOfAny(s, searchChars); - // } - // - // @AfterTemplate - // int after(String s, String searchChars) { - // return searchChars == null || searchChars.isEmpty() ? -1 : - // IntStream.range(0, searchChars.length()) - // .map(searchChars::charAt) - // .map(s::indexOf) - // .min() - // .orElse(-1); - // } - //} - - // NOTE: not sure if accurate replacement - //public static class IsAlphanumericSpace { - // @BeforeTemplate - // boolean before(String s) { - // return StringUtils.isAlphanumericSpace(s); - // } - - // boolean after(String s) { - // return (s != null && s.matches("^[a-zA-Z0-9\\s]*$")); - // } - //} - - - // `chars()` is only in Java 9+ - //public static class IsAlphanumeric { - // @BeforeTemplate - // boolean before(@Matches(RepeatableArgumentMatcher.class) String s) { - // return StringUtils.isAlphanumeric(s); - // } - // - // @AfterTemplate - // boolean after(String s) { - // return (s != null && !s.isEmpty() && s.chars().allMatch(Character::isLetterOrDigit)); - // } - //} - - // NOTE: not sure if accurate replacement - //public static class IsAlphaSpace { - // @BeforeTemplate - // boolean before(String s) { - // return StringUtils.isAlphaSpace(s); - // } - - // @AfterTemplate - // boolean after(String s) { - // return (s != null && s.matches("[a-zA-Z\\s]+")); - // } - //} - - //public static class StripAll { - // @BeforeTemplate - // String[] before(String[] s) { - // return StringUtils.stripAll(s); - // } - - // @AfterTemplate - // String[] after(String[] s) { - // return Arrays.stream(s) - // .map(String::trim) - // .toArray(String[]::new); - // } - //} - - // `chars()` is only in Java 9+ - //public static class IsAlpha { - // @BeforeTemplate - // boolean before(@Matches(RepeatableArgumentMatcher.class) String s) { - // return StringUtils.isAlpha(s); - // } - // - // @AfterTemplate - // boolean after(String s) { - // return (s != null && !s.isEmpty() && s.chars().allMatch(Character::isLetter)); - // } - //} - - // NOTE: better handled by `org.openrewrite.java.migrate.apache.commons.lang.IsNotEmptyToJdk` - //public static class IsEmpty { - // @BeforeTemplate - // boolean before(String s) { - // return StringUtils.isEmpty(s); - // } - // - // @AfterTemplate - // boolean after(String s) { - // return (s == null || s.isEmpty()); - // } - //} - - // NOTE: These two methods don't generate the recipe templates right - //public static class LeftPad { - // @BeforeTemplate - // String before(String s, int l) { - // return StringUtils.leftPad(s, l); - // } - // @AfterTemplate - // String after(String s, int l) { - // return String.format("%" + l + "s", s); - // } - //} - - //public static class RightPad { - // @BeforeTemplate - // String before(String s, int l) { - // return StringUtils.rightPad(s, l); - // } - // @AfterTemplate - // String after(String s, int l) { - // return String.format("%" + (-l) + "s", s); - // } - //} - - //public static class Join { - // @BeforeTemplate - // String before(String s) { - // return StringUtils.join(s); - // } - // - // @AfterTemplate - // String after(String s) { - // return (s == null ? null : String.join("", s)); - // } - //} - - // NOTE: not sure if accurate replacement - @SuppressWarnings("ConstantValue") - //public static class Left { - // @BeforeTemplate - // String before(String s, int l) { - // return StringUtils.left(s, l); - // } - - // @AfterTemplate - // String after(String s, int l) { - // return (s == null ? null : s.substring(s.length() - l, s.length() - 1)); - // } - //} - - @RecipeDescriptor( - name = "Replace `StringUtils.lowerCase(String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.lowerCase(String str)` with JDK provided API.") - public static class Lowercase { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.lowerCase(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.toLowerCase()); - } - } - - // NOTE: not sure if accurate replacement - //public static class Mid { - // @BeforeTemplate - // String before(String s, int p, int l) { - // return StringUtils.mid(s, p, l); - // } - - // @AfterTemplate - // String after(String s, int p, int l) { - // return (s == null ? null : (p + l < s.length() ? s.substring(p, p + l) : s.substring(p, s.length() - 1))); - // } - //} - - // NOTE: not sure if accurate replacement - //public static class Overlay { - // @BeforeTemplate - // String before(String s, int w, int l, String overlay) { - // return StringUtils.overlay(s, overlay, w, l); - // } - - // @AfterTemplate - // String after(String s, int w, int l, String overlay) { - // return (s == null ? null : s.substring(0, w) + overlay + s.substring(l)); - // } - //} - - // NOTE: Similar issues to what LeftPad and RightPad have - //public static class Center { - // @BeforeTemplate - // String before(String s, int size) { - // return StringUtils.center(s, size); - // } - - // @AfterTemplate - // String after(String s, int size) { - // return String.format("%" + size + "s" + s + "%" + size + "s", "", ""); - // } - //} - - @RecipeDescriptor( - name = "Replace `StringUtils.removeEnd(String, String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.removeEnd(String str, String remove)` with JDK provided API.") - public static class RemoveEnd { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s, - @Matches(RepeatableArgumentMatcher.class) String end) { - return StringUtils.removeEnd(s, end); - } - - @AfterTemplate - String after(String s, String end) { - return (s == null || s.isEmpty() || end == null || end.isEmpty() || !s.endsWith(end) ? - s : s.substring(0, s.length() - end.length())); - } - } - - //public static class Repeat { - // @BeforeTemplate - // String before(String s, int l) { - // return StringUtils.repeat(s, l); - // } - // - // @AfterTemplate - // String after(String s, int l) { - // return (s == null ? null : new String(new char[l]).replace("\0", s)); - // } - //} - - // NOTE: requires dedicated recipe to clean up `Pattern.quote(",")` - //public static class ReplaceOnce { - // @BeforeTemplate - // String before(String s, String search, String replacement) { - // return StringUtils.replaceOnce(s, search, replacement); - // } - // - // @AfterTemplate - // String after(String s, String search, String replacement) { - // return (s == null || s.isEmpty() || search == null || search.isEmpty() || replacement == null ? s : s.replaceFirst(Pattern.quote(search), replacement)); - // } - //} - - @RecipeDescriptor( - name = "Replace `StringUtils.replace(String, String, String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.replace(String text, String searchString, String replacement)` with JDK provided API.") - public static class Replace { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s, - @Matches(RepeatableArgumentMatcher.class) String search, - @Matches(RepeatableArgumentMatcher.class) String replacement) { - return StringUtils.replace(s, search, replacement); - } - - @AfterTemplate - String after(String s, String search, String replacement) { - return (s == null || s.isEmpty() || search == null || search.isEmpty() || replacement == null ? s : s.replace(search, replacement)); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.reverse(String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.reverse(String str)` with JDK provided API.") - public static class Reverse { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.reverse(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : new StringBuilder(s).reverse().toString()); - } - } - - // NOTE: not sure if accurate replacement - //public static class Right { - // @BeforeTemplate - // String before(String s, int l) { - // return StringUtils.right(s, l); - // } - - // @AfterTemplate - // String after(String s, int l) { - // return (s == null ? null : s.substring(s.length() - l, s.length() - 1)); - // } - //} - - @RecipeDescriptor( - name = "Replace `StringUtils.split(String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.split(String str)` with JDK provided API.") - public static class Split { - @BeforeTemplate - String[] before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.split(s); - } - - @AfterTemplate - String[] after(String s) { - return (s == null ? null : s.split("\\s+")); - } - } - - // NOTE: requires dedicated recipe to clean up `Pattern.quote(",")` - //public static class SplitSeparator { - // @BeforeTemplate - // String[] before(String s, String arg) { - // return StringUtils.split(s, arg); - // } - // - // @AfterTemplate - // String[] after(String s, String arg) { - // return (s == null ? null : s.split(Pattern.quote(arg))); - // } - //} - - // NOTE: different semantics in handling max=0 to discard trailing empty strings - //public static class SplitSeparatorMax { - // @BeforeTemplate - // String[] before(String s, String arg, int max) { - // return StringUtils.split(s, arg, max); - // } - // - // @AfterTemplate - // String[] after(String s, String arg, int max) { - // return (s == null ? null : s.split(Pattern.quote(arg), max)); - // } - //} - - @RecipeDescriptor( - name = "Replace `StringUtils.strip(String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.strip(String str)` with JDK provided API.") - public static class Strip { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.strip(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.trim()); - } - } - - // NOTE: suffix is a set of characters, not a complete literal string - //public static class StripEnd { - // @BeforeTemplate - // String before(String s, String suffix) { - // return StringUtils.stripEnd(s, suffix); - // } - // - // @AfterTemplate - // String after(String s, String suffix) { - // return (s == null ? null : (s.endsWith(suffix) ? s.substring(0, s.lastIndexOf(suffix)) : s)); - // } - //} - - // NOTE: suffix is a set of characters, not a complete literal string - //public static class StripStart { - // @BeforeTemplate - // String before(String s, String chars) { - // return StringUtils.stripStart(s, chars); - // } - // - // @AfterTemplate - // String after(String s, String chars) { - // return (s == null ? null : (s.startsWith(chars) ? s.substring(chars.length()) : s)); - // } - //} - - // NOTE: not sure if accurate replacement - //public static class StartsWith { - // @BeforeTemplate - // boolean before(String s, String prefix) { - // return StringUtils.startsWith(s, prefix); - // } - - // @AfterTemplate - // boolean after(String s, String prefix) { - // return (s == null || prefix == null ? null : s.startsWith(prefix)); - // } - //} - - // NOTE: Incorrect handling of before null/empty and separator null/empty - //public static class SubstringAfter { - // @BeforeTemplate - // String before(String s, String sep) { - // return StringUtils.substringAfter(s, sep); - // } - // - // @AfterTemplate - // String after(String s, String sep) { - // return (s == null ? null : s.substring(s.indexOf(sep) + 1, s.length())); - // } - //} - - // NOTE: Incorrect handling of negative values - //public static class Substring { - // @BeforeTemplate - // String before(String s, int l, int w) { - // return StringUtils.substring(s, l, w); - // } - // - // @AfterTemplate - // String after(String s, int l, int w) { - // return (s == null ? null : s.substring(l, w)); - // } - //} - - // NOTE: fails to account for isTitleCase - //public static class SwapCase { - // @BeforeTemplate - // String before(String s, char sep) { - // return StringUtils.swapCase(s); - // } - // - // @AfterTemplate - // String after(String s) { - // return (s == null ? null : s.chars() - // .map(c -> Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c)) - // .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) - // .toString()); - // } - //} - - @RecipeDescriptor( - name = "Replace `StringUtils.trimToEmpty(String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.trimToEmpty(String str)` with JDK provided API.") - @SuppressWarnings("ConstantValue") - public static class TrimToEmpty { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.trimToEmpty(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? "" : s.trim()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.trimToNull(String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.trimToNull(String str)` with JDK provided API.") - @SuppressWarnings("ConstantValue") - public static class TrimToNull { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.trimToNull(s); - } - - @AfterTemplate - String after(String s) { - return (s == null || s.trim().isEmpty() ? null : s.trim()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.trim(String)` with JDK provided API", - description = "Replace Apache Commons `StringUtils.trim(String str)` with JDK provided API.") - public static class Trim { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.trim(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.trim()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.upperCase(String)` with JDK internals", - description = "Replace Apache Commons `StringUtils.upperCase(String str)` with JDK internals.") - public static class Uppercase { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.upperCase(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.toUpperCase()); - } - } - - // NOTE: breaks on empty strings - //public static class Uncapitalize { - // @BeforeTemplate - // String before(String s) { - // return StringUtils.uncapitalize(s); - // } - // - // @AfterTemplate - // String after(String s) { - // return (s == null ? null : Character.toLowerCase(s.charAt(0)) + s.substring(1)); - // } - //} -} diff --git a/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/IsNotEmptyToJdk.java b/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/IsNotEmptyToJdk.java deleted file mode 100644 index 6b4954c700..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/IsNotEmptyToJdk.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.lang; - -import org.openrewrite.ExecutionContext; -import org.openrewrite.Preconditions; -import org.openrewrite.Recipe; -import org.openrewrite.TreeVisitor; -import org.openrewrite.java.JavaTemplate; -import org.openrewrite.java.JavaVisitor; -import org.openrewrite.java.MethodMatcher; -import org.openrewrite.java.search.UsesMethod; -import org.openrewrite.java.template.Semantics; -import org.openrewrite.java.tree.Expression; -import org.openrewrite.java.tree.J; - -import java.time.Duration; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import static org.openrewrite.java.migrate.apache.commons.lang.RepeatableArgumentMatcher.isRepeatableArgument; - -public class IsNotEmptyToJdk extends Recipe { - - @Override - public String getDisplayName() { - return "Replace any StringUtils#isEmpty(String) and #isNotEmpty(String)"; - } - - @Override - public String getDescription() { - return "Replace any `StringUtils#isEmpty(String)` and `#isNotEmpty(String)` with `s == null || s.isEmpty()` and `s != null && !s.isEmpty()`."; - } - - @Override - public Duration getEstimatedEffortPerOccurrence() { - return Duration.ofMinutes(1); - } - - @Override - public Set getTags() { - return new HashSet<>(Arrays.asList("apache", "commons")); - } - - @Override - public TreeVisitor getVisitor() { - TreeVisitor precondition = Preconditions.or( - new UsesMethod<>("org.apache.commons.lang3.StringUtils isEmpty(..)"), - new UsesMethod<>("org.apache.commons.lang3.StringUtils isNotEmpty(..)"), - new UsesMethod<>("org.apache.maven.shared.utils.StringUtils isEmpty(..)"), - new UsesMethod<>("org.apache.maven.shared.utils.StringUtils isNotEmpty(..)"), - new UsesMethod<>("org.codehaus.plexus.util.StringUtils isEmpty(..)"), - new UsesMethod<>("org.codehaus.plexus.util.StringUtils isNotEmpty(..)")); - - return Preconditions.check(precondition, new JavaVisitor() { - private final MethodMatcher isEmptyMatcher = new MethodMatcher("*..StringUtils isEmpty(..)"); - private final MethodMatcher isNotEmptyMatcher = new MethodMatcher("*..StringUtils isNotEmpty(..)"); - private final MethodMatcher trimMatcher = new MethodMatcher("java.lang.String trim()"); - - private final JavaTemplate isEmptyReplacement = Semantics.expression(this, "IsEmpty", (String s) -> (s == null || s.isEmpty())).build(); - private final JavaTemplate isNotEmptyReplacement = Semantics.expression(this, "IsNotEmpty", (String s) -> (s != null && !s.isEmpty())).build(); - private final JavaTemplate isEmptyTrimmed = Semantics.expression(this, "IsEmptyTrimmed", (String s) -> s.trim().isEmpty()).build(); - private final JavaTemplate isNotEmptyTrimmed = Semantics.expression(this, "IsNotEmptyTrimmed", (String s) -> !s.trim().isEmpty()).build(); - - @Override - public J visitMethodInvocation(J.MethodInvocation mi, ExecutionContext ctx) { - boolean isEmptyCall = isEmptyMatcher.matches(mi); - if (!isEmptyCall && !isNotEmptyMatcher.matches(mi)) { - return mi; - } - - Expression arg = mi.getArguments().get(0); - - // Replace StringUtils.isEmpty(var) with var == null || var.isEmpty() - if (isRepeatableArgument(arg)) { - JavaTemplate replacementTemplate = isEmptyCall ? isEmptyReplacement : isNotEmptyReplacement; - // Maybe remove imports - maybeRemoveImport("org.apache.commons.lang3.StringUtils"); - maybeRemoveImport("org.apache.maven.shared.utils.StringUtils"); - maybeRemoveImport("org.codehaus.plexus.util.StringUtils"); - // Remove excess parentheses inserted in lambda that may be required depending on the context - doAfterVisit(new org.openrewrite.staticanalysis.UnnecessaryParentheses().getVisitor()); - return replacementTemplate.apply(updateCursor(mi), mi.getCoordinates().replace(), arg); - } - - // Replace StringUtils.isEmpty(var.trim()) with var.trim().isEmpty() - if (trimMatcher.matches(arg) - && (((J.MethodInvocation) arg).getSelect() instanceof J.Identifier || ((J.MethodInvocation) arg).getSelect() instanceof J.FieldAccess)) { - JavaTemplate replacementTemplate = isEmptyCall ? isEmptyTrimmed : isNotEmptyTrimmed; - // Maybe remove imports - maybeRemoveImport("org.apache.commons.lang3.StringUtils"); - maybeRemoveImport("org.apache.maven.shared.utils.StringUtils"); - maybeRemoveImport("org.codehaus.plexus.util.StringUtils"); - return replacementTemplate.apply(updateCursor(mi), mi.getCoordinates().replace(), ((J.MethodInvocation) arg).getSelect()); - } - - return super.visitMethodInvocation(mi, ctx); - } - }); - } -} diff --git a/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/RepeatableArgumentMatcher.java b/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/RepeatableArgumentMatcher.java deleted file mode 100644 index 560bef8738..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/RepeatableArgumentMatcher.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.lang; - -import org.openrewrite.java.template.Matcher; -import org.openrewrite.java.tree.Expression; -import org.openrewrite.java.tree.J; -import org.openrewrite.java.tree.TypeUtils; - -public class RepeatableArgumentMatcher implements Matcher { - /** - * @param arg an argument to a method invocation - * @return true if the argument is a simple getter that returns a String, or an identifier or field access - */ - static boolean isRepeatableArgument(Expression arg) { - if (arg instanceof J.Literal || arg instanceof J.Identifier || arg instanceof J.FieldAccess) { - return true; - } - // Allow simple getters that return a String - return arg instanceof J.MethodInvocation - && ((J.MethodInvocation) arg).getSelect() instanceof J.Identifier - && ((J.MethodInvocation) arg).getSimpleName().startsWith("get") - && (((J.MethodInvocation) arg).getArguments().isEmpty() || ((J.MethodInvocation) arg).getArguments().get(0) instanceof J.Empty) - && TypeUtils.isAssignableTo("java.lang.String", ((J.MethodInvocation) arg).getMethodType()); - } - - @Override - public boolean matches(Expression expr) { - return isRepeatableArgument(expr); - } -} diff --git a/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/package-info.java b/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/package-info.java deleted file mode 100644 index 6be5403e53..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/apache/commons/lang/package-info.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2021 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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. - */ -@NonNullApi -package org.openrewrite.java.migrate.apache.commons.lang; - -import org.openrewrite.internal.lang.NonNullApi; diff --git a/src/main/java/org/openrewrite/java/migrate/maven/shared/MavenSharedStringUtils.java b/src/main/java/org/openrewrite/java/migrate/maven/shared/MavenSharedStringUtils.java deleted file mode 100644 index 860feaab3b..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/maven/shared/MavenSharedStringUtils.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.maven.shared; - -import com.google.errorprone.refaster.annotation.AfterTemplate; -import com.google.errorprone.refaster.annotation.BeforeTemplate; -import org.apache.maven.shared.utils.StringUtils; -import org.openrewrite.java.migrate.apache.commons.lang.RepeatableArgumentMatcher; -import org.openrewrite.java.template.Matches; -import org.openrewrite.java.template.RecipeDescriptor; - -import java.util.Objects; - -@SuppressWarnings("ALL") -public class MavenSharedStringUtils { - @RecipeDescriptor( - name = "Replace `StringUtils.abbreviate(String, int)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.abbreviate(String str, int maxWidth)` with JDK provided API.") - public static class Abbreviate { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s1, - @Matches(RepeatableArgumentMatcher.class) int width) { - return StringUtils.abbreviate(s1, width); - } - - @AfterTemplate - String after(String s, int width) { - return (s.length() <= width ? s : s.substring(0, width - 3) + "..."); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.capitalise(String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.capitalise(String str)` with JDK provided API.") - @SuppressWarnings("ConstantValue") - public static class Capitalise { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.capitalise(s); - } - - @AfterTemplate - String after(String s) { - return (s == null || s.isEmpty() ? s : Character.toTitleCase(s.charAt(0)) + s.substring(1)); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.defaultString(Object)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.defaultString(Object obj)` with JDK provided API.") - public static class DefaultString { - @BeforeTemplate - String before(String s) { - return StringUtils.defaultString(s); - } - - @AfterTemplate - String after(String s) { - return Objects.toString(s, ""); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.defaultString(Object, String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.defaultString(Object obj, String nullDefault)` with JDK provided API.") - public static class DefaultStringFallback { - @BeforeTemplate - String before(String s, String nullDefault) { - return StringUtils.defaultString(s, nullDefault); - } - - @AfterTemplate - String after(String s, String nullDefault) { - return Objects.toString(s, nullDefault); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.deleteWhitespace(String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.deleteWhitespace(String str)` with JDK provided API.") - public static class DeleteWhitespace { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.deleteWhitespace(s); - } - - @AfterTemplate - String after(String s) { - return s.replaceAll("\\s+", ""); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.equalsIgnoreCase(String, String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.equalsIgnoreCase(String str1, String str2)` with JDK provided API.") - public static class EqualsIgnoreCase { - @BeforeTemplate - boolean before(@Matches(RepeatableArgumentMatcher.class) String s, - @Matches(RepeatableArgumentMatcher.class) String other) { - return StringUtils.equalsIgnoreCase(s, other); - } - - @AfterTemplate - boolean after(String s, String other) { - return (s == null ? other == null : s.equalsIgnoreCase(other)); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.equals(String, String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.equals(String str1, String str2)` with JDK provided API.") - public static class Equals { - @BeforeTemplate - boolean before(String s, String other) { - return StringUtils.equals(s, other); - } - - @AfterTemplate - boolean after(String s, String other) { - return Objects.equals(s, other); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.lowerCase(String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.lowerCase(String str)` with JDK provided API.") - public static class Lowercase { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.lowerCase(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.toLowerCase()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.replace(String, String, String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.replace(String text, String searchString, String replacement)` with JDK provided API.") - public static class Replace { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s, - @Matches(RepeatableArgumentMatcher.class) String search, - @Matches(RepeatableArgumentMatcher.class) String replacement) { - return StringUtils.replace(s, search, replacement); - } - - @AfterTemplate - String after(String s, String search, String replacement) { - return (s == null || s.isEmpty() || search == null || search.isEmpty() || replacement == null ? s : s.replace(search, replacement)); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.reverse(String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.reverse(String str)` with JDK provided API.") - public static class Reverse { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.reverse(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : new StringBuffer(s).reverse().toString()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.split(String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.split(String str)` with JDK provided API.") - public static class Split { - @BeforeTemplate - String[] before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.split(s); - } - - @AfterTemplate - String[] after(String s) { - return s.split("\\s+"); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.strip(String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.strip(String str)` with JDK provided API.") - public static class Strip { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.strip(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.trim()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.trim(String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.trim(String str)` with JDK provided API.") - public static class Trim { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.trim(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.trim()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.upperCase(String)` with JDK provided API", - description = "Replace Maven Shared `StringUtils.upperCase(String str)` with JDK provided API.") - public static class Uppercase { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.upperCase(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.toUpperCase()); - } - } -} diff --git a/src/main/java/org/openrewrite/java/migrate/plexus/PlexusFileUtils.java b/src/main/java/org/openrewrite/java/migrate/plexus/PlexusFileUtils.java deleted file mode 100644 index c3fbe799fa..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/plexus/PlexusFileUtils.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.plexus; - -import com.google.errorprone.refaster.annotation.AfterTemplate; -import com.google.errorprone.refaster.annotation.BeforeTemplate; -import org.codehaus.plexus.util.FileUtils; -import org.openrewrite.java.template.RecipeDescriptor; - -import java.io.File; - -class PlexusFileUtils { - - // https://github.com/codehaus-plexus/plexus-utils/blob/master/src/main/java/org/codehaus/plexus/util/StringUtils.java - - @RecipeDescriptor( - name = "Replace `FileUtils.deleteDirectory(File)` with JDK provided API", - description = "Replace Plexus `FileUtils.deleteDirectory(File directory)` with JDK provided API.") - static class DeleteDirectoryFile { - @BeforeTemplate - void before(File dir) throws Exception { - FileUtils.deleteDirectory(dir); - } - - @AfterTemplate - void after(File dir) throws Exception { - org.apache.commons.io.FileUtils.deleteDirectory(dir); - } - } - - @RecipeDescriptor( - name = "Replace `FileUtils.deleteDirectory(String)` with JDK provided API", - description = "Replace Plexus `FileUtils.deleteDirectory(String directory)` with JDK provided API.") - static class DeleteDirectoryString { - @BeforeTemplate - void before(String dir) throws Exception { - FileUtils.deleteDirectory(dir); - } - - @AfterTemplate - void after(String dir) throws Exception { - org.apache.commons.io.FileUtils.deleteDirectory(new File(dir)); - } - } - - @RecipeDescriptor( - name = "Replace `FileUtils.fileExists(String)` with JDK provided API", - description = "Replace Plexus `FileUtils.fileExists(String fileName)` with JDK provided API.") - static class FileExistsString { - @BeforeTemplate - boolean before(String fileName) throws Exception { - return FileUtils.fileExists(fileName); - } - - @AfterTemplate - boolean after(String fileName) throws Exception { - return new File(fileName).exists(); - } - } - - @RecipeDescriptor( - name = "Replace `FileUtils.getFile(String)` with JDK provided API", - description = "Replace Plexus `FileUtils.getFile(String fileName)` with JDK provided API.") - static class GetFile { - @BeforeTemplate - File before(String fileName) throws Exception { - return FileUtils.getFile(fileName); - } - - @AfterTemplate - File after(String fileName) throws Exception { - return new File(fileName); - } - } -} diff --git a/src/main/java/org/openrewrite/java/migrate/plexus/PlexusStringUtils.java b/src/main/java/org/openrewrite/java/migrate/plexus/PlexusStringUtils.java deleted file mode 100644 index ed3ca4a8e1..0000000000 --- a/src/main/java/org/openrewrite/java/migrate/plexus/PlexusStringUtils.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.plexus; - -import com.google.errorprone.refaster.annotation.AfterTemplate; -import com.google.errorprone.refaster.annotation.BeforeTemplate; -import org.codehaus.plexus.util.StringUtils; -import org.openrewrite.java.migrate.apache.commons.lang.RepeatableArgumentMatcher; -import org.openrewrite.java.template.Matches; -import org.openrewrite.java.template.RecipeDescriptor; - -import java.util.Objects; - -@SuppressWarnings("ALL") -public class PlexusStringUtils { - @RecipeDescriptor( - name = "Replace `StringUtils.abbreviate(String, int)` with JDK provided API", - description = "Replace Plexus `StringUtils.abbreviate(String str, int maxWidth)` with JDK provided API.") - public static class Abbreviate { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s1, - @Matches(RepeatableArgumentMatcher.class) int width) { - return StringUtils.abbreviate(s1, width); - } - - @AfterTemplate - String after(String s, int width) { - return (s.length() <= width ? s : s.substring(0, width - 3) + "..."); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.capitalise(String)` with JDK provided API", - description = "Replace Plexus `StringUtils.capitalise(String str)` with JDK provided API.") - @SuppressWarnings("ConstantValue") - public static class Capitalise { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.capitalise(s); - } - - @AfterTemplate - String after(String s) { - return (s == null || s.isEmpty() ? s : Character.toTitleCase(s.charAt(0)) + s.substring(1)); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.defaultString(Object)` with JDK provided API", - description = "Replace Plexus `StringUtils.defaultString(Object obj)` with JDK provided API.") - public static class DefaultString { - @BeforeTemplate - String before(String s) { - return StringUtils.defaultString(s); - } - - @AfterTemplate - String after(String s) { - return Objects.toString(s, ""); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.defaultString(Object, String)` with JDK provided API", - description = "Replace Plexus `StringUtils.defaultString(Object obj, String nullDefault)` with JDK provided API.") - public static class DefaultStringFallback { - @BeforeTemplate - String before(String s, String nullDefault) { - return StringUtils.defaultString(s, nullDefault); - } - - @AfterTemplate - String after(String s, String nullDefault) { - return Objects.toString(s, nullDefault); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.deleteWhitespace(String)` with JDK provided API", - description = "Replace Plexus `StringUtils.deleteWhitespace(String str)` with JDK provided API.") - public static class DeleteWhitespace { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.deleteWhitespace(s); - } - - @AfterTemplate - String after(String s) { - return s.replaceAll("\\s+", ""); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.equalsIgnoreCase(String, String)` with JDK provided API", - description = "Replace Plexus `StringUtils.equalsIgnoreCase(String str1, String str2)` with JDK provided API.") - public static class EqualsIgnoreCase { - @BeforeTemplate - boolean before(@Matches(RepeatableArgumentMatcher.class) String s, - @Matches(RepeatableArgumentMatcher.class) String other) { - return StringUtils.equalsIgnoreCase(s, other); - } - - @AfterTemplate - boolean after(String s, String other) { - return (s == null ? other == null : s.equalsIgnoreCase(other)); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.equals(String, String)` with JDK provided API", - description = "Replace Plexus `StringUtils.equals(String str1, String str2)` with JDK provided API.") - public static class Equals { - @BeforeTemplate - boolean before(String s, String other) { - return StringUtils.equals(s, other); - } - - @AfterTemplate - boolean after(String s, String other) { - return Objects.equals(s, other); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.lowerCase(String)` with JDK provided API", - description = "Replace Plexus `StringUtils.lowerCase(String str)` with JDK provided API.") - public static class Lowercase { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.lowerCase(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.toLowerCase()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.replace(String, String, String)` with JDK provided API", - description = "Replace Plexus `StringUtils.replace(String text, String searchString, String replacement)` with JDK provided API.") - public static class Replace { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s, - @Matches(RepeatableArgumentMatcher.class) String search, - @Matches(RepeatableArgumentMatcher.class) String replacement) { - return StringUtils.replace(s, search, replacement); - } - - @AfterTemplate - String after(String s, String search, String replacement) { - return (s == null || s.isEmpty() || search == null || search.isEmpty() || replacement == null ? s : s.replace(search, replacement)); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.reverse(String)` with JDK provided API", - description = "Replace Plexus `StringUtils.reverse(String str)` with JDK provided API.") - public static class Reverse { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.reverse(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : new StringBuilder(s).reverse().toString()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.split(String)` with JDK provided API", - description = "Replace Plexus `StringUtils.split(String str)` with JDK provided API.") - public static class Split { - @BeforeTemplate - String[] before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.split(s); - } - - @AfterTemplate - String[] after(String s) { - return s.split("\\s+"); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.strip(String)` with JDK provided API", - description = "Replace Plexus `StringUtils.strip(String str)` with JDK provided API.") - public static class Strip { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.strip(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.trim()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.trim(String)` with JDK provided API", - description = "Replace Plexus `StringUtils.trim(String str)` with JDK provided API.") - public static class Trim { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.trim(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.trim()); - } - } - - @RecipeDescriptor( - name = "Replace `StringUtils.upperCase(String)` with JDK provided API", - description = "Replace Plexus `StringUtils.upperCase(String str)` with JDK provided API.") - public static class Uppercase { - @BeforeTemplate - String before(@Matches(RepeatableArgumentMatcher.class) String s) { - return StringUtils.upperCase(s); - } - - @AfterTemplate - String after(String s) { - return (s == null ? null : s.toUpperCase()); - } - } - -} diff --git a/src/main/resources/META-INF/rewrite/apache-commons-io.yml b/src/main/resources/META-INF/rewrite/apache-commons-io.yml deleted file mode 100644 index 279cbcadab..0000000000 --- a/src/main/resources/META-INF/rewrite/apache-commons-io.yml +++ /dev/null @@ -1,71 +0,0 @@ -# -# Copyright 2021 the original author or authors. -#

-# 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 -#

-# https://www.apache.org/licenses/LICENSE-2.0 -#

-# 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. -# ---- -type: specs.openrewrite.org/v1beta/recipe -name: org.openrewrite.java.migrate.apache.commons.io.RelocateApacheCommonsIo -displayName: Relocate `org.apache.commons:commons-io` to `commons-io:commons-io` -description: The deployment of `org.apache.commons:commons-io` [was a publishing mistake around 2012](https://issues.sonatype.org/browse/MVNCENTRAL-244) which was corrected by changing the deployment GAV to be located under `commons-io:commons-io`. -tags: - - apache - - commons - - security -recipeList: - - org.openrewrite.java.dependencies.ChangeDependency: - oldGroupId: org.apache.commons - oldArtifactId: commons-io - newGroupId: commons-io - newArtifactId: commons-io ---- -type: specs.openrewrite.org/v1beta/recipe -name: org.openrewrite.java.migrate.apache.commons.io.UseSystemLineSeparator -displayName: Prefer `System.lineSeparator()` -description: Prefer the Java standard library's `System.lineSeparator()` over third-party usage of apache's `IOUtils.LINE_SEPARATOR`. -tags: - - apache - - commons -recipeList: - - org.openrewrite.java.ChangeStaticFieldToMethod: - oldClassName: org.apache.commons.io.IOUtils - oldFieldName: LINE_SEPARATOR - newClassName: java.lang.System - newMethodName: lineSeparator ---- -type: specs.openrewrite.org/v1beta/recipe -name: org.openrewrite.java.migrate.apache.commons.io.UseStandardCharsets -displayName: Prefer `java.nio.charset.StandardCharsets` -description: Prefer the Java standard library's `java.nio.charset.StandardCharsets` over third-party usage of apache's `org.apache.commons.io.Charsets`. -tags: - - apache - - commons -recipeList: - - org.openrewrite.java.ChangeType: - oldFullyQualifiedTypeName: org.apache.commons.io.Charsets.ISO_8859_1 - newFullyQualifiedTypeName: java.nio.charset.StandardCharsets.ISO_8859_1 - - org.openrewrite.java.ChangeType: - oldFullyQualifiedTypeName: org.apache.commons.io.Charsets.US_ASCII - newFullyQualifiedTypeName: java.nio.charset.StandardCharsets.US_ASCII - - org.openrewrite.java.ChangeType: - oldFullyQualifiedTypeName: org.apache.commons.io.Charsets.UTF_8 - newFullyQualifiedTypeName: java.nio.charset.StandardCharsets.UTF_8 - - org.openrewrite.java.ChangeType: - oldFullyQualifiedTypeName: org.apache.commons.io.Charsets.UTF_16 - newFullyQualifiedTypeName: java.nio.charset.StandardCharsets.UTF_16 - - org.openrewrite.java.ChangeType: - oldFullyQualifiedTypeName: org.apache.commons.io.Charsets.UTF_16BE - newFullyQualifiedTypeName: java.nio.charset.StandardCharsets.UTF_16BE - - org.openrewrite.java.ChangeType: - oldFullyQualifiedTypeName: org.apache.commons.io.Charsets.UTF_16LE - newFullyQualifiedTypeName: java.nio.charset.StandardCharsets.UTF_16LE \ No newline at end of file diff --git a/src/test/java/org/openrewrite/java/migrate/apache/commons/codec/ApacheBase64ToJavaBase64Test.java b/src/test/java/org/openrewrite/java/migrate/apache/commons/codec/ApacheBase64ToJavaBase64Test.java deleted file mode 100644 index b698fe36d9..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/apache/commons/codec/ApacheBase64ToJavaBase64Test.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2021 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.codec; - -import org.junit.jupiter.api.Test; -import org.openrewrite.DocumentExample; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; - -class ApacheBase64ToJavaBase64Test implements RewriteTest { - - @Override - public void defaults(RecipeSpec spec) { - spec - .recipe(new ApacheBase64ToJavaBase64()) - .parser(JavaParser.fromJavaVersion().classpath("commons-codec")); - } - - @DocumentExample - @Test - void toJavaBase64() { - rewriteRun( - //language=java - java( - """ - import org.apache.commons.codec.binary.Base64; - - class Test { - static byte[] decodeBytes(byte[] encodedBytes) { - return Base64.decodeBase64(encodedBytes); - } - static byte[] decodeToBytes(String encodedString) { - return Base64.decodeBase64(encodedString); - } - static String encodeToString(byte[] decodedByteArr) { - return Base64.encodeBase64String(decodedByteArr); - } - static byte[] encodeBase64(byte[] binaryData) { - return Base64.encodeBase64(binaryData); - } - static byte[] encodeBytesUrlSafe(byte [] encodeBytes) { - return Base64.encodeBase64URLSafe(encodeBytes); - } - static String encodeBytesUrlSafeString(byte [] encodeBytes) { - return Base64.encodeBase64URLSafeString(encodeBytes); - } - } - """, - """ - import java.util.Base64; - - class Test { - static byte[] decodeBytes(byte[] encodedBytes) { - return Base64.getDecoder().decode(encodedBytes); - } - static byte[] decodeToBytes(String encodedString) { - return Base64.getDecoder().decode(encodedString); - } - static String encodeToString(byte[] decodedByteArr) { - return Base64.getEncoder().encodeToString(decodedByteArr); - } - static byte[] encodeBase64(byte[] binaryData) { - return Base64.getEncoder().encode(binaryData); - } - static byte[] encodeBytesUrlSafe(byte [] encodeBytes) { - return Base64.getUrlEncoder().withoutPadding().encode(encodeBytes); - } - static String encodeBytesUrlSafeString(byte [] encodeBytes) { - return Base64.getUrlEncoder().withoutPadding().encodeToString(encodeBytes); - } - } - """ - ) - ); - } -} diff --git a/src/test/java/org/openrewrite/java/migrate/apache/commons/io/ApacheCommonsFileUtilsTest.java b/src/test/java/org/openrewrite/java/migrate/apache/commons/io/ApacheCommonsFileUtilsTest.java deleted file mode 100644 index fb3221cb02..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/apache/commons/io/ApacheCommonsFileUtilsTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.io; - -import org.junit.jupiter.api.Test; -import org.openrewrite.DocumentExample; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; - -class ApacheCommonsFileUtilsTest implements RewriteTest { - @Override - public void defaults(RecipeSpec spec) { - spec.parser(JavaParser.fromJavaVersion().classpath("commons-io")) - .recipe(new ApacheCommonsFileUtilsRecipes()); - } - - @Test - @DocumentExample - void ubertest() { - rewriteRun( - //language=java - java( - """ - import org.apache.commons.io.FileUtils; - - import java.io.File; - import java.io.FileFilter; - import java.net.URL; - import java.nio.charset.Charset; - import java.util.Collection; - import java.util.Collections; - import java.util.List; - - class Foo { - void bar(File fileA, File fileB, URL url, Charset cs, FileFilter filter, CharSequence charSeq) throws Exception { - long l = 10L; - String s = "hello world"; - String[] stringArray = new String[4]; - Collection collection = Collections.EMPTY_LIST; - byte[] bytes = new byte[0]; - String str; - boolean bool; - List strList; - List fileList; - File f; - - FileUtils.write(fileA, s, cs); - f = FileUtils.getFile(s); - f = FileUtils.getFile(s, s); - f = FileUtils.toFile(url); - - str = FileUtils.byteCountToDisplaySize(l); - FileUtils.cleanDirectory(fileA); - bool = FileUtils.contentEquals(fileA, fileB); - bool = FileUtils.contentEqualsIgnoreEOL(fileA, fileB, s); - FileUtils.copyDirectory(fileA, fileB); - FileUtils.copyFileToDirectory(fileA, fileB); - FileUtils.copyFile(fileA, fileB); - FileUtils.copyURLToFile(url, fileA); - f = FileUtils.current(); - FileUtils.deleteDirectory(fileA); - f = FileUtils.delete(fileA); - bool = FileUtils.deleteQuietly(fileA); - FileUtils.forceDeleteOnExit(fileA); - FileUtils.forceDelete(fileA); - FileUtils.forceMkdir(fileA); - FileUtils.forceMkdirParent(fileA); - f = FileUtils.getTempDirectory(); - str = FileUtils.readFileToString(fileA, cs); - str = FileUtils.readFileToString(fileA, s); - strList = FileUtils.readLines(fileA, cs); - FileUtils.writeByteArrayToFile(fileA, bytes); - FileUtils.writeLines(fileA, collection); - FileUtils.writeStringToFile(fileA, s); - } - } - """, - """ - import org.apache.commons.io.FileUtils; - - import java.io.File; - import java.io.FileFilter; - import java.net.URL; - import java.nio.charset.Charset; - import java.nio.file.Files; - import java.util.Collection; - import java.util.Collections; - import java.util.List; - - class Foo { - void bar(File fileA, File fileB, URL url, Charset cs, FileFilter filter, CharSequence charSeq) throws Exception { - long l = 10L; - String s = "hello world"; - String[] stringArray = new String[4]; - Collection collection = Collections.EMPTY_LIST; - byte[] bytes = new byte[0]; - String str; - boolean bool; - List strList; - List fileList; - File f; - - FileUtils.write(fileA, s, cs); - f = new File(s); - f = FileUtils.getFile(s, s); - f = FileUtils.toFile(url); - - str = FileUtils.byteCountToDisplaySize(l); - FileUtils.cleanDirectory(fileA); - bool = FileUtils.contentEquals(fileA, fileB); - bool = FileUtils.contentEqualsIgnoreEOL(fileA, fileB, s); - FileUtils.copyDirectory(fileA, fileB); - FileUtils.copyFileToDirectory(fileA, fileB); - FileUtils.copyFile(fileA, fileB); - FileUtils.copyURLToFile(url, fileA); - f = FileUtils.current(); - FileUtils.deleteDirectory(fileA); - f = FileUtils.delete(fileA); - bool = FileUtils.deleteQuietly(fileA); - FileUtils.forceDeleteOnExit(fileA); - FileUtils.forceDelete(fileA); - FileUtils.forceMkdir(fileA); - FileUtils.forceMkdirParent(fileA); - f = FileUtils.getTempDirectory(); - str = FileUtils.readFileToString(fileA, cs); - str = FileUtils.readFileToString(fileA, s); - strList = FileUtils.readLines(fileA, cs); - FileUtils.writeByteArrayToFile(fileA, bytes); - FileUtils.writeLines(fileA, collection); - Files.write(fileA.toPath(), s.getBytes()); - } - } - """ - ) - ); - } -} diff --git a/src/test/java/org/openrewrite/java/migrate/apache/commons/io/ApacheFileUtilsToJavaFilesTest.java b/src/test/java/org/openrewrite/java/migrate/apache/commons/io/ApacheFileUtilsToJavaFilesTest.java deleted file mode 100644 index 19fe7d8632..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/apache/commons/io/ApacheFileUtilsToJavaFilesTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2021 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.io; - -import org.junit.jupiter.api.Test; -import org.openrewrite.DocumentExample; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; - -class ApacheFileUtilsToJavaFilesTest implements RewriteTest { - @Override - public void defaults(RecipeSpec spec) { - spec - .recipe(new ApacheFileUtilsToJavaFiles()) - .parser(JavaParser.fromJavaVersion().classpath("commons-io")); - } - - @DocumentExample - @Test - void convertTest() { - //language=java - rewriteRun( - java( - """ - import java.io.File; - import java.nio.charset.Charset; - import org.apache.commons.io.FileUtils; - import java.util.List; - - class A { - byte[] readFileBytes(File file) { - return FileUtils.readFileToByteArray(file); - } - List readLines(File file) { - return FileUtils.readLines(file); - } - List readLinesWithCharset(File file, Charset charset) { - return FileUtils.readLines(file, charset); - } - List readLinesWithCharsetId(File file) { - return FileUtils.readLines(file, "UTF_8"); - } - } - """, - """ - import java.io.File; - import java.nio.charset.Charset; - import java.nio.file.Files; - - import java.util.List; - - class A { - byte[] readFileBytes(File file) { - return Files.readAllBytes(file.toPath()); - } - List readLines(File file) { - return Files.readAllLines(file.toPath()); - } - List readLinesWithCharset(File file, Charset charset) { - return Files.readAllLines(file.toPath(), charset); - } - List readLinesWithCharsetId(File file) { - return Files.readAllLines(file.toPath(), Charset.forName("UTF_8")); - } - } - """ - ) - ); - } -} diff --git a/src/test/java/org/openrewrite/java/migrate/apache/commons/io/ApacheIOUtilsUseExplicitCharsetTest.java b/src/test/java/org/openrewrite/java/migrate/apache/commons/io/ApacheIOUtilsUseExplicitCharsetTest.java deleted file mode 100644 index 5e34b77abc..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/apache/commons/io/ApacheIOUtilsUseExplicitCharsetTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.io; - -import org.junit.jupiter.api.Test; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; -import static org.openrewrite.java.Assertions.srcMainJava; - -class ApacheIOUtilsUseExplicitCharsetTest implements RewriteTest { - - @Override - public void defaults(RecipeSpec spec) { - spec - .recipe(new ApacheIOUtilsUseExplicitCharset(null)) - .parser(JavaParser.fromJavaVersion().classpath("commons-io")); - } - - @Test - void useCharset() { - //language=java - rewriteRun( - srcMainJava( - java( - """ - import org.apache.commons.io.IOUtils; - import java.io.InputStream; - import java.io.OutputStream; - import java.io.Reader; - import java.io.Writer; - import java.net.URI; - import java.net.URL; - - class T { - InputStream inputStream; - OutputStream outputStream; - Reader reader; - Writer writer; - CharSequence charSequence; - String someString; - byte[] bytes; - URI uri; - URL url; - char[] chars; - StringBuffer stringBuffer; - - void flex() { - IOUtils.copy(inputStream, writer); - IOUtils.copy(reader, outputStream); - IOUtils.readLines(inputStream); - IOUtils.toByteArray(someString); - IOUtils.toByteArray(reader); - IOUtils.toCharArray(inputStream); - IOUtils.toInputStream(charSequence); - IOUtils.toInputStream("Test"); - IOUtils.toString("Test".getBytes()); - IOUtils.toString(inputStream); - IOUtils.toString(uri); - IOUtils.toString(url); - IOUtils.write(bytes, writer); - IOUtils.write(chars, outputStream); - IOUtils.write(charSequence, outputStream); - IOUtils.write(someString, outputStream); - IOUtils.write(stringBuffer, outputStream); - } - } - """, - """ - import org.apache.commons.io.IOUtils; - import java.io.InputStream; - import java.io.OutputStream; - import java.io.Reader; - import java.io.Writer; - import java.net.URI; - import java.net.URL; - import java.nio.charset.StandardCharsets; - - class T { - InputStream inputStream; - OutputStream outputStream; - Reader reader; - Writer writer; - CharSequence charSequence; - String someString; - byte[] bytes; - URI uri; - URL url; - char[] chars; - StringBuffer stringBuffer; - - void flex() { - IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8); - IOUtils.copy(reader, outputStream, StandardCharsets.UTF_8); - IOUtils.readLines(inputStream, StandardCharsets.UTF_8); - someString.getBytes(StandardCharsets.UTF_8); - IOUtils.toByteArray(reader, StandardCharsets.UTF_8); - IOUtils.toCharArray(inputStream, StandardCharsets.UTF_8); - IOUtils.toInputStream(charSequence, StandardCharsets.UTF_8); - IOUtils.toInputStream("Test", StandardCharsets.UTF_8); - IOUtils.toString("Test".getBytes(), StandardCharsets.UTF_8); - IOUtils.toString(inputStream, StandardCharsets.UTF_8); - IOUtils.toString(uri, StandardCharsets.UTF_8); - IOUtils.toString(url, StandardCharsets.UTF_8); - IOUtils.write(bytes, writer, StandardCharsets.UTF_8); - IOUtils.write(chars, outputStream, StandardCharsets.UTF_8); - IOUtils.write(charSequence, outputStream, StandardCharsets.UTF_8); - IOUtils.write(someString, outputStream, StandardCharsets.UTF_8); - IOUtils.write(stringBuffer, outputStream, StandardCharsets.UTF_8); - } - } - """ - ) - ) - ); - } -} diff --git a/src/test/java/org/openrewrite/java/migrate/apache/commons/io/UseJavaStandardCharsetsTest.java b/src/test/java/org/openrewrite/java/migrate/apache/commons/io/UseJavaStandardCharsetsTest.java deleted file mode 100644 index 458b915be6..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/apache/commons/io/UseJavaStandardCharsetsTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2021 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.io; - -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.openrewrite.config.Environment; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; - -class UseJavaStandardCharsetsTest implements RewriteTest { - @Override - public void defaults(RecipeSpec spec) { - spec - .recipe(Environment.builder() - .scanRuntimeClasspath("org.openrewrite.java.migrate.apache.commons.io") - .build() - .activateRecipes("org.openrewrite.java.migrate.apache.commons.io.UseStandardCharsets")) - .parser(JavaParser.fromJavaVersion().classpath("commons-io")); - } - - @Test - @Disabled - void toStandardCharsets() { - //language=java - rewriteRun( - java( - """ - import java.nio.charset.Charset; - import org.apache.commons.io.Charsets; - - class A { - Charset iso88591 = Charsets.ISO_8859_1; - Charset usAscii = Charsets.US_ASCII; - Charset utf16 = Charsets.UTF_16; - Charset utf16be = Charsets.UTF_16BE; - Charset utf16le = Charsets.UTF_16LE; - Charset utf8 = Charsets.UTF_8; - } - """, - """ - import java.nio.charset.Charset; - import java.nio.charset.StandardCharsets; - - class A { - Charset iso88591 = StandardCharsets.ISO_8859_1; - Charset usAscii = StandardCharsets.US_ASCII; - Charset utf16 = StandardCharsets.UTF_16; - Charset utf16be = StandardCharsets.UTF_16BE; - Charset utf16le = StandardCharsets.UTF_16LE; - Charset utf8 = StandardCharsets.UTF_8; - } - """ - ) - ); - } -} diff --git a/src/test/java/org/openrewrite/java/migrate/apache/commons/io/UseSystemLineSeparatorTest.java b/src/test/java/org/openrewrite/java/migrate/apache/commons/io/UseSystemLineSeparatorTest.java deleted file mode 100644 index e947b87e61..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/apache/commons/io/UseSystemLineSeparatorTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2021 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.io; - -import org.junit.jupiter.api.Test; -import org.openrewrite.DocumentExample; -import org.openrewrite.Issue; -import org.openrewrite.config.Environment; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; - -class UseSystemLineSeparatorTest implements RewriteTest { - - @Override - public void defaults(RecipeSpec spec) { - spec - .recipe(Environment.builder() - .scanRuntimeClasspath("org.openrewrite.java.migrate.apache.commons.io") - .build() - .activateRecipes("org.openrewrite.java.migrate.apache.commons.io.UseSystemLineSeparator")) - .parser(JavaParser.fromJavaVersion().classpath("commons-io")); - } - - - @DocumentExample - @Test - void migratesQualifiedField() { - //language=java - rewriteRun( - java( - """ - import org.apache.commons.io.IOUtils; - - class A { - static String lineSeparator() { - return IOUtils.LINE_SEPARATOR; - } - } - """, - """ - class A { - static String lineSeparator() { - return System.lineSeparator(); - } - } - """ -) -); - } - - @Test - void migratesStaticImportedField() { - //language=java - rewriteRun( - java( - """ - import static org.apache.commons.io.IOUtils.LINE_SEPARATOR; - - class A { - static String lineSeparator() { - return LINE_SEPARATOR; - } - } - """, - """ - class A { - static String lineSeparator() { - return System.lineSeparator(); - } - } - """ - ) - ); - } - - @Test - @Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/54") - void migratesFieldInitializer() { - //language=java - rewriteRun( - java( - """ - import org.apache.commons.io.IOUtils; - - class A { - private final String LINE_SEPARATOR_AND_INDENTATION = IOUtils.LINE_SEPARATOR; - } - """, - """ - class A { - private final String LINE_SEPARATOR_AND_INDENTATION = System.lineSeparator(); - } - """ - ) - ); - } - - @Test - void ignoreUnrelatedFields() { - //language=java - rewriteRun( - java( - """ - class A { - private static final String LINE_SEPARATOR = System.lineSeparator(); - - static String lineSeparator() { - return LINE_SEPARATOR; - } - } - """ - ) - ); - } -} diff --git a/src/test/java/org/openrewrite/java/migrate/apache/commons/lang/ApacheCommonsStringUtilsTest.java b/src/test/java/org/openrewrite/java/migrate/apache/commons/lang/ApacheCommonsStringUtilsTest.java deleted file mode 100644 index fa0d3803ce..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/apache/commons/lang/ApacheCommonsStringUtilsTest.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.lang; - -import org.junit.jupiter.api.Test; -import org.openrewrite.DocumentExample; -import org.openrewrite.Issue; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; - -@SuppressWarnings({"Deprecation", "UnusedAssignment", "DataFlowIssue", "StringOperationCanBeSimplified"}) -class ApacheCommonsStringUtilsTest implements RewriteTest { - - @Override - public void defaults(RecipeSpec spec) { - spec.parser(JavaParser.fromJavaVersion().classpath("commons-lang3")) - .recipe(new ApacheCommonsStringUtilsRecipes()); - } - - @Test - @DocumentExample - void ubertest() { - rewriteRun( - //language=java - java( - """ - import org.apache.commons.lang3.StringUtils; - - class Foo { - void bar(String in, CharSequence cs) { - // Reuse output variables for readability - String[] array; - boolean bool; - int integer; - String string; - - // Test all methods in alphabetical order to only execute the slow recipes once - string = StringUtils.abbreviate(in, 10); - string = StringUtils.capitalize(in); - string = StringUtils.center(in, 10); - string = StringUtils.center(in, 10, ' '); - string = StringUtils.center(in, 10, " "); - string = StringUtils.chomp(in); - string = StringUtils.chop(in); - - bool = StringUtils.contains(in, "search"); - - integer = StringUtils.countMatches(in, '|'); - integer = StringUtils.countMatches(in, "|"); - - string = StringUtils.defaultString(in); - string = StringUtils.defaultString(in, "nil"); - string = StringUtils.deleteWhitespace(in); - - //bool = StringUtils.endsWithIgnoreCase(in, "suffix"); - bool = StringUtils.equalsIgnoreCase(in, "other"); - bool = StringUtils.equals(in, "other"); - bool = StringUtils.equals(cs, "other"); - bool = StringUtils.equals(cs, cs); - - //integer = StringUtils.indexOfAny(in, "search"); - - bool = StringUtils.isAlphanumericSpace(in); - bool = StringUtils.isAlphanumeric(in); - bool = StringUtils.isAlphaSpace(in); - bool = StringUtils.isAlpha(in); - bool = StringUtils.isEmpty(in); - - string = StringUtils.join(in); - string = StringUtils.joinWith(",", in); - string = StringUtils.left(in, 4); - string = StringUtils.leftPad(in, 4); - string = StringUtils.leftPad(in, 4, ' '); - string = StringUtils.leftPad(in, 4, " "); - string = StringUtils.lowerCase(in); - string = StringUtils.mid(in, 3, 4); - string = StringUtils.overlay(in, "overlay", 3, 5); - - string = StringUtils.remove(in, "r"); - string = StringUtils.removeEnd(in, "suffix"); - string = StringUtils.repeat(in, 4); - string = StringUtils.repeat(in, ",", 4); - string = StringUtils.replace(in, "search", "replacement"); - //string = StringUtils.replaceOnce(in, "search", "replacement"); - string = StringUtils.reverse(in); - string = StringUtils.right(in, 5); - string = StringUtils.rightPad(in, 5); - string = StringUtils.rightPad(in, 5, ' '); - string = StringUtils.rightPad(in, 5, " "); - - array = StringUtils.split(in); - //array = StringUtils.split(in, "*"); - bool = StringUtils.startsWith(in, "prefix"); - bool = StringUtils.startsWithAny(in, "prefix"); - bool = StringUtils.startsWithIgnoreCase(in, "prefix"); - array = StringUtils.stripAll(in); - - string = StringUtils.strip(in); - string = StringUtils.stripEnd(in, "suffix"); - string = StringUtils.stripStart(in, "chars"); - - bool = StringUtils.startsWith(in, "prefix"); - - string = StringUtils.substringAfter(in, "|"); - string = StringUtils.substring(in, 2, 4); - string = StringUtils.swapCase(in); - string = StringUtils.trimToEmpty(in); - string = StringUtils.trimToNull(in); - string = StringUtils.trim(in); - string = StringUtils.upperCase(in); - string = StringUtils.uncapitalize(in); - } - } - """, - """ - import org.apache.commons.lang3.StringUtils; - - import java.util.Objects; - - class Foo { - void bar(String in, CharSequence cs) { - // Reuse output variables for readability - String[] array; - boolean bool; - int integer; - String string; - - // Test all methods in alphabetical order to only execute the slow recipes once - string = in == null || in.length() <= 10 ? in : in.substring(0, 10 - 3) + "..."; - string = in == null || in.isEmpty() || Character.isTitleCase(in.charAt(0)) ? in : Character.toTitleCase(in.charAt(0)) + in.substring(1); - string = StringUtils.center(in, 10); - string = StringUtils.center(in, 10, ' '); - string = StringUtils.center(in, 10, " "); - string = StringUtils.chomp(in); - string = StringUtils.chop(in); - - bool = StringUtils.contains(in, "search"); - - integer = StringUtils.countMatches(in, '|'); - integer = StringUtils.countMatches(in, "|"); - - string = Objects.toString(in, ""); - string = Objects.toString(in, "nil"); - string = in == null ? null : in.replaceAll("\\\\s+", ""); - - //bool = StringUtils.endsWithIgnoreCase(in, "suffix"); - bool = in == null ? false : in.equalsIgnoreCase("other"); - bool = Objects.equals(in, "other"); - bool = StringUtils.equals(cs, "other"); - bool = StringUtils.equals(cs, cs); - - //integer = StringUtils.indexOfAny(in, "search"); - - bool = StringUtils.isAlphanumericSpace(in); - bool = StringUtils.isAlphanumeric(in); - bool = StringUtils.isAlphaSpace(in); - bool = StringUtils.isAlpha(in); - bool = StringUtils.isEmpty(in); - - string = StringUtils.join(in); - string = StringUtils.joinWith(",", in); - string = StringUtils.left(in, 4); - string = StringUtils.leftPad(in, 4); - string = StringUtils.leftPad(in, 4, ' '); - string = StringUtils.leftPad(in, 4, " "); - string = in == null ? null : in.toLowerCase(); - string = StringUtils.mid(in, 3, 4); - string = StringUtils.overlay(in, "overlay", 3, 5); - - string = StringUtils.remove(in, "r"); - string = in == null || in.isEmpty() || !in.endsWith("suffix") ? in : in.substring(0, in.length() - "suffix".length()); - string = StringUtils.repeat(in, 4); - string = StringUtils.repeat(in, ",", 4); - string = in == null || in.isEmpty() ? in : in.replace("search", "replacement"); - //string = StringUtils.replaceOnce(in, "search", "replacement"); - string = in == null ? null : new StringBuilder(in).reverse().toString(); - string = StringUtils.right(in, 5); - string = StringUtils.rightPad(in, 5); - string = StringUtils.rightPad(in, 5, ' '); - string = StringUtils.rightPad(in, 5, " "); - - array = in == null ? null : in.split("\\\\s+"); - //array = StringUtils.split(in, "*"); - bool = StringUtils.startsWith(in, "prefix"); - bool = StringUtils.startsWithAny(in, "prefix"); - bool = StringUtils.startsWithIgnoreCase(in, "prefix"); - array = StringUtils.stripAll(in); - - string = in == null ? null : in.trim(); - string = StringUtils.stripEnd(in, "suffix"); - string = StringUtils.stripStart(in, "chars"); - - bool = StringUtils.startsWith(in, "prefix"); - - string = StringUtils.substringAfter(in, "|"); - string = StringUtils.substring(in, 2, 4); - string = StringUtils.swapCase(in); - string = in == null ? "" : in.trim(); - string = in == null || in.trim().isEmpty() ? null : in.trim(); - string = in == null ? null : in.trim(); - string = in == null ? null : in.toUpperCase(); - string = StringUtils.uncapitalize(in); - } - } - """ - ) - ); - } - - @Test - void canCallMethodOnResult() { - rewriteRun( - //language=java - java( - """ - import org.apache.commons.lang3.StringUtils; - - class Foo { - void test(String s) { - String test = StringUtils.strip(s).toString(); - } - } - """, - """ - class Foo { - void test(String s) { - String test = (s == null ? null : s.trim()).toString(); - } - } - """ - ) - ); - } - - @Test - void invertedBooleanHandled() { - rewriteRun( - //language=java - java( - """ - import org.apache.commons.lang3.StringUtils; - - class Foo { - void test(String s, String other) { - boolean test = !StringUtils.equalsIgnoreCase(s, other); - } - } - """, - """ - class Foo { - void test(String s, String other) { - boolean test = !(s == null ? other == null : s.equalsIgnoreCase(other)); - } - } - """ - ) - ); - } - - @Test - @Issue("https://github.com/openrewrite/rewrite-templating/issues/27") - void inputMethodsNotCalledTwice() { - rewriteRun( - //language=java - java( - """ - class Bar { - String baz() { - return "baz"; - } - } - """), - //language=java - java( - """ - import org.apache.commons.lang3.StringUtils; - - class Foo { - void test(Bar bar) { - String test = StringUtils.strip(bar.baz()); - } - } - """ - ) - ); - } - - @Test - @Issue("https://github.com/openrewrite/rewrite-templating/issues/27") - void getterIsCalledTwice() { - rewriteRun( - //language=java - java( - """ - class Bar { - String getBaz() { - return "baz"; - } - } - """), - //language=java - java( - """ - import org.apache.commons.lang3.StringUtils; - - class Foo { - void test(Bar bar) { - String test = StringUtils.strip(bar.getBaz()); - } - } - """, - """ - class Foo { - void test(Bar bar) { - String test = bar.getBaz() == null ? null : bar.getBaz().trim(); - } - } - """ - ) - ); - } -} diff --git a/src/test/java/org/openrewrite/java/migrate/apache/commons/lang/IsNotEmptyToJdkTest.java b/src/test/java/org/openrewrite/java/migrate/apache/commons/lang/IsNotEmptyToJdkTest.java deleted file mode 100644 index 6f621c67f2..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/apache/commons/lang/IsNotEmptyToJdkTest.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.apache.commons.lang; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.ValueSource; -import org.openrewrite.DocumentExample; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; - -class IsNotEmptyToJdkTest implements RewriteTest { - - @Override - public void defaults(RecipeSpec spec) { - spec.parser(JavaParser.fromJavaVersion().classpath("commons-lang3", "plexus-utils", "maven-shared-utils")) - .recipe(new IsNotEmptyToJdk()); - } - - @Test - @DocumentExample - void exampleUse() { - rewriteRun( - // language=java - java( - """ - import org.apache.commons.lang3.StringUtils; - - class A { - boolean test(String first) { - return StringUtils.isEmpty(first); - } - } - """, """ - class A { - boolean test(String first) { - return first == null || first.isEmpty(); - } - } - """)); - } - - @ParameterizedTest - @ValueSource(strings = { - "org.apache.commons.lang3.StringUtils", - "org.apache.maven.shared.utils.StringUtils", - "org.codehaus.plexus.util.StringUtils" - }) - void trim(String import_) { - // language=java - rewriteRun( - java( - """ - import %s; - - class A { - boolean test(String first) { - boolean a = StringUtils.isEmpty(first.trim()); - boolean b = !StringUtils.isEmpty(first.trim()); - boolean c = StringUtils.isNotEmpty(first.trim()); - boolean d = !StringUtils.isNotEmpty(first.trim()); // yeah, this is weird, but not worth cleaning up - boolean e = StringUtils.isEmpty(foo().trim()); // Not guaranteed safe to replace - } - String foo() { - return "foo"; - } - } - """.formatted(import_), - """ - import %s; - - class A { - boolean test(String first) { - boolean a = first.trim().isEmpty(); - boolean b = !first.trim().isEmpty(); - boolean c = !first.trim().isEmpty(); - boolean d = !!first.trim().isEmpty(); // yeah, this is weird, but not worth cleaning up - boolean e = StringUtils.isEmpty(foo().trim()); // Not guaranteed safe to replace - } - String foo() { - return "foo"; - } - } - """.formatted(import_) - ) - ); - } - - @ParameterizedTest - @CsvSource(delimiter = '#', textBlock = """ - org.apache.commons.lang3.StringUtils # StringUtils.isEmpty(first) # first == null || first.isEmpty() - org.apache.commons.lang3.StringUtils # StringUtils.isEmpty(field) # field == null || field.isEmpty() - org.apache.commons.lang3.StringUtils # StringUtils.isEmpty(this.field) # this.field == null || this.field.isEmpty() - org.apache.commons.lang3.StringUtils # StringUtils.isNotEmpty(first) # first != null && !first.isEmpty() - org.apache.maven.shared.utils.StringUtils # StringUtils.isEmpty(first) # first == null || first.isEmpty() - org.apache.maven.shared.utils.StringUtils # StringUtils.isNotEmpty(first) # first != null && !first.isEmpty() - org.codehaus.plexus.util.StringUtils # StringUtils.isEmpty(first) # first == null || first.isEmpty() - org.codehaus.plexus.util.StringUtils # StringUtils.isNotEmpty(first) # first != null && !first.isEmpty() - """) - void replaceDirectUse(String classname, String beforeLine, String afterLine) { - // language=java - rewriteRun( - java( - """ - import %s; - - class A { - String field = "foo"; - boolean test(String first) { - return %s; - } - } - """.formatted(classname, beforeLine), - """ - class A { - String field = "foo"; - boolean test(String first) { - return %s; - } - } - """.formatted(afterLine))); - } - - @ParameterizedTest - @CsvSource(delimiter = '#', textBlock = """ - org.apache.commons.lang3.StringUtils # !StringUtils.isEmpty(first) # !(first == null || first.isEmpty()) - org.apache.commons.lang3.StringUtils # !StringUtils.isNotEmpty(first) # !(first != null && !first.isEmpty()) - org.apache.commons.lang3.StringUtils # !(StringUtils.isEmpty(first)) # !(first == null || first.isEmpty()) - org.apache.commons.lang3.StringUtils # !(StringUtils.isNotEmpty(first)) # !(first != null && !first.isEmpty()) - org.apache.maven.shared.utils.StringUtils # !StringUtils.isEmpty(first) # !(first == null || first.isEmpty()) - org.apache.maven.shared.utils.StringUtils # !StringUtils.isNotEmpty(first) # !(first != null && !first.isEmpty()) - org.codehaus.plexus.util.StringUtils # !StringUtils.isEmpty(first) # !(first == null || first.isEmpty()) - org.codehaus.plexus.util.StringUtils # !StringUtils.isNotEmpty(first) # !(first != null && !first.isEmpty()) - """) - void replaceNegated(String classname, String beforeLine, String afterLine) { - // language=java - rewriteRun( - java( - """ - import %s; - - class A { - boolean test(String first) { - return %s; - } - } - """.formatted(classname, beforeLine), - """ - class A { - boolean test(String first) { - return %s; - } - } - """.formatted(afterLine))); - } - - @Test - void convertSimpleGetters() { - // language=java - rewriteRun( - java( - """ - class B { - String field; - String getField() { - return field; - } - } - """ - ), - java( - """ - import org.apache.commons.lang3.StringUtils; - - class A { - boolean test(B b) { - return StringUtils.isEmpty(b.getField()); - } - } - """, - """ - class A { - boolean test(B b) { - return b.getField() == null || b.getField().isEmpty(); - } - } - """ - ) - ); - } - - @ParameterizedTest - @CsvSource(delimiter = '#', textBlock = """ - org.apache.commons.lang3.StringUtils # StringUtils.isEmpty(foo()) - org.apache.commons.lang3.StringUtils # StringUtils.isEmpty(first + second) - org.apache.commons.lang3.StringUtils # StringUtils.isNotEmpty(foo()) - org.apache.commons.lang3.StringUtils # StringUtils.isNotEmpty(first + second) - org.apache.maven.shared.utils.StringUtils # StringUtils.isEmpty(foo()) - org.codehaus.plexus.util.StringUtils # StringUtils.isEmpty(foo()) - """) - void retainComplexUse(String classname, String beforeLine) { - // language=java - rewriteRun( - java( - """ - import %s; - - class A { - boolean test(String first, String second) { - return %s; - } - private String foo() { - return "foo"; - } - } - """.formatted(classname, beforeLine))); - } -} \ No newline at end of file diff --git a/src/test/java/org/openrewrite/java/migrate/maven/shared/MavenSharedStringUtilsTest.java b/src/test/java/org/openrewrite/java/migrate/maven/shared/MavenSharedStringUtilsTest.java deleted file mode 100644 index ea16cba5da..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/maven/shared/MavenSharedStringUtilsTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.maven.shared; - -import org.junit.jupiter.api.Test; -import org.openrewrite.DocumentExample; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; - -@SuppressWarnings({"Deprecation", "UnusedAssignment", "DataFlowIssue", "StringOperationCanBeSimplified"}) -class MavenSharedStringUtilsTest implements RewriteTest { - - @Override - public void defaults(RecipeSpec spec) { - spec.parser(JavaParser.fromJavaVersion().classpath("maven-shared-utils")) - .recipe(new MavenSharedStringUtilsRecipes()); - } - - @Test - @DocumentExample - void ubertest() { - rewriteRun( - //language=java - java( - """ - import org.apache.maven.shared.utils.StringUtils; - - class Foo { - void bar(String in, CharSequence cs) { - // Reuse output variables for readability - String[] array; - boolean bool; - String string; - - // Test all methods in alphabetical order to only execute the slow recipes once - string = StringUtils.abbreviate(in, 10); - string = StringUtils.capitalise(in); - string = StringUtils.defaultString(in); - string = StringUtils.defaultString(in, "nil"); - string = StringUtils.deleteWhitespace(in); - - bool = StringUtils.equalsIgnoreCase(in, "other"); - bool = StringUtils.equals(in, "other"); - //bool = StringUtils.equals(cs, "other"); - bool = StringUtils.isEmpty(in); - - string = StringUtils.lowerCase(in); - string = StringUtils.replace(in, "search", "replacement"); - string = StringUtils.reverse(in); - array = StringUtils.split(in); - string = StringUtils.strip(in); - string = StringUtils.trim(in); - string = StringUtils.upperCase(in); - } - } - """, - """ - import org.apache.maven.shared.utils.StringUtils; - - import java.util.Objects; - - class Foo { - void bar(String in, CharSequence cs) { - // Reuse output variables for readability - String[] array; - boolean bool; - String string; - - // Test all methods in alphabetical order to only execute the slow recipes once - string = in.length() <= 10 ? in : in.substring(0, 10 - 3) + "..."; - string = in == null || in.isEmpty() ? in : Character.toTitleCase(in.charAt(0)) + in.substring(1); - string = Objects.toString(in, ""); - string = Objects.toString(in, "nil"); - string = in.replaceAll("\\\\s+", ""); - - bool = in == null ? false : in.equalsIgnoreCase("other"); - bool = Objects.equals(in, "other"); - //bool = StringUtils.equals(cs, "other"); - bool = StringUtils.isEmpty(in); - - string = in == null ? null : in.toLowerCase(); - string = in == null || in.isEmpty() ? in : in.replace("search", "replacement"); - string = in == null ? null : new StringBuffer(in).reverse().toString(); - array = in.split("\\\\s+"); - string = in == null ? null : in.trim(); - string = in == null ? null : in.trim(); - string = in == null ? null : in.toUpperCase(); - } - } - """ - ) - ); - } - -} diff --git a/src/test/java/org/openrewrite/java/migrate/plexus/PlexusFileUtilsTest.java b/src/test/java/org/openrewrite/java/migrate/plexus/PlexusFileUtilsTest.java deleted file mode 100644 index 42c0328d2f..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/plexus/PlexusFileUtilsTest.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.plexus; - -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; - -class PlexusFileUtilsTest implements RewriteTest { - - @Override - public void defaults(RecipeSpec spec) { - spec - .parser(JavaParser.fromJavaVersion().classpath("commons-io", "plexus-utils")) - .recipe(new PlexusFileUtilsRecipes()); - } - - @Nested - class DeleteDirectory { - - @Test - void deleteDirectoryFullyQualified() { - rewriteRun( - //language=java - java( - """ - import java.io.File; - - class Test { - void test() throws Exception { - org.codehaus.plexus.util.FileUtils.deleteDirectory("test"); - File file = new File("test"); - org.codehaus.plexus.util.FileUtils.deleteDirectory(file); - } - } - """, - """ - import org.apache.commons.io.FileUtils; - - import java.io.File; - - class Test { - void test() throws Exception { - FileUtils.deleteDirectory(new File("test")); - File file = new File("test"); - FileUtils.deleteDirectory(file); - } - } - """ - ) - ); - } - - @Test - void deleteDirectorySimpleImport() { - rewriteRun( - //language=java - java( - """ - import org.codehaus.plexus.util.FileUtils; - - import java.io.File; - - class Test { - void test() throws Exception { - FileUtils.deleteDirectory("test"); - } - } - """, - """ - import org.apache.commons.io.FileUtils; - - import java.io.File; - - class Test { - void test() throws Exception { - FileUtils.deleteDirectory(new File("test")); - } - } - """ - ) - ); - } - - @Test - void deleteDirectoryRetainedImport() { - rewriteRun( - //language=java - java( - """ - import org.codehaus.plexus.util.FileUtils; - - import java.io.File; - - class Test { - void test() throws Exception { - FileUtils.deleteDirectory("test"); - FileUtils.dirname("/foo/bar"); - } - } - """, - """ - import org.codehaus.plexus.util.FileUtils; - - import java.io.File; - - class Test { - void test() throws Exception { - org.apache.commons.io.FileUtils.deleteDirectory(new File("test")); - FileUtils.dirname("/foo/bar"); - } - } - """ - ) - ); - } - } - - @Nested - class FileExists { - @Test - void fileExists() { - rewriteRun( - //language=java - java( - """ - import org.codehaus.plexus.util.FileUtils; - - class Test { - boolean test(String fileName) throws Exception { - return FileUtils.fileExists(fileName); - } - } - """, - """ - import java.io.File; - - class Test { - boolean test(String fileName) throws Exception { - return new File(fileName).exists(); - } - } - """ - ) - ); - } - } - - @Nested - class GetFile { - @Test - void getFile() { - rewriteRun( - //language=java - java( - """ - import org.codehaus.plexus.util.FileUtils; - - import java.io.File; - - class Test { - File test(String fileName) throws Exception { - return FileUtils.getFile(fileName); - } - } - """, - """ - import java.io.File; - - class Test { - File test(String fileName) throws Exception { - return new File(fileName); - } - } - """ - ) - ); - } - } -} \ No newline at end of file diff --git a/src/test/java/org/openrewrite/java/migrate/plexus/PlexusStringUtilsTest.java b/src/test/java/org/openrewrite/java/migrate/plexus/PlexusStringUtilsTest.java deleted file mode 100644 index 3e4b95cc1a..0000000000 --- a/src/test/java/org/openrewrite/java/migrate/plexus/PlexusStringUtilsTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * 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.java.migrate.plexus; - -import org.junit.jupiter.api.Test; -import org.openrewrite.DocumentExample; -import org.openrewrite.java.JavaParser; -import org.openrewrite.test.RecipeSpec; -import org.openrewrite.test.RewriteTest; - -import static org.openrewrite.java.Assertions.java; - -@SuppressWarnings({"Deprecation", "UnusedAssignment", "DataFlowIssue", "StringOperationCanBeSimplified"}) -class PlexusStringUtilsTest implements RewriteTest { - - @Override - public void defaults(RecipeSpec spec) { - spec.parser(JavaParser.fromJavaVersion().classpath("plexus-utils")) - .recipe(new PlexusStringUtilsRecipes()); - } - - @Test - @DocumentExample - void ubertest() { - rewriteRun( - //language=java - java( - """ - import org.codehaus.plexus.util.StringUtils; - - class Foo { - void bar(String in, CharSequence cs) { - // Reuse output variables for readability - String[] array; - boolean bool; - String string; - - // Test all methods in alphabetical order to only execute the slow recipes once - string = StringUtils.abbreviate(in, 10); - string = StringUtils.capitalise(in); - string = StringUtils.defaultString(in); - string = StringUtils.defaultString(in, "nil"); - string = StringUtils.deleteWhitespace(in); - - bool = StringUtils.equalsIgnoreCase(in, "other"); - bool = StringUtils.equals(in, "other"); - //bool = StringUtils.equals(cs, "other"); - - bool = StringUtils.isAlphanumeric(in); - bool = StringUtils.isAlpha(in); - bool = StringUtils.isEmpty(in); - - string = StringUtils.lowerCase(in); - string = StringUtils.replace(in, "search", "replacement"); - string = StringUtils.reverse(in); - array = StringUtils.split(in); - string = StringUtils.strip(in); - string = StringUtils.trim(in); - string = StringUtils.upperCase(in); - } - } - """, - """ - import org.codehaus.plexus.util.StringUtils; - - import java.util.Objects; - - class Foo { - void bar(String in, CharSequence cs) { - // Reuse output variables for readability - String[] array; - boolean bool; - String string; - - // Test all methods in alphabetical order to only execute the slow recipes once - string = in.length() <= 10 ? in : in.substring(0, 10 - 3) + "..."; - string = in == null || in.isEmpty() ? in : Character.toTitleCase(in.charAt(0)) + in.substring(1); - string = Objects.toString(in, ""); - string = Objects.toString(in, "nil"); - string = in.replaceAll("\\\\s+", ""); - - bool = in == null ? false : in.equalsIgnoreCase("other"); - bool = Objects.equals(in, "other"); - //bool = StringUtils.equals(cs, "other"); - - bool = StringUtils.isAlphanumeric(in); - bool = StringUtils.isAlpha(in); - bool = StringUtils.isEmpty(in); - - string = in == null ? null : in.toLowerCase(); - string = in == null || in.isEmpty() ? in : in.replace("search", "replacement"); - string = in == null ? null : new StringBuilder(in).reverse().toString(); - array = in.split("\\\\s+"); - string = in == null ? null : in.trim(); - string = in == null ? null : in.trim(); - string = in == null ? null : in.toUpperCase(); - } - } - """ - ) - ); - } - -}