Skip to content

Commit

Permalink
[Core] Use MessageToNdjsonWriter in MessageFormatter
Browse files Browse the repository at this point in the history
Follow consistent patterns where all messages are written using
dedicated writers
  • Loading branch information
mpkorstanje committed Apr 5, 2024
1 parent 6a1b362 commit 6549826
Showing 1 changed file with 16 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,35 +1,41 @@
package io.cucumber.core.plugin;

import io.cucumber.messages.MessageToNdjsonWriter;
import io.cucumber.messages.types.Envelope;
import io.cucumber.plugin.ConcurrentEventListener;
import io.cucumber.plugin.event.EventPublisher;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

public final class MessageFormatter implements ConcurrentEventListener {

private final Writer writer;
private final MessageToNdjsonWriter writer;

public MessageFormatter(OutputStream outputStream) {
this.writer = new UTF8OutputStreamWriter(outputStream);
this.writer = new MessageToNdjsonWriter(outputStream, Jackson.OBJECT_MAPPER::writeValue);
}

@Override
public void setEventPublisher(EventPublisher publisher) {
publisher.registerHandlerFor(Envelope.class, this::writeMessage);
publisher.registerHandlerFor(Envelope.class, this::write);
}

private void writeMessage(Envelope envelope) {
private void write(Envelope event) {
try {
Jackson.OBJECT_MAPPER.writeValue(writer, envelope);
writer.write("\n");
if (envelope.getTestRunFinished().isPresent()) {
writer.write(event);
} catch (IOException e) {
throw new IllegalStateException(e);
}

// TODO: Plugins should implement the closable interface
// and be closed by Cucumber
if (event.getTestRunFinished().isPresent()) {
try {
writer.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

Expand Down

0 comments on commit 6549826

Please sign in to comment.