io.cucumber.core.eventbus.AbstractEventPublisher Maven / Gradle / Ivy
The newest version!
package io.cucumber.core.eventbus;
import io.cucumber.plugin.event.Event;
import io.cucumber.plugin.event.EventHandler;
import io.cucumber.plugin.event.EventPublisher;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class AbstractEventPublisher implements EventPublisher {
protected final Map, List> handlers = new HashMap<>();
@Override
public final void registerHandlerFor(Class eventType, EventHandler handler) {
if (handlers.containsKey(eventType)) {
handlers.get(eventType).add(handler);
} else {
List list = new ArrayList<>();
list.add(handler);
handlers.put(eventType, list);
}
}
@Override
public final void removeHandlerFor(Class eventType, EventHandler handler) {
if (handlers.containsKey(eventType)) {
handlers.get(eventType).remove(handler);
}
}
protected void sendAll(Iterable events) {
for (T event : events) {
send(event);
}
}
protected void send(T event) {
if (handlers.containsKey(Event.class) && event instanceof Event) {
for (EventHandler handler : handlers.get(Event.class)) {
// noinspection unchecked: protected by registerHandlerFor
handler.receive(event);
}
}
if (handlers.containsKey(event.getClass())) {
for (EventHandler handler : handlers.get(event.getClass())) {
// noinspection unchecked: protected by registerHandlerFor
handler.receive(event);
}
}
}
}