Skip to content

Commit

Permalink
Add LogOutputStream.create(LineConsumer) (#107)
Browse files Browse the repository at this point in the history
So instead of creating an anonymous class it can be one-liner with a lambda expression.
  • Loading branch information
panchenko committed Mar 15, 2024
1 parent 812eb73 commit 2ba09d1
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 7 deletions.
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,17 @@ new ProcessExecutor().command("java", "-version")

<hr/>

* Handling output line-by-line while process is running
* Handling output line-by-line while process is running (Java 8+)

```java
new ProcessExecutor().command("java", "-version")
.redirectOutput(line -> ...)
.execute();
```

<hr/>

* Handling output line-by-line while process is running (prior to Java 8)

```java
new ProcessExecutor().command("java", "-version")
Expand Down Expand Up @@ -264,4 +274,3 @@ Future<ProcessResult> future = new ProcessExecutor()
// do some stuff
String output = future.get(60, TimeUnit.SECONDS).outputUTF8();
```

30 changes: 28 additions & 2 deletions src/main/java/org/zeroturnaround/exec/ProcessExecutor.java
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ public class ProcessExecutor {
// Run in case of any constructor
exitValues(DEFAULT_EXIT_VALUES);
stopper(DestroyProcessStopper.INSTANCE);
redirectOutput(null);
redirectError(null);
redirectOutput(NullOutputStream.NULL_OUTPUT_STREAM);
redirectError(NullOutputStream.NULL_OUTPUT_STREAM);
destroyer(null);
redirectErrorStream(DEFAULT_REDIRECT_ERROR_STREAM);
}
Expand Down Expand Up @@ -471,6 +471,19 @@ public ProcessExecutor redirectOutput(OutputStream output) {
return streams(new PumpStreamHandler(output, pumps == null ? null : pumps.getErr(), pumps == null ? null : pumps.getInput()));
}

/**
* Redirects the process' output stream to given line consumer.
* If this method is invoked multiple times each call overwrites the previous.
* Use {@link #redirectOutputAlsoTo(OutputStream)} if you want to redirect the output to multiple streams.
*
* @param consumer consumer where the process output is redirected to.
* @return This process executor.
* @see #redirectOutput(OutputStream)
*/
public ProcessExecutor redirectOutput(LineConsumer consumer) {
return redirectOutput(LogOutputStream.create(consumer));
}

/**
* Redirects the process' error stream to given output stream.
* If this method is invoked multiple times each call overwrites the previous.
Expand All @@ -492,6 +505,19 @@ public ProcessExecutor redirectError(OutputStream output) {
return this;
}

/**
* Redirects the process' error stream to given line consumer.
* If this method is invoked multiple times each call overwrites the previous.
* Use {@link #redirectErrorAlsoTo(OutputStream)} if you want to redirect the output to multiple streams.
*
* @param consumer consumer where the process error is redirected to.
* @return This process executor.
* @see #redirectError(OutputStream)
*/
public ProcessExecutor redirectError(LineConsumer consumer) {
return redirectError(LogOutputStream.create(consumer));
}

/**
* Redirects the process' output stream also to a given output stream.
* This method can be used to redirect output to multiple streams.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package org.zeroturnaround.exec.stream;

/**
* This is equivalent to {@code java.util.function.Consumer} while staying compatible with
* Java versions earlier than 8.
*/
public interface LineConsumer {
void accept(String line);
}
23 changes: 20 additions & 3 deletions src/main/java/org/zeroturnaround/exec/stream/LogOutputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
* Base class to connect a logging system to the output and/or
Expand All @@ -32,7 +31,7 @@
public abstract class LogOutputStream extends OutputStream {

/** Initial buffer size. */
private static final int INTIAL_SIZE = 132;
private static final int INITIAL_SIZE = 132;

/** Carriage return */
private static final int CR = 0x0d;
Expand All @@ -42,7 +41,7 @@ public abstract class LogOutputStream extends OutputStream {

/** the internal buffer */
private final ByteArrayOutputStream buffer = new ByteArrayOutputStream(
INTIAL_SIZE);
INITIAL_SIZE);

byte lastReceivedByte;

Expand Down Expand Up @@ -159,4 +158,22 @@ protected void processBuffer() {
*/
protected abstract void processLine(String line);

/**
* Factory method to create a <code>LogOutputStream</code> that passes each line to the specified consumer.
* <p>Mostly useful with Java 8+, so the consumer can be passed as a lambda expression.</p>
*
* @param consumer the consumer to consume the log lines
* @return the created <code>LogOutputStream</code>, passing each line to the specified consumer.
*/
public static LogOutputStream create(final LineConsumer consumer) {
if (consumer == null) {
throw new IllegalArgumentException("Line consumer must be provided.");
}
return new LogOutputStream() {
@Override
protected void processLine(String line) {
consumer.accept(line);
}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import org.junit.Assert;
import org.junit.Test;
import org.zeroturnaround.exec.stream.LineConsumer;
import org.zeroturnaround.exec.stream.LogOutputStream;

public class LogOutputStreamTest {
Expand Down Expand Up @@ -74,4 +75,16 @@ public void testNewLineAtTheEnd() throws UnsupportedEncodingException, IOExcepti
testLogOutputStream("foo\n", "foo");
}

@Test
public void lambda() throws IOException {
final List<String> lines = new ArrayList<String>();
LogOutputStream out = LogOutputStream.create(new LineConsumer() {
@Override
public void accept(String line) {
lines.add(line);
}
});
out.write("foo\nbar\n".getBytes());
Assert.assertEquals(Arrays.asList("foo", "bar"), lines);
}
}

0 comments on commit 2ba09d1

Please sign in to comment.