io.crnk.cdi.internal.CdiServiceDiscovery Maven / Gradle / Ivy
package io.crnk.cdi.internal;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.CDI;
import javax.enterprise.util.TypeLiteral;
import io.crnk.core.engine.error.JsonApiExceptionMapper;
import io.crnk.core.engine.internal.utils.ClassUtils;
import io.crnk.core.module.discovery.ServiceDiscovery;
import io.crnk.core.utils.Optional;
/**
* CDI-based discovery of services.
*
* By default makes use of CDI.current() to get a BeanManager instance. An additional setter allows to set a custom
* BeanManager.
*/
public class CdiServiceDiscovery implements ServiceDiscovery {
private BeanManager beanManager;
public void setBeanManager(BeanManager beanManager) {
this.beanManager = beanManager;
}
public BeanManager getBeanManager() {
if (beanManager != null) {
return beanManager;
}
else {
return CDI.current().getBeanManager();
}
}
@SuppressWarnings("unchecked")
@Override
public List getInstancesByType(Class clazz) {
BeanManager beanManager = getBeanManager();
Type type = clazz;
if (clazz == JsonApiExceptionMapper.class) {
TypeLiteral> typeLiteral = new TypeLiteral>() {
};
type = typeLiteral.getType();
}
Set> beans = beanManager.getBeans(type);
List list = new ArrayList<>();
for (Bean> bean : beans) {
CreationalContext> creationalContext = beanManager.createCreationalContext(bean);
T object = (T) beanManager.getReference(bean, type, creationalContext);
list.add(object);
}
return list;
}
@Override
public List