All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.thorbenkuck.keller.event.NativeParallelDispatcherStrategy Maven / Gradle / Ivy

The newest version!
package com.github.thorbenkuck.keller.event;

import com.github.thorbenkuck.keller.utility.Keller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

final class NativeParallelDispatcherStrategy implements DispatcherStrategy {

	private final EventBus eventBus;

	NativeParallelDispatcherStrategy(final EventBus eventBus) {
		this.eventBus = eventBus;
	}

	private void dispatch(final List eventBridgeList, final Object event) {
		final List newEvents = new ArrayList<>();
		eventBridgeList
				.parallelStream()
				.forEach(listening -> {
					final Object result = listening.trigger(event);
					if(result != null) {
						newEvents.add(result);
					}
				});

		newEvents.forEach(eventBus::post);
	}

	@Override
	public void dispatch(final Object event, final Collection bridges) {
		Keller.parameterNotNull(event);
		final List listings = bridges.stream()
				.filter(listening -> listening.isApplicable(event))
				.collect(Collectors.toList());

		dispatch(listings, event);
	}

	@Override
	public void dispatchDeadEvent(final DeadEvent deadEvent, final Collection bridges) {
		final List deadEventHandler = bridges.stream()
				.filter(listening -> listening.isApplicable(deadEvent))
				.collect(Collectors.toList());
		if(deadEventHandler.isEmpty()) {
			final Object originalEvent = deadEvent.getEvent();
			throw new DeadEventException("Found DeadEvent[" + originalEvent.getClass() + "]: " + originalEvent);
		}

		deadEventHandler.forEach(listening -> listening.trigger(deadEvent));
	}
}