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

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

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

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;

public final class ExceptionMapperRegistryBuilder {
    private final Set exceptionMappers = new HashSet();

    public ExceptionMapperRegistry build(String resourceSearchPackage) {
        return build(new DefaultExceptionMapperLookup(resourceSearchPackage));
    }

    public ExceptionMapperRegistry build(ExceptionMapperLookup exceptionMapperLookup) {
        addKatharsisDefaultMappers();
        for (JsonApiExceptionMapper exceptionMapper : exceptionMapperLookup.getExceptionMappers()) {
            registerExceptionMapper(exceptionMapper);
        }
        return new ExceptionMapperRegistry(exceptionMappers);
    }

    private void addKatharsisDefaultMappers() {
        registerExceptionMapper(new KatharsisExceptionMapper());
    }

    private void registerExceptionMapper(JsonApiExceptionMapper exceptionMapper) {
        Class exceptionClass = getGenericType(exceptionMapper.getClass());
        exceptionMappers.add(new ExceptionMapperType(exceptionClass, exceptionMapper));
    }

    private Class getGenericType(Class mapper) {
        Type[] types = mapper.getGenericInterfaces();
        for (Type type : types) {
        	if (type instanceof ParameterizedType && (((ParameterizedType)type).getRawType() == JsonApiExceptionMapper.class || ((ParameterizedType)type).getRawType() == ExceptionMapper.class)) {
                //noinspection unchecked
                return (Class)((ParameterizedType)type).getActualTypeArguments()[0];
            }
        }
        //Won't get in here
        return null;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy