Skip to content

Commit

Permalink
Fix non ascii character handling
Browse files Browse the repository at this point in the history
  • Loading branch information
jebeaudet committed Jun 21, 2023
1 parent 90b8337 commit 4868265
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/main/java/org/codehaus/mojo/exec/LineRedirectOutputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@
* under the License.
*/

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
Expand All @@ -32,8 +37,8 @@
*/
class LineRedirectOutputStream extends OutputStream {

private StringBuilder currentLine = new StringBuilder();
private final Consumer<String> linePrinter;
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();

public LineRedirectOutputStream(Consumer<String> linePrinter) {
this.linePrinter = linePrinter;
Expand All @@ -45,18 +50,23 @@ public void write(final int b) {
printAndReset();
return;
}
currentLine.append((char) b);
buffer.write(b);
}

@Override
public void flush() {
if (currentLine.length() > 0) {
if (buffer.size() > 0) {
printAndReset();
}
}

@Override
public void close() {
flush();
}

private void printAndReset() {
linePrinter.accept(currentLine.toString());
currentLine = new StringBuilder();
linePrinter.accept(new String(buffer.toByteArray(), Charset.defaultCharset()));
buffer = new ByteArrayOutputStream();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package org.codehaus.mojo.exec;

import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.Charset;

public class LineRedirectOutputStreamTest {

@Test
public void givenUtf8Output_whenRedirecting_thenShouldDecodeProperly() throws IOException {
StringBuilder sb = new StringBuilder();
String firstLine = "Hello 😃 😄";
String secondLine = "foo bar éà";

try (LineRedirectOutputStream os = new LineRedirectOutputStream(sb::append)) {
os.write(String.join("\n", firstLine, secondLine).getBytes(Charset.defaultCharset()));
}

Assert.assertEquals(firstLine + secondLine, sb.toString());
}
}

0 comments on commit 4868265

Please sign in to comment.