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

com.opencredo.concursus.mapping.events.pojos.PojoEventConverter Maven / Gradle / Ivy

The newest version!
package com.opencredo.concursus.mapping.events.pojos;

import com.google.common.base.Preconditions;
import com.opencredo.concursus.domain.common.VersionedName;
import com.opencredo.concursus.domain.events.Event;
import com.opencredo.concursus.mapping.annotations.Name;

import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class PojoEventConverter implements Function> {

    @SafeVarargs
    public static  PojoEventConverter mapping(Class...classes) {
        return mapping(Stream.of(classes));
    }

    public static  PojoEventConverter mapping(Collection> classes) {
        return mapping(classes.stream());
    }

    private static  PojoEventConverter mapping(Stream> classes) {
        return new PojoEventConverter<>(classes.collect(Collectors.toMap(
                PojoEventConverter::getVersionedName,
                Function.identity()
        )));
    }

    private static VersionedName getVersionedName(Class klass) {
        return klass.isAnnotationPresent(Name.class)
                ? VersionedName.of(
                    klass.getAnnotation(Name.class).value(),
                    klass.getAnnotation(Name.class).version())
                : VersionedName.of(
                    klass.getSimpleName().substring(0, 1).toLowerCase() + klass.getSimpleName().substring(1),
                    "0");
    }

    private final Map> classLookup;

    private PojoEventConverter(Map> classLookup) {
        this.classLookup = classLookup;
    }

    @Override
    public PojoEvent apply(Event event) {
        VersionedName eventName = event.getEventName();
        Preconditions.checkArgument(classLookup.containsKey(eventName),
                "No class registered for event %s", eventName);

        return PojoEvent.of(event, classLookup.get(eventName));
    }

}