Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add BufferedWriterCreation recipe #258

Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.staticanalysis;

import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import org.openrewrite.java.template.Primitive;
import org.openrewrite.java.template.RecipeDescriptor;

import java.io.BufferedWriter;
import java.io.IOException;

@RecipeDescriptor(
name = "Modernize `BufferedWriter` creation & prevent file descriptor leaks",
description = "The code `new BufferedWriter(new FileWriter(f))` creates a `BufferedWriter` that does not close the underlying `FileWriter` when it is closed. " +
"This can lead to file descriptor leaks as per [CWE-755](https://cwe.mitre.org/data/definitions/755.html). " +
"Use `Files.newBufferedWriter` to create a `BufferedWriter` that closes the underlying file descriptor when it is closed."
)
public class BufferedWriterCreation {

@RecipeDescriptor(
name = "Convert `new BufferedWriter(new FileWriter(File))` to `Files.newBufferedWriter(Path)`",
description = "Convert `new BufferedWriter(new FileWriter(f))` to `Files.newBufferedWriter(f.toPath())`."
)
static class BufferedWriterFromNewFileWriterWithFileArgument {
@BeforeTemplate
BufferedWriter before(java.io.File f) throws IOException {
return new BufferedWriter(new java.io.FileWriter(f));
}

@AfterTemplate
BufferedWriter after(java.io.File f) throws IOException {
return java.nio.file.Files.newBufferedWriter(f.toPath());
}
}

@RecipeDescriptor(
name = "Convert `new BufferedWriter(new FileWriter(String))` to `Files.newBufferedWriter(Path)`",
description = "Convert `new BufferedWriter(new FileWriter(s))` to `Files.newBufferedWriter(new java.io.File(s).toPath())`."
)
static class BufferedWriterFromNewFileWriterWithStringArgument {
@BeforeTemplate
BufferedWriter before(String s) throws IOException {
return new BufferedWriter(new java.io.FileWriter(s));
}

@AfterTemplate
BufferedWriter after(String s) throws IOException {
return java.nio.file.Files.newBufferedWriter(new java.io.File(s).toPath());
}
}

@RecipeDescriptor(
name = "Convert `new BufferedWriter(new FileWriter(File, boolean))` to `Files.newBufferedWriter(Path, StandardOpenOption)`",
description = "Convert `new BufferedWriter(new FileWriter(f, b))` to `Files.newBufferedWriter(f.toPath(), b ? StandardOpenOption.APPEND : StandardOpenOption.CREATE)`."
)
static class BufferedWriterFromNewFileWriterWithFileAndBooleanArguments {
@BeforeTemplate
BufferedWriter before(java.io.File f, @Primitive Boolean b) throws IOException {
return new BufferedWriter(new java.io.FileWriter(f, b));
}

@AfterTemplate
BufferedWriter after(java.io.File f, @Primitive Boolean b) throws IOException {
return java.nio.file.Files.newBufferedWriter(f.toPath(), b ?
java.nio.file.StandardOpenOption.APPEND : java.nio.file.StandardOpenOption.CREATE);
}
}

@RecipeDescriptor(
name = "Convert `new BufferedWriter(new FileWriter(String, boolean))` to `Files.newBufferedWriter(Path, StandardOpenOption)`",
description = "Convert `new BufferedWriter(new FileWriter(s, b))` to `Files.newBufferedWriter(new java.io.File(s).toPath(), b ? StandardOpenOption.APPEND : StandardOpenOption.CREATE)`."
)
static class BufferedWriterFromNewFileWriterWithStringAndBooleanArguments {
@BeforeTemplate
BufferedWriter before(String s, @Primitive Boolean b) throws IOException {
return new BufferedWriter(new java.io.FileWriter(s, b));
}

@AfterTemplate
BufferedWriter after(String s, @Primitive Boolean b) throws IOException {
return java.nio.file.Files.newBufferedWriter(new java.io.File(s).toPath(), b ?
java.nio.file.StandardOpenOption.APPEND : java.nio.file.StandardOpenOption.CREATE);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@
*/
package org.openrewrite.staticanalysis;

import org.jspecify.annotations.Nullable;
import org.openrewrite.Cursor;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.SourceFile;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.cleanup.SimplifyBooleanExpressionVisitor;
Expand Down Expand Up @@ -69,34 +68,31 @@ public J visitBlock(J.Block block, ExecutionContext ctx) {
}

@SuppressWarnings("unchecked")
private <E extends Expression> E cleanupBooleanExpression(
E expression, ExecutionContext ctx
) {
E ex1 =
(E) new UnnecessaryParenthesesVisitor()
.visitNonNull(expression, ctx, getCursor().getParentOrThrow());
ex1 = (E) new SimplifyBooleanExpressionVisitor()
.visitNonNull(ex1, ctx, getCursor().getParentTreeCursor());
if (expression == ex1 || isLiteralFalse(ex1) || isLiteralTrue(ex1)) {
private static <E extends Expression> E cleanupBooleanExpression(E expression, Cursor c, ExecutionContext ctx) {
E ex1 = (E) new UnnecessaryParenthesesVisitor<>().visitNonNull(expression, ctx, c.getParentOrThrow());
ex1 = (E) new SimplifyBooleanExpressionVisitor().visitNonNull(ex1, ctx, c.getParentTreeCursor());
if (expression == ex1 ||
J.Literal.isLiteralValue(ex1, Boolean.FALSE) ||
J.Literal.isLiteralValue(ex1, Boolean.TRUE)) {
return ex1;
}
// Run recursively until no further changes are needed
return cleanupBooleanExpression(ex1, ctx);
return cleanupBooleanExpression(ex1, c, ctx);
}

@Override
public J visitIf(J.If if_, ExecutionContext ctx) {
J.If if__ = (J.If) super.visitIf(if_, ctx);
J.If ifBeforeCleanup = if__;

J.ControlParentheses<Expression> cp = cleanupBooleanExpression(if__.getIfCondition(), ctx);
J.ControlParentheses<Expression> cp = cleanupBooleanExpression(if__.getIfCondition(), getCursor(), ctx);
if__ = if__.withIfCondition(cp);

// The compile-time constant value of the if condition control parentheses.
final Optional<Boolean> compileTimeConstantBoolean;
if (isLiteralTrue(cp.getTree())) {
if (J.Literal.isLiteralValue(cp.getTree(), Boolean.TRUE)) {
compileTimeConstantBoolean = Optional.of(true);
} else if (isLiteralFalse(cp.getTree())) {
} else if (J.Literal.isLiteralValue(cp.getTree(), Boolean.FALSE)) {
compileTimeConstantBoolean = Optional.of(false);
} else {
// The condition is not a literal, so we can't simplify it.
Expand Down Expand Up @@ -147,14 +143,5 @@ public J visitIf(J.If if_, ExecutionContext ctx) {
return J.Block.createEmptyBlock();
}
}

private static boolean isLiteralTrue(@Nullable Expression expression) {
return J.Literal.isLiteralValue(expression, Boolean.TRUE);
}

private static boolean isLiteralFalse(@Nullable Expression expression) {
return J.Literal.isLiteralValue(expression, Boolean.FALSE);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.staticanalysis;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

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

@SuppressWarnings("EmptyTryBlock")
class BufferedWriterCreationTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new BufferedWriterCreationRecipes());
}

@Test
@DocumentExample
void bufferedReaderCreation() {
rewriteRun(
//language=java
java(
"""
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;

public class BufferedWriterCreationTest {
public void createBufferedWriter(File f) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) {

}
}
}
""",
"""
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class BufferedWriterCreationTest {
public void createBufferedWriter(File f) throws IOException {
try (BufferedWriter writer = Files.newBufferedWriter(f.toPath())) {

}
}
}
"""
)
);
}

@Test
void bufferedReaderCreationAppend() {
rewriteRun(
//language=java
java(
"""
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;

public class BufferedWriterCreationTest {
public void createBufferedWriter(File f) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(f, true))) {

}
}
}
""",
"""
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;

public class BufferedWriterCreationTest {
public void createBufferedWriter(File f) throws IOException {
try (BufferedWriter writer = Files.newBufferedWriter(f.toPath(), StandardOpenOption.APPEND)) {

}
}
}
"""
)
);
}

@Test
void bufferedReaderStringCreation() {
rewriteRun(
//language=java
java(
"""
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;

public class BufferedWriterCreationTest {
public void createBufferedWriter(String f) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) {

}
}
}
""",
"""
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class BufferedWriterCreationTest {
public void createBufferedWriter(String f) throws IOException {
try (BufferedWriter writer = Files.newBufferedWriter(new File(f).toPath())) {

}
}
}
"""
)
);
}

@Test
void bufferedReaderStringCreationAppend() {
rewriteRun(
//language=java
java(
"""
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;

public class BufferedWriterCreationTest {
public void createBufferedWriter(String f) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(f, false))) {

}
}
}
""",
"""
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;

public class BufferedWriterCreationTest {
public void createBufferedWriter(String f) throws IOException {
try (BufferedWriter writer = Files.newBufferedWriter(new File(f).toPath(), StandardOpenOption.CREATE)) {

}
}
}
"""
)
);
}
}