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

io.katharsis.errorhandling.mapper.ExceptionMapperRegistry Maven / Gradle / Ivy

There is a newer version: 3.0.2
Show newest version
package io.katharsis.errorhandling.mapper;

import io.katharsis.utils.java.Optional;

import java.util.Set;

public final class ExceptionMapperRegistry {

    private final Set exceptionMappers;

    ExceptionMapperRegistry(Set exceptionMappers) {
        this.exceptionMappers = exceptionMappers;
    }

    Set getExceptionMappers() {
        return exceptionMappers;
    }

    public Optional findMapperFor(Class exceptionClass) {
        int currentDistance = Integer.MAX_VALUE;
        JsonApiExceptionMapper closestExceptionMapper = null;
        for (ExceptionMapperType mapperType : exceptionMappers) {
            int tempDistance = getDistanceBetweenExceptions(exceptionClass, mapperType.getExceptionClass());
            if (tempDistance < currentDistance) {
                currentDistance = tempDistance;
                closestExceptionMapper = mapperType.getExceptionMapper();
                if (currentDistance == 0) {
                    break;
                }
            }
        }
        return Optional.ofNullable(closestExceptionMapper);
    }

    int getDistanceBetweenExceptions(Class clazz, Class mapperTypeClazz) {
        int distance = 0;
        Class superClazz = clazz;
        if (!mapperTypeClazz.isAssignableFrom(clazz))
            return Integer.MAX_VALUE;

        while (superClazz != mapperTypeClazz) {
            superClazz = superClazz.getSuperclass();
            distance++;
        }
        return distance;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy