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

io.github.dronesecurity.userapplication.events.DomainEvents Maven / Gradle / Ivy

/*
 * Copyright (c) 2021-2022, Mirko Felice & Maxim Derevyanchenko. All rights reserved.
 * Licensed under the MIT license. See LICENSE file in the project root for details.
 */

package io.github.dronesecurity.userapplication.events;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

/**
 * Manager class of all domain events.
 */
public final class DomainEvents {

    private static final Map, List>> ALL_CONSUMERS =
            new ConcurrentHashMap<>();

    private DomainEvents() { }

    /**
     * Adds a handler to manage the arrival of an event.
     * @param clazz {@link Class} of the {@link DomainEvent} to register on
     * @param handler the {@link Consumer} to execute when an event is raised
     * @param  type parameter to constraint consuming only {@link DomainEvent} subclasses
     */
    public static  void register(final Class clazz, final Consumer handler) {
        ALL_CONSUMERS.computeIfAbsent(clazz, k -> new ArrayList<>());
        ALL_CONSUMERS.get(clazz).add(handler);
    }

    /**
     * Removes a handler previously registered.
     * @param clazz {@link Class} of the {@link DomainEvent} to unregister from
     * @param handler the {@link Consumer} previously registered
     * @param  type parameter to constraint consuming only {@link DomainEvent} subclasses
     */
    public static  void unregister(final Class clazz, final Consumer handler) {
        final List> consumers = ALL_CONSUMERS.get(clazz);
        if (consumers != null && handler != null) {
            consumers.remove(handler);
            if (consumers.isEmpty())
                ALL_CONSUMERS.remove(clazz);
        }
    }

    /**
     * Raises the event for the domain.
     *
     * @param event the new event
     * @param  type parameter to constraint raising only {@link DomainEvent} subclasses
     */
    @SuppressWarnings("unchecked")
    public static  void raise(final @NotNull T event) {
        final List> consumers =
                List.copyOf(ALL_CONSUMERS.getOrDefault(event.getClass(), new ArrayList<>()));
        for (final Consumer cons : consumers) {
            ((Consumer) cons).accept(event);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy