Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/changes/changes.xml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
<action type="fix" dev="ggregory" due-to="Sharang Gupta, Gary Gregory">Add missing @Test to CSVFormatTest.testEqualsSkipHeaderRecord#testEqualsSkipHeaderRecord() (#639).</action>
<action type="fix" dev="ggregory" due-to="Mohd Irshad, Gary Gregory">Fix Predefined @see references in CSVFormat (#641).</action>
<action type="fix" dev="ggregory" due-to="Gary Gregory">Document CSVFormat validation exceptions.</action>
<action type="fix" issue="CSV-334" due-to="Qiuye Wang">Close the file writer if CSVPrinter construction fails.</action>
<!-- ADD -->
<action type="add" dev="ggregory" due-to="Gary Gregory, Indy, Sylvia van Os" issue="CSV-307">Add an "Android Compatibility" section to the web site.</action>
<action type="add" dev="ggregory" due-to="Ruiqi Dong, Gary Gregory" issue="CSV-325">Add CSVParser.Builder.setByteOffset(long) (#604).</action>
Expand Down
24 changes: 23 additions & 1 deletion src/main/java/org/apache/commons/csv/CSVFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -2720,7 +2720,29 @@ private void print(final Object object, final CharSequence value, final Appendab
*/
@SuppressWarnings("resource")
public CSVPrinter print(final Path out, final Charset charset) throws IOException {
return print(Files.newBufferedWriter(out, charset));
return printWithOwnedWriter(Files.newBufferedWriter(out, charset));
}

/**
* Creates a printer for a writer opened by the path overload, closing the writer if construction fails.
*
* @param out The writer to pass to the printer.
* @return A printer to the writer.
* @throws IOException If the optional header comments or header cannot be printed.
*/
CSVPrinter printWithOwnedWriter(final Writer out) throws IOException {
try {
return print(out);
} catch (final IOException | RuntimeException | Error creationFailure) {
try {
out.close();
} catch (final IOException | RuntimeException | Error closeFailure) {
if (closeFailure != creationFailure) {
creationFailure.addSuppressed(closeFailure);
}
}
throw creationFailure;
}
}

/**
Expand Down
68 changes: 68 additions & 0 deletions src/test/java/org/apache/commons/csv/CSVFormatTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
Expand All @@ -43,6 +44,7 @@
import java.io.ObjectOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
Expand All @@ -56,6 +58,8 @@

import org.apache.commons.csv.CSVFormat.Builder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

/**
* Tests {@link CSVFormat}.
Expand All @@ -70,6 +74,38 @@ public enum Header {
Name, Email, Phone
}

private static final class RecordingWriter extends Writer {

private final IOException writeFailure;
private final IOException closeFailure;
private int closeCount;

RecordingWriter(final IOException writeFailure, final IOException closeFailure) {
this.writeFailure = writeFailure;
this.closeFailure = closeFailure;
}

@Override
public void close() throws IOException {
closeCount++;
if (closeFailure != null) {
throw closeFailure;
}
}

@Override
public void flush() {
// no-op
}

@Override
public void write(final char[] buffer, final int offset, final int length) throws IOException {
if (writeFailure != null) {
throw writeFailure;
}
}
}

private static void assertNotEqualsFlip(final Object right, final Object left) {
assertNotEquals(right, left);
assertNotEquals(left, right);
Expand Down Expand Up @@ -912,6 +948,38 @@ void testNullRecordSeparatorCsv106__Deprecated() {
assertFalse(formatStr.endsWith("null"));
}

@Test
void testPrintBorrowedWriterLeavesOwnershipOnConstructionFailure() {
final CSVFormat format = CSVFormat.DEFAULT.builder().setHeader("A").get();
final IOException writeFailure = new IOException("header write failed");
final RecordingWriter writer = new RecordingWriter(writeFailure, null);
assertSame(writeFailure, assertThrows(IOException.class, () -> format.print(writer)));
assertEquals(0, writer.closeCount);
}

@ParameterizedTest
@ValueSource(booleans = {false, true})
void testPrintOwnedWriterClosesAfterHeaderFailure(final boolean sameFailure) {
final CSVFormat format = CSVFormat.DEFAULT.builder().setHeader("A").get();
final IOException writeFailure = new IOException("header write failed");
final IOException closeFailure = sameFailure ? writeFailure : new IOException("close failed");
final RecordingWriter writer = new RecordingWriter(writeFailure, closeFailure);
final IOException actual = assertThrows(IOException.class, () -> format.printWithOwnedWriter(writer));
assertSame(writeFailure, actual);
assertEquals(1, writer.closeCount);
assertArrayEquals(sameFailure ? new Throwable[0] : new Throwable[] {closeFailure}, actual.getSuppressed());
}

@Test
void testPrintOwnedWriterTransfersOwnershipOnSuccess() throws IOException {
final RecordingWriter writer = new RecordingWriter(null, null);
try (CSVPrinter printer = CSVFormat.DEFAULT.printWithOwnedWriter(writer)) {
printer.printRecord("value");
assertEquals(0, writer.closeCount);
}
assertEquals(1, writer.closeCount);
}

@Test
void testPrintRecord() throws IOException {
final Appendable out = new StringBuilder();
Expand Down