package org.glassfish.jersey.internal;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.ext.ExceptionMapper;
import org.glassfish.jersey.internal.inject.Bindings;
import org.glassfish.jersey.internal.inject.InjectionManager;
import org.glassfish.jersey.internal.inject.InstanceBinding;
import org.glassfish.jersey.internal.inject.Providers;
import org.glassfish.jersey.internal.inject.ServiceHolder;
import org.glassfish.jersey.internal.util.ReflectionHelper;
import org.glassfish.jersey.internal.util.collection.ClassTypePair;
import org.glassfish.jersey.internal.util.collection.LazyValue;
import org.glassfish.jersey.internal.util.collection.Value;
import org.glassfish.jersey.internal.util.collection.Values;
import org.glassfish.jersey.spi.ExceptionMappers;
import org.glassfish.jersey.spi.ExtendedExceptionMapper;
public class ExceptionMapperFactory implements ExceptionMappers {
private static final Logger LOGGER = Logger.getLogger(ExceptionMapperFactory.class.getName());
public static class ExceptionMappersConfigurator implements BootstrapConfigurator {
private ExceptionMapperFactory exceptionMapperFactory;
@Override
public void init(InjectionManager injectionManager, BootstrapBag bootstrapBag) {
exceptionMapperFactory = new ExceptionMapperFactory(injectionManager);
InstanceBinding<ExceptionMapperFactory> binding =
Bindings.service(exceptionMapperFactory)
.to(ExceptionMappers.class);
injectionManager.register(binding);
}
@Override
public void postInit(InjectionManager injectionManager, BootstrapBag bootstrapBag) {
bootstrapBag.setExceptionMappers(exceptionMapperFactory);
}
}
private static class ExceptionMapperType {
ServiceHolder<ExceptionMapper> mapper;
Class<? extends Throwable> exceptionType;
public ExceptionMapperType(final ServiceHolder<ExceptionMapper> mapper, final Class<? extends Throwable> exceptionType) {
this.mapper = mapper;
this.exceptionType = exceptionType;
}
}
private final Value<Set<ExceptionMapperType>> exceptionMapperTypes;
@Override
@SuppressWarnings("unchecked")
public <T extends Throwable> ExceptionMapper<T> findMapping(final T exceptionInstance) {
return find((Class<T>) exceptionInstance.getClass(), exceptionInstance);
}
@Override
public <T extends Throwable> ExceptionMapper<T> find(final Class<T> type) {
return find(type, null);
}
@SuppressWarnings("unchecked")
private <T extends Throwable> ExceptionMapper<T> find(final Class<T> type, final T exceptionInstance) {
ExceptionMapper<T> mapper = null;
int minDistance = Integer.MAX_VALUE;
for (final ExceptionMapperType mapperType : exceptionMapperTypes.get()) {
final int d = distance(type, mapperType.exceptionType);
if (d >= 0 && d <= minDistance) {
final ExceptionMapper<T> candidate = mapperType.mapper.getInstance();
if (isPreferredCandidate(exceptionInstance, candidate, d == minDistance)) {
mapper = candidate;
minDistance = d;
if (d == 0) {
return mapper;
}
}
}
}
return mapper;
}
private <T extends Throwable> boolean isPreferredCandidate(final T exceptionInstance, final ExceptionMapper<T> candidate,
final boolean sameDistance) {
if (exceptionInstance == null) {
return true;
}
if (candidate instanceof ExtendedExceptionMapper) {
return !sameDistance
&& ((ExtendedExceptionMapper<T>) candidate).isMappable(exceptionInstance);
} else {
return !sameDistance;
}
}
public ExceptionMapperFactory(InjectionManager injectionManager) {
exceptionMapperTypes = createLazyExceptionMappers(injectionManager);
}
private LazyValue<Set<ExceptionMapperType>> createLazyExceptionMappers(InjectionManager injectionManager) {
return Values.lazy((Value<Set<ExceptionMapperType>>) () -> {
Collection<ServiceHolder<ExceptionMapper>> mapperHandles =
Providers.getAllServiceHolders(injectionManager, ExceptionMapper.class);
Set<ExceptionMapperType> exceptionMapperTypes = new LinkedHashSet<>();
for (ServiceHolder<ExceptionMapper> mapperHandle: mapperHandles) {
ExceptionMapper mapper = mapperHandle.getInstance();
if (Proxy.isProxyClass(mapper.getClass())) {
SortedSet<Class<? extends ExceptionMapper>> mapperTypes =
new TreeSet<>((o1, o2) -> o1.isAssignableFrom(o2) ? -1 : 1);
Set<Type> contracts = mapperHandle.getContractTypes();
for (final Type contract : contracts) {
if (contract instanceof Class
&& ExceptionMapper.class.isAssignableFrom((Class<?>) contract)
&& contract != ExceptionMapper.class) {
mapperTypes.add((Class<? extends ExceptionMapper>) contract);
}
}
if (!mapperTypes.isEmpty()) {
final Class<? extends Throwable> c = getExceptionType(mapperTypes.first());
if (c != null) {
exceptionMapperTypes.add(new ExceptionMapperType(mapperHandle, c));
}
}
} else {
final Class<? extends Throwable> c = getExceptionType(mapper.getClass());
if (c != null) {
exceptionMapperTypes.add(new ExceptionMapperType(mapperHandle, c));
}
}
}
return exceptionMapperTypes;
});
}
private int distance(Class<?> c, final Class<?> emtc) {
int distance = 0;
if (!emtc.isAssignableFrom(c)) {
return -1;
}
while (c != emtc) {
c = c.getSuperclass();
distance++;
}
return distance;
}
@SuppressWarnings("unchecked")
private Class<? extends Throwable> getExceptionType(final Class<? extends ExceptionMapper> c) {
final Class<?> t = getType(c);
if (Throwable.class.isAssignableFrom(t)) {
return (Class<? extends Throwable>) t;
}
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.warning(LocalizationMessages.EXCEPTION_MAPPER_SUPPORTED_TYPE_UNKNOWN(c.getName()));
}
return null;
}
private Class getType(final Class<? extends ExceptionMapper> clazz) {
Class clazzHolder = clazz;
while (clazzHolder != Object.class) {
final Class type = getTypeFromInterface(clazzHolder, clazz);
if (type != null) {
return type;
}
clazzHolder = clazzHolder.getSuperclass();
}
throw new ProcessingException(LocalizationMessages.ERROR_FINDING_EXCEPTION_MAPPER_TYPE(clazz));
}
private Class getTypeFromInterface(Class<?> clazz, final Class<? extends ExceptionMapper> original) {
final Type[] types = clazz.getGenericInterfaces();
for (final Type type : types) {
if (type instanceof ParameterizedType) {
final ParameterizedType pt = (ParameterizedType) type;
if (pt.getRawType() == ExceptionMapper.class
|| pt.getRawType() == ExtendedExceptionMapper.class) {
return getResolvedType(pt.getActualTypeArguments()[0], original, clazz);
}
} else if (type instanceof Class<?>) {
clazz = (Class<?>) type;
if (ExceptionMapper.class.isAssignableFrom(clazz)) {
return getTypeFromInterface(clazz, original);
}
}
}
return null;
}
private Class getResolvedType(final Type t, final Class c, final Class dc) {
if (t instanceof Class) {
return (Class) t;
} else if (t instanceof TypeVariable) {
final ClassTypePair ct = ReflectionHelper.resolveTypeVariable(c, dc, (TypeVariable) t);
if (ct != null) {
return ct.rawClass();
} else {
return null;
}
} else if (t instanceof ParameterizedType) {
final ParameterizedType pt = (ParameterizedType) t;
return (Class) pt.getRawType();
} else {
return null;
}
}
}