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

io.serialized.client.aggregate.StateBuilder Maven / Gradle / Ivy

package io.serialized.client.aggregate;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

public class StateBuilder {

  private final Class stateClass;
  private final Map> handlers = new LinkedHashMap<>();

  private StateBuilder(Class stateClass, Map> handlers) {
    this.stateClass = stateClass;
    this.handlers.putAll(handlers);
  }

  public static  StateBuilder stateBuilder(Class stateClass) {
    return new StateBuilder<>(stateClass, new LinkedHashMap<>());
  }

  public static  StateBuilder stateBuilder(Class stateClass, Map> handlers) {
    return new StateBuilder<>(stateClass, handlers);
  }

  public  StateBuilder withHandler(Class eventClass, EventHandler handler) {
    this.handlers.put(eventClass.getSimpleName(), handler);
    return this;
  }

  public T buildState(List events) {
    try {
      AtomicReference data = new AtomicReference<>(stateClass.newInstance());
      events.forEach(e -> {
        String simpleName = e.data().getClass().getSimpleName();
        EventHandler handler = handlers.get(simpleName);

        if (handler == null) {
          throw new IllegalStateException("No matching handler for event type: " + simpleName);
        }

        T handle = (T) handler.handle(data.get(), e);
        data.set(handle);
          }
      );
      return data.get();
    } catch (InstantiationException | IllegalAccessException e) {
      throw new RuntimeException("Failed to build State", e);
    }
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy