Skip to content

Commit

Permalink
buffer and flush
Browse files Browse the repository at this point in the history
  • Loading branch information
JuicyDragon committed Aug 10, 2023
1 parent d40d862 commit 8ed1242
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
import org.jetbrains.annotations.NotNull;
import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.ScriptingContainer;
import org.jruby.embed.internal.BiVariableMap;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -25,11 +23,12 @@ public class RubyScriptRunner {
private static final Logger log = LogManager.getLogger(RubyScriptRunner.class);

/***
* Writer implementation which specializes in forwarding to to consumer. Used to forward
* Writer implementation which specializes in forwarding to a consumer. Used to forward
* standard out and err to consumer from script container.
*/
static class EventedWriter extends Writer {
private Consumer<String> consumer;
private final StringBuilder buffer = new StringBuilder();

public EventedWriter(Consumer<String> consumer) {
this.consumer = consumer;
Expand All @@ -42,13 +41,15 @@ public void write(@NotNull char[] cbuf, int off, int len) throws IOException {
char[] subchars = new char[len];
System.arraycopy(cbuf, off, subchars, 0, len);
String value = new String(subchars);
consumer.accept(value);
buffer.append(value);
}
}
}

@Override
public void flush() throws IOException {
consumer.accept(buffer.toString());
buffer.setLength(0); // Clear for reuse
}

@Override
Expand Down
3 changes: 2 additions & 1 deletion Nx/src/test/java/RubyScriptRunnerTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@ public class RubyScriptRunnerTests {
@Test
public void RunScript() throws Exception {
// Validate that script runs and output is captured
String script = "puts 'hello'";
String script = "5.times{puts 'hello'}";
List<String> output = new ArrayList<>();
RubyScriptRunner rubyScriptRunner = new RubyScriptRunner();
rubyScriptRunner.setStandardOutputConsumer(output::add);
rubyScriptRunner.setErrorOutputConsumer(output::add);
rubyScriptRunner.runScriptAsync(script, "0.0.0.0", Map.of());
rubyScriptRunner.join();
assertTrue(output.size() > 0);
System.out.println(String.join("",output));
}

@Test
Expand Down

0 comments on commit 8ed1242

Please sign in to comment.