Package match.handler

Source Code of match.handler.MatchHandler

package match.handler;

import match.aggregate.Match;
import match.api.Command;
import match.api.Event;
import match.api.EventStore;
import match.api.EventStream;
import match.event.CreatedMatchEvent;

import java.util.Iterator;
import java.util.UUID;

public class MatchHandler {

    private final EventStore eventStore;
    private Match match;

    public MatchHandler(Match match, EventStore eventStore) {
        this.match = match;
        this.eventStore = eventStore;
        this.eventStore.store(match.getMatchId(), this.match.handle(new CreatedMatchEvent(match.getMatchId(), match.getPlayerSet())));
    }

    public void handle(Command command) {
        Event event = match.handle(command);
        storeEvents(event);
    }

    private void storeEvents(Event event) {
        eventStore.store(match.getMatchId(), event);
        if (event.getSucceedingEvent().isPresent()) {
            storeEvents(event.getSucceedingEvent().get());
        }
    }

    public void restoreState(EventStream eventStream) {
        Iterator<Event> iterator = eventStream.iterator();
        CreatedMatchEvent createdMatchEvent = (CreatedMatchEvent) iterator.next();
        if (createdMatchEvent == null)
            throw new RuntimeException("Restoring state failed");

        this.match = new Match(UUID.randomUUID(), createdMatchEvent.getPlayersMap());

        // Execute all arisen events.
        while (iterator.hasNext()) {
            Event next = iterator.next();
            next.execute(this.match);
        }
    }

    public Match getMatch() {
        return match;
    }
}
TOP

Related Classes of match.handler.MatchHandler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.