Java Code Examples for javax.enterprise.inject.spi.BeanManager

The following examples show how to use javax.enterprise.inject.spi.BeanManager. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: smallrye-jwt   Source File: SmallRyeJWTAuthCDIExtension.java    License: Apache License 2.0 6 votes vote down vote up
void beforeBeanDiscovery(@Observes BeforeBeanDiscovery event, BeanManager beanManager) {
    CDILogging.log.beforeBeanDiscovery(beanManager);

    // TODO: Do not add CDI beans unless @LoginConfig (or other trigger) is configured
    addAnnotatedType(event, beanManager, ClaimValueProducer.class);
    addAnnotatedType(event, beanManager, CommonJwtProducer.class);
    addAnnotatedType(event, beanManager, DefaultJWTParser.class);
    addAnnotatedType(event, beanManager, JsonValueProducer.class);
    addAnnotatedType(event, beanManager, JWTAuthContextInfoProvider.class);
    addAnnotatedType(event, beanManager, JWTAuthenticationFilter.class);
    addAnnotatedType(event, beanManager, PrincipalProducer.class);
    addAnnotatedType(event, beanManager, RawClaimTypeProducer.class);
    if (registerOptionalClaimTypeProducer()) {
        addAnnotatedType(event, beanManager, OptionalClaimTypeProducer.class);
    }

    if (isEESecurityAvailable()) {
        addAnnotatedType(event, beanManager, JWTHttpAuthenticationMechanism.class);
        CDILogging.log.jwtHttpAuthenticationMechanismRegistered();
    } else {
        // EE Security is not available, register the JAX-RS authentication filter.
        CDILogging.log.jwtHttpAuthenticationMechanismNotRegistered();
    }
}
 
Example 2
Source Project: cdi   Source File: AxonCdiExtension.java    License: Apache License 2.0 6 votes vote down vote up
private void registerMessageHandlers(BeanManager beanManager, Configurer configurer,
        EventHandlingConfiguration eventHandlingConfiguration) {
    for (MessageHandlingBeanDefinition messageHandler : messageHandlers) {
        Component<Object> component = new Component<>(() -> null, "messageHandler",
                c -> messageHandler.getBean().create(beanManager.createCreationalContext(null)));

        if (messageHandler.isEventHandler()) {
            logger.info("Registering event handler: {}.",
                    messageHandler.getBean().getBeanClass().getSimpleName());
            eventHandlingConfiguration.registerEventHandler(c -> component.get());
        }

        if (messageHandler.isCommandHandler()) {
            logger.info("Registering command handler: {}.",
                    messageHandler.getBean().getBeanClass().getSimpleName());
            configurer.registerCommandHandler(c -> component.get());
        }

        if (messageHandler.isQueryHandler()) {
            logger.info("Registering query handler: {}.",
                    messageHandler.getBean().getBeanClass().getSimpleName());
            configurer.registerQueryHandler(c -> component.get());
        }
    }
}
 
Example 3
Source Project: ozark   Source File: OzarkServletContextListenerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void failIfControllerIsNoCdiBean() {

    BeanManager beanManager = createMock(BeanManager.class);
    ServletContextEvent event = createMock(ServletContextEvent.class);
    ServletContext context = createMock(ServletContext.class);

    OzarkServletContextListener listener = new OzarkServletContextListener(beanManager);
    Set<Class<?>> controllers = new HashSet<>(singletonList(TestController.class));

    expect(event.getServletContext()).andStubReturn(context);
    expect(context.getAttribute(OzarkContainerInitializer.CONTROLLER_CLASSES)).andStubReturn(controllers);
    expect(beanManager.getBeans(TestController.class)).andStubReturn(new HashSet<>());

    EasyMock.replay(event, context, beanManager);

    listener.contextInitialized(event);
}
 
Example 4
Source Project: crnk-framework   Source File: CdiServiceDiscovery.java    License: Apache License 2.0 6 votes vote down vote up
public BeanManager getBeanManager() {
	if (beanManager != null) {
		return beanManager;
	} else if (cdiAvailable != Boolean.FALSE) {
		try {
			CDI<Object> current = CDI.current();
			cdiAvailable = Boolean.TRUE;
			return current.getBeanManager();
		} catch (IllegalStateException e) {
			LOGGER.error("CDI context not available, CdiServiceDiscovery will not be used");
			LOGGER.debug("CDI.current() failed", e);
			cdiAvailable = Boolean.FALSE;
			return null;
		}
	}
	return null;
}
 
Example 5
Source Project: openwebbeans-meecrowave   Source File: JtaExtension.java    License: Apache License 2.0 6 votes vote down vote up
void addContextAndBeans(@Observes final AfterBeanDiscovery afterBeanDiscovery, final BeanManager bm) {
    context = new TransactionContext();
    afterBeanDiscovery.addContext(context);

    if (!hasManager && !hasRegistry) {
        try {
            final GeronimoTransactionManager mgr = new GeronimoTransactionManager();
            afterBeanDiscovery.addBean(new JtaBean(mgr));
        } catch (final XAException e) {
            throw new IllegalStateException(e);
        }
        hasManager = true;
        hasRegistry = true;
    }

    afterBeanDiscovery.addBean(new JtaConfigBean(config));
}
 
Example 6
public static SubscriptionPublisherInjectionWrapper createInvocationHandler(Bean<?> bean, BeanManager beanManager) {
    SubscriptionPublisherProducer subscriptionPublisherProducer = getSubscriptionPublisherProducerReference(beanManager);
    Class proxiedInterface = SubscriptionPublisherInjection.class;
    Class subscriptionPublisherClass = null;
    Class beanClass = bean.getBeanClass();
    for (InjectionPoint injectionPoint : bean.getInjectionPoints()) {
        if (!injectionPoint.getQualifiers().contains(SUBSCRIPTION_PUBLISHER_ANNOTATION_LITERAL)) {
            continue;
        }
        Type baseType = injectionPoint.getAnnotated().getBaseType();
        if (baseType instanceof Class && SubscriptionPublisher.class.isAssignableFrom((Class) baseType)) {
            subscriptionPublisherClass = (Class) baseType;
            break;
        }
    }
    logger.debug("Found injector {} and publisher {} classes.", proxiedInterface, subscriptionPublisherClass);
    if (subscriptionPublisherClass == null || proxiedInterface == null) {
        throw new JoynrIllegalStateException("Cannot create subscription publisher injection wrapper proxy for bean which doesn't inject a concrete SubscriptionPublisher.");
    }
    return new SubscriptionPublisherInjectionWrapper(proxiedInterface,
                                                     subscriptionPublisherClass,
                                                     subscriptionPublisherProducer,
                                                     beanClass);
}
 
Example 7
Source Project: quarkus   Source File: BeanManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testResolveInterceptors() {
    BeanManager beanManager = Arc.container().beanManager();
    List<javax.enterprise.inject.spi.Interceptor<?>> interceptors;
    // InterceptionType does not match
    interceptors = beanManager.resolveInterceptors(InterceptionType.AROUND_CONSTRUCT, new DummyBinding.Literal(true, true));
    assertTrue(interceptors.isEmpty());
    // alpha is @Nonbinding
    interceptors = beanManager.resolveInterceptors(InterceptionType.AROUND_INVOKE, new DummyBinding.Literal(false, true),
            new AnnotationLiteral<UselessBinding>() {
            });
    assertEquals(2, interceptors.size());
    assertEquals(DummyInterceptor.class, interceptors.get(0).getBeanClass());
    assertEquals(LowPriorityInterceptor.class, interceptors.get(1).getBeanClass());
}
 
Example 8
Source Project: deltaspike   Source File: BeanProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@link #getContextualReference(Class, Annotation...)} which returns <code>null</code> if the 'optional' parameter
 * is set to <code>true</code>. This method is intended for usage where the BeanManger is known, e.g. in Extensions.
 *
 * @param beanManager the BeanManager to use
 * @param type        the type of the bean in question
 * @param optional    if <code>true</code> it will return <code>null</code> if no bean could be found or created.
 *                    Otherwise it will throw an {@code IllegalStateException}
 * @param qualifiers  additional qualifiers which further distinct the resolved bean
 * @param <T>         target type
 *
 * @return the resolved Contextual Reference
 *
 * @see #getContextualReference(Class, Annotation...)
 */
public static <T> T getContextualReference(BeanManager beanManager,
                                           Class<T> type,
                                           boolean optional,
                                           Annotation... qualifiers)
{
    Set<Bean<?>> beans = beanManager.getBeans(type, qualifiers);

    if (beans == null || beans.isEmpty())
    {
        if (optional)
        {
            return null;
        }

        throw new IllegalStateException("Could not find beans for Type=" + type
                + " and qualifiers:" + Arrays.toString(qualifiers));
    }

    return getContextualReference(type, beanManager, beans);
}
 
Example 9
@SuppressWarnings("unchecked")
private static <T> T getContextualReference(BeanManager bm, Set<Bean<?>> beans, Class<?> type) {
  if (beans == null || beans.size() == 0) {
    return null;
  }

  // if we would resolve to multiple beans then BeanManager#resolve would throw an AmbiguousResolutionException
  Bean<?> bean = bm.resolve(beans);
  if (bean == null) {
    return null;

  } else {
    CreationalContext<?> creationalContext = bm.createCreationalContext(bean);

    // if we obtain a contextual reference to a @Dependent scope bean, make sure it is released
    if(isDependentScoped(bean)) {
      releaseOnContextClose(creationalContext, bean);
    }

    return (T) bm.getReference(bean, type, creationalContext);

  }
}
 
Example 10
Source Project: deltaspike   Source File: BeanProvider.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> DependentProvider<T> getDependent(BeanManager beanManager, Class<T> type,
                                                    Annotation... qualifiers)
{
    Set<Bean<?>> beans = beanManager.getBeans(type, qualifiers);
    @SuppressWarnings("unchecked")
    Bean<T> bean = (Bean<T>) beanManager.resolve(beans);
    return createDependentProvider(beanManager, type, bean);
}
 
Example 11
Source Project: deltaspike   Source File: ExceptionControlExtension.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies all injection points for every handler are valid.
 *
 * @param afterDeploymentValidation Lifecycle event
 * @param bm  BeanManager instance
 */
@SuppressWarnings("UnusedDeclaration")
public void verifyInjectionPoints(@Observes final AfterDeploymentValidation afterDeploymentValidation,
                                  final BeanManager bm)
{
    if (!isActivated)
    {
        return;
    }

    for (Map.Entry<Type, Collection<HandlerMethod<? extends Throwable>>> entry : allHandlers.entrySet())
    {
        for (HandlerMethod<? extends Throwable> handler : entry.getValue())
        {
            for (InjectionPoint ip : ((HandlerMethodImpl<? extends Throwable>) handler).getInjectionPoints(bm))
            {
                try
                {
                    bm.validate(ip);
                }
                catch (InjectionException e)
                {
                    afterDeploymentValidation.addDeploymentProblem(e);
                }
            }
        }
    }
}
 
Example 12
Source Project: metrics-cdi   Source File: MetricNameFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Produces
// TODO: should be declared @ApplicationScoped when WELD-2083 is fixed
private MetricName metricName(BeanManager manager) {
    try {
        // Cannot be inlined as OWB throws a NPE when manager.getELResolver() gets called
        ExpressionFactory factory = ExpressionFactory.newInstance();
        return new ElMetricName(manager.getELResolver(), manager.wrapExpressionFactory(factory), manager.getExtension(MetricsExtension.class));
    } catch (ELException cause) {
        // Falls back to SE
        return new SeMetricName(manager.getExtension(MetricsExtension.class));
    }
}
 
Example 13
void addBeansFromJava(@Observes final BeforeBeanDiscovery bbd, final BeanManager bm) {
    if (Cxfs.IS_PRESENT) {
        bbd.addInterceptorBinding(JAXRSFieldInjectionInterceptor.Binding.class);

        Stream.of(MeecrowaveBus.class, JAXRSFieldInjectionInterceptor.class)
              .forEach(type -> bbd.addAnnotatedType(bm.createAnnotatedType(type)));
    }
}
 
Example 14
Source Project: dubbox   Source File: SolrRepositoryExtension.java    License: Apache License 2.0 5 votes vote down vote up
private <T> Bean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers,
		BeanManager beanManager) {
	Bean<SolrOperations> solrOperationBeans = this.solrOperationsMap.get(qualifiers.toString());

	if (solrOperationBeans == null) {
		throw new UnsatisfiedResolutionException(
				String.format("Unable to resolve a bean for '%s' with qualifiers %s.",
						SolrOperations.class.getName(), qualifiers));
	}

	return new SolrRepositoryBean<T>(solrOperationBeans, qualifiers, repositoryType, beanManager,
			getCustomImplementationDetector());
}
 
Example 15
Source Project: deltaspike   Source File: ExceptionControlExtension.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Listener to ProcessBean event to locate handlers.
 *
 * @param processBean current {@link AnnotatedType}
 * @param beanManager  Activated Bean Manager
 * @throws TypeNotPresentException if any of the actual type arguments refers to a non-existent type declaration
 *                                 when trying to obtain the actual type arguments from a
 *                                 {@link java.lang.reflect.ParameterizedType}
 * @throws java.lang.reflect.MalformedParameterizedTypeException
 *                                 if any of the actual type parameters refer to a parameterized type that cannot
 *                                 be instantiated for any reason when trying to obtain the actual type arguments
 *                                 from a {@link java.lang.reflect.ParameterizedType}
 */
@SuppressWarnings("UnusedDeclaration")
public <T> void findHandlers(@Observes final ProcessBean<?> processBean, final BeanManager beanManager)
{
    if (!isActivated)
    {
        return;
    }

    if (processBean.getBean() instanceof Interceptor || processBean.getBean() instanceof Decorator ||
            !(processBean.getAnnotated() instanceof AnnotatedType))
    {
        return;
    }

    AnnotatedType annotatedType = (AnnotatedType)processBean.getAnnotated();

    if (annotatedType.getJavaClass().isAnnotationPresent(ExceptionHandler.class))
    {
        final Set<AnnotatedMethod<? super T>> methods = annotatedType.getMethods();

        for (AnnotatedMethod<? super T> method : methods)
        {
            if (HandlerMethodImpl.isHandler(method))
            {
                if (method.getJavaMember().getExceptionTypes().length != 0)
                {
                    processBean.addDefinitionError(new IllegalArgumentException(
                        String.format("Handler method %s must not throw exceptions", method.getJavaMember())));
                }

                //beanManager won't be stored in the instance -> no issue with wls12c
                registerHandlerMethod(new HandlerMethodImpl(processBean.getBean(), method, beanManager));
            }
        }
    }
}
 
Example 16
@Inject
public ConfiguredChannelFactory(@Any Instance<IncomingConnectorFactory> incomingConnectorFactories,
        @Any Instance<OutgoingConnectorFactory> outgoingConnectorFactories,
        Instance<Config> config, @Any Instance<ChannelRegistry> registry,
        BeanManager beanManager) {

    this(incomingConnectorFactories, outgoingConnectorFactories, config, registry, beanManager, true);
}
 
Example 17
Source Project: deltaspike   Source File: CdiTestRunner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void evaluate() throws Throwable
{
    BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager();
    Class<?> type = this.method.getMethod().getDeclaringClass();
    Set<Bean<?>> beans = beanManager.getBeans(type);

    if (!USE_TEST_CLASS_AS_CDI_BEAN || beans == null || beans.isEmpty())
    {
        if (!ALLOW_INJECTION_POINT_MANIPULATION)
        {
            BeanProvider.injectFields(this.originalTarget); //fallback to simple injection
        }
        invokeMethod(this.originalTarget);
    }
    else
    {
        Bean<Object> bean = (Bean<Object>) beanManager.resolve(beans);

        CreationalContext<Object> creationalContext = beanManager.createCreationalContext(bean);

        Object target = beanManager.getReference(bean, type, creationalContext);

        try
        {
            invokeMethod(target);
        }
        finally
        {
            if (bean.getScope().equals(Dependent.class))
            {
                bean.destroy(target, creationalContext);
            }
        }
    }
}
 
Example 18
private List<String> getConnectors(BeanManager beanManager, Class<?> clazz) {
    return beanManager.getBeans(clazz, Any.Literal.INSTANCE).stream()
            .map(BeanAttributes::getQualifiers)
            .flatMap(set -> set.stream().filter(a -> a.annotationType().equals(Connector.class)))
            .map(annotation -> ((Connector) annotation).value())
            .collect(Collectors.toList());
}
 
Example 19
Source Project: deltaspike   Source File: MockAwareProducerWrapper.java    License: Apache License 2.0 5 votes vote down vote up
public MockAwareProducerWrapper(BeanManager beanManager,
                                Producer<T> wrapped,
                                List<Type> beanTypes,
                                List<Annotation> qualifiers)
{
    this.beanManager = beanManager;
    this.wrapped = wrapped;
    this.beanTypes = beanTypes;
    this.qualifiers = qualifiers;
}
 
Example 20
Source Project: tomee   Source File: OpenEJBScripter.java    License: Apache License 2.0 5 votes vote down vote up
public Object beanFromClass(final String appName, final String classname) {
    final AppContext appContext = appContext(appName);
    final BeanManager bm = appContext.getBeanManager();
    final Class<?> clazz;
    try {
        clazz = appContext.getClassLoader().loadClass(classname);
    } catch (final ClassNotFoundException e) {
        throw new OpenEJBRuntimeException(e);
    }
    final Set<Bean<?>> beans = bm.getBeans(clazz);
    return instance(bm, beans, clazz);
}
 
Example 21
Source Project: tomee   Source File: HashServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    final BeanManager bm = HashCdiExtension.BMS.get(tccl);
    // todo: do some lookup
    resp.getWriter().write(Boolean.toString(bm != null));
}
 
Example 22
Source Project: camunda-bpm-platform   Source File: CdiEventListener.java    License: Apache License 2.0 5 votes vote down vote up
protected BeanManager getBeanManager() {
  BeanManager bm = BeanManagerLookup.getBeanManager();
  if (bm == null) {
    throw new ProcessEngineException("No cdi bean manager available, cannot publish event.");
  }
  return bm;
}
 
Example 23
Source Project: deltaspike   Source File: ImmutableInjectionPoint.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Instantiate a new {@link InjectionPoint} based upon an
 * {@link AnnotatedField}, reading the qualifiers from the annotations
 * declared on the field.
 *
 * @param field         the field for which to create the injection point
 * @param declaringBean the declaringBean declaring the injection point
 * @param isTransient   <code>true</code> if the injection point is transient
 * @param delegate      <code>true</code> if the injection point is a delegate
 *                      injection point on a decorator
 */
public ImmutableInjectionPoint(AnnotatedField<?> field, BeanManager beanManager, Bean<?> declaringBean,
                               boolean isTransient, boolean delegate)
{
    annotated = field;
    member = field.getJavaMember();
    qualifiers = BeanUtils.getQualifiers(beanManager, field.getAnnotations());
    type = field.getJavaMember().getGenericType();
    this.isTransient = isTransient;
    this.delegate = delegate;
    this.declaringBean = declaringBean;
}
 
Example 24
Source Project: deltaspike   Source File: PartialBeanBindingExtension.java    License: Apache License 2.0 5 votes vote down vote up
private Class<? extends Annotation> extractScope(Annotation[] annotations, BeanManager beanManager)
{
    for (Annotation annotation : annotations)
    {
        if (beanManager.isScope(annotation.annotationType()))
        {
            return annotation.annotationType();
        }
    }
    return Dependent.class;
}
 
Example 25
Source Project: deltaspike   Source File: BridgeExceptionHandlerWrapper.java    License: Apache License 2.0 5 votes vote down vote up
public BridgeExceptionHandlerWrapper(ExceptionHandler wrapped,
                                     BeanManager beanManager,
                                     Annotation exceptionQualifier)
{
    this.wrapped = wrapped;
    this.beanManager = beanManager;
    this.exceptionQualifier = exceptionQualifier;
}
 
Example 26
Source Project: tomee   Source File: JPAHasBeanManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void doAsserts() {
    assertNotNull(TheTestProvider.MAP);
    final Object bm = TheTestProvider.MAP.get("javax.persistence.bean.manager");
    assertNotNull(bm);
    assertTrue(BeanManager.class.isInstance(bm));
    assertNotNull(em.find(TheTestEntity.class, persisted.getId()));
}
 
Example 27
Source Project: quarkus   Source File: TransactionBeanWithEvents.java    License: Apache License 2.0 5 votes vote down vote up
void transactionScopeActivated(@Observes @Initialized(TransactionScoped.class) final Object event,
        final BeanManager beanManager) throws SystemException {
    Transaction tx = tm.getTransaction();
    if (tx == null) {
        log.error("@Intialized expects an active transaction");
        throw new IllegalStateException("@Intialized expects an active transaction");
    }
    if (tx.getStatus() != Status.STATUS_ACTIVE) {
        log.error("@Initialized expects transaction is Status.STATUS_ACTIVE");
        throw new IllegalStateException("@Initialized expects transaction is Status.STATUS_ACTIVE");
    }
    Context ctx;
    try {
        ctx = beanManager.getContext(TransactionScoped.class);
    } catch (Exception e) {
        log.error("Context on @Initialized is not available");
        throw e;
    }
    if (!ctx.isActive()) {
        log.error("Context on @Initialized has to be active");
        throw new IllegalStateException("Context on @Initialized has to be active");
    }
    if (!(event instanceof Transaction)) {
        log.error("@Intialized scope expects event payload being the " + Transaction.class.getName());
        throw new IllegalStateException("@Intialized scope expects event payload being the " + Transaction.class.getName());
    }

    initializedCount++;
}
 
Example 28
Source Project: joynr   Source File: JoynrIntegrationBean.java    License: Apache License 2.0 5 votes vote down vote up
@Inject
public JoynrIntegrationBean(BeanManager beanManager,
                            JoynrRuntimeFactory joynrRuntimeFactory,
                            ServiceProviderDiscovery serviceProviderDiscovery,
                            CallbackHandlerDiscovery callbackHandlerDiscovery) {
    this.beanManager = beanManager;
    this.joynrRuntimeFactory = joynrRuntimeFactory;
    this.serviceProviderDiscovery = serviceProviderDiscovery;
    this.callbackHandlerDiscovery = callbackHandlerDiscovery;
}
 
Example 29
Source Project: portals-pluto   Source File: RedirectScopedConfig.java    License: Apache License 2.0 5 votes vote down vote up
/** 
 * Gets the concrete contextual for the bean and puts it into the context map.
 * Called after bean discovery during the activation process.
 * Finishes up the configuration process and provides a debug summary.
 * 
 * @param bm      The bean manager
 */
public void activate(BeanManager bm) {
   
   // The assigned render parameters are based on the alphabetic order of the PSS bean 
   // class names, so generate such a list.
   
   for (Class<?> c : class2Anno.keySet()) {
      sortedAnnotatedClassNames.add(c.getCanonicalName());
   }
   Collections.sort(sortedAnnotatedClassNames);
   
   // Activate the beans
   
   for (Class<?> cls : class2Anno.keySet()) {
      Set<Bean<?>> beans = bm.getBeans(cls);
      Bean<?> bean = bm.resolve(beans);
      assert bean != null;
      context2Anno.put(bean, class2Anno.get(cls));
   }
   
   // dump configuration data to trace
   
   if (isTrace) {
      StringBuilder txt = new StringBuilder(128);
      txt.append("RedirectScopedBeanHolder configuration.");
      txt.append(" Annotated Beans: ");
      txt.append(getConfigAsString());
      LOG.debug(txt.toString());
   }
}
 
Example 30
Source Project: cxf   Source File: JAXRSCdiResourceExtension.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create the JAXRSServerFactoryBean from the objects declared by application itself.
 * @param application application instance
 * @return JAXRSServerFactoryBean instance
 */
private JAXRSServerFactoryBean createFactoryInstance(final Application application, final BeanManager beanManager) {
    final JAXRSServerFactoryBean instance =
        ResourceUtils.createApplication(application, false, false, false, bus);
    final ClassifiedClasses classified = classes2singletons(application, beanManager);

    instance.setProviders(classified.getProviders());
    instance.getFeatures().addAll(classified.getFeatures());

    for (final ResourceProvider resourceProvider: classified.getResourceProviders()) {
        instance.setResourceProvider(resourceProvider.getResourceClass(), resourceProvider);
    }

    return instance;
}