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

com.opencredo.concourse.domain.storing.InMemoryEventStore Maven / Gradle / Ivy

package com.opencredo.concourse.domain.storing;

import com.opencredo.concourse.domain.common.AggregateId;
import com.opencredo.concourse.domain.events.Event;
import com.opencredo.concourse.domain.events.matching.EventTypeMatcher;
import com.opencredo.concourse.domain.time.TimeRange;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static com.opencredo.concourse.domain.events.selection.EventSelection.*;

/**
 * An in-memory {@link EventStore}, primarily for testing purposes.
 */
public final class InMemoryEventStore implements EventStore {

    private static final Comparator reverseTimestampOrder = Comparator.comparing(Event::getEventTimestamp)
            .reversed();

    public static InMemoryEventStore empty() {
        return new InMemoryEventStore(new ConcurrentHashMap<>());
    }

    public static InMemoryEventStore with(Collection events) {
        InMemoryEventStore eventStore = empty();
        eventStore.accept(events);
        return eventStore;
    }

    private final ConcurrentMap> events;

    private InMemoryEventStore(ConcurrentMap> events) {
        this.events = events;
    }

    @Override
    public void accept(Collection events) {
        events.forEach(this::store);
    }

    private void store(Event event) {
        events.compute(event.getAggregateId(),
                (id, events) -> {
                    Set updatedEvents = events == null ? new TreeSet<>(reverseTimestampOrder) : events;
                    updatedEvents.add(event);
                    return updatedEvents;
                });
    }

    @Override
    public List getEvents(EventTypeMatcher matcher, AggregateId aggregateId, TimeRange timeRange) {
        return selectEvents(events, inRange(timeRange).and(matchedBy(matcher)), aggregateId);
    }

    @Override
    public Map> getEvents(EventTypeMatcher matcher, String aggregateType, Collection aggregateIds, TimeRange timeRange) {
        return selectEvents(events, matchedBy(matcher).and(inRange(timeRange)), aggregateType, aggregateIds);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy