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

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

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

import io.katharsis.resource.exception.init.InvalidResourceException;
import org.reflections.Reflections;

import java.util.HashSet;
import java.util.Set;

/**
 * Exception mapper lookup which scans the classpath for exception mappers which
 * are annotated with the {@link ExceptionMapperProvider} annotation.
 */
public class DefaultExceptionMapperLookup implements ExceptionMapperLookup {
    private String resourceSearchPackage;

    public DefaultExceptionMapperLookup(String resourceSearchPackage) {
        this.resourceSearchPackage = resourceSearchPackage;
    }

    @Override
    public Set getExceptionMappers() {
        Reflections reflections;
        if (resourceSearchPackage != null) {
            String[] packageNames = resourceSearchPackage.split(",");
            reflections = new Reflections(packageNames);
        } else {
            reflections = new Reflections(resourceSearchPackage);
        }
        Set> exceptionMapperClasses = reflections.getTypesAnnotatedWith(ExceptionMapperProvider.class);

        Set exceptionMappers = new HashSet();
        for (Class exceptionMapperClazz : exceptionMapperClasses) {
            if (!JsonApiExceptionMapper.class.isAssignableFrom(exceptionMapperClazz)) {
                throw new InvalidResourceException(exceptionMapperClazz.getCanonicalName() + " is not an implementation of JsonApiExceptionMapper");
            }
            try {
                exceptionMappers.add((JsonApiExceptionMapper) exceptionMapperClazz.newInstance());
            } catch (Exception e) {
                throw new InvalidResourceException(exceptionMapperClazz.getCanonicalName() + " can not be initialized", e);
            }
        }
        return exceptionMappers;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy