Java Code Examples for javax.enterprise.inject.spi.BeanManager#getReference()

The following examples show how to use javax.enterprise.inject.spi.BeanManager#getReference() . 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 File: ProgrammaticBeanLookup.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: RequestServlet.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private RequestScopedBean getRequestScopedBean()
{
    BeanManager beanManager = CdiContainerLoader.getCdiContainer().getBeanManager();

    if (beanManager == null)
    {
        return null;
    }
    Set<Bean<?>> beans = beanManager.getBeans(RequestScopedBean.class);
    Bean<RequestScopedBean> reqScpdBean = (Bean<RequestScopedBean>) beanManager.resolve(beans);

    CreationalContext<RequestScopedBean> reqScpdCC =
            beanManager.createCreationalContext(reqScpdBean);

    RequestScopedBean instance = (RequestScopedBean)
            beanManager.getReference(reqScpdBean, RequestScopedBean.class, reqScpdCC);
    return instance;
}
 
Example 3
Source File: CdiServiceDiscovery.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Override
public <A extends Annotation> List<Object> getInstancesByAnnotation(Class<A> annotationClass) {
	List<Object> list = new ArrayList<>();
	BeanManager beanManager = getBeanManager();
	if (beanManager != null) {
		Set<Bean<?>> beans = beanManager.getBeans(Object.class);
		for (Bean<?> bean : beans) {
			Class<?> beanClass = bean.getBeanClass();
			Optional<A> annotation = ClassUtils.getAnnotation(beanClass, annotationClass);
			if (annotation.isPresent()) {
				CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
				Object object = beanManager.getReference(bean, beanClass, creationalContext);
				list.add(object);
			}
		}
	}
	return list;
}
 
Example 4
Source File: PortletCDIExtension.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
/**
 * After the bean container has validated the deployment from its point of view,
 * do some checking from the portlet point of view. Activate the portlet deployment
 * by passing in a bean manager in order to create the required portlet bean instances.
 * 
 * @param adv
 * @param bm
 * @throws InvalidAnnotationException
 */
void afterDeploymentValidation(@Observes AfterDeploymentValidation adv, BeanManager bm)
      throws InvalidAnnotationException {
   
   // Done processing the annotations, so put the resulting configuration in an
   // application scoped bean to pass it to the servlet
   
   LOG.trace("Now attempting to get the AnnotatedConfigBean ...");
   Set<Bean<?>> beans = bm.getBeans(AnnotatedConfigBean.class);
   @SuppressWarnings("unchecked")
   Bean<AnnotatedConfigBean> bean = (Bean<AnnotatedConfigBean>) bm.resolve(beans);
   if (bean != null) {
      LOG.trace("Got AnnotatedConfigBean bean: " + bean.getBeanClass().getCanonicalName());
      try {
         CreationalContext<AnnotatedConfigBean> cc = bm.createCreationalContext(bean);
         acb = (AnnotatedConfigBean) bm.getReference(bean, AnnotatedConfigBean.class, cc);
         LOG.trace("Got AnnotatedConfigBean instance.");
         acb.setMethodStore(ams);
         acb.setSummary(summary);
         acb.setRedirectScopedConfig(par.getRedirectScopedConfig());
         acb.setStateScopedConfig(par.getStateScopedConfig());
         acb.setSessionScopedConfig(par.getSessionScopedConfig());
      } catch (Exception e) {
         StringBuilder txt = new StringBuilder(128);
         txt.append("Exception getting AnnotatedConfigBean bean instance: ");
         txt.append(e.toString());
         LOG.warn(txt.toString());
      }
   } else {
      LOG.warn("AnnotatedConfigBean bean was null.");
   }
   LOG.info("Portlet CDI Extension complete. Config bean: " + acb);
}
 
Example 5
Source File: StartWebServer.java    From hammock with Apache License 2.0 5 votes vote down vote up
private WebServer resolveWebServer(BeanManager beanManager) {
    Set<Bean<?>> beans = beanManager.getBeans(WebServer.class);
    if (beans.size() > 1) {
        StringJoiner foundInstances = new StringJoiner(",", "[", "]");
        beans.iterator().forEachRemaining(ws -> foundInstances.add(ws.toString()));
        throw new RuntimeException("Multiple web server implementations found on the classpath " + foundInstances);
    }
    if (beans.isEmpty()) {
        throw new RuntimeException("No web server implementations found on the classpath");
    }
    Bean<?> bean = beanManager.resolve(beans);
    CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
    return (WebServer) beanManager.getReference(bean, WebServer.class, creationalContext);
}
 
Example 6
Source File: ProgrammaticBeanLookup.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T lookup(Class<T> clazz, BeanManager bm) {
    Iterator<Bean<?>> iter = bm.getBeans(clazz).iterator();
    if (!iter.hasNext()) {
        throw new IllegalStateException("CDI BeanManager cannot find an instance of requested type " + clazz.getName());
    }
    Bean<T> bean = (Bean<T>) iter.next();
    CreationalContext<T> ctx = bm.createCreationalContext(bean);
    T dao = (T) bm.getReference(bean, clazz, ctx);
    return dao;
}
 
Example 7
Source File: ClassUnwrapperTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private<T> T getBeanReference(Class<T> clazz) {
    final BeanManager beanManager = lifecycle.getBeanManager();
    final Set<Bean<?>> beans = beanManager.getBeans(clazz);
    final Bean<?> bean = beanManager.resolve(beans);
    return (T)beanManager.getReference(bean, clazz, beanManager.createCreationalContext(bean));
}
 
Example 8
Source File: CarServiceIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T getBean(Class<T> beanClass) {
    BeanManager bm = CDI.current().getBeanManager();
    Bean<T> bean = (Bean<T>) bm.getBeans(beanClass).iterator().next();
    CreationalContext<T> ctx = bm.createCreationalContext(bean);
    return (T) bm.getReference(bean, beanClass, ctx);
}
 
Example 9
Source File: CdiServiceDiscovery.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> List<T> getInstancesByType(Class<T> clazz) {
	BeanManager beanManager = CDI.current().getBeanManager();
	Set<Bean<?>> beans = beanManager.getBeans(clazz);
	List<T> list = new ArrayList<>();
	for (Bean<?> bean : beans) {
		CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
		T object = (T) beanManager.getReference(bean, clazz, creationalContext);
		list.add(object);
	}
	return list;
}
 
Example 10
Source File: BeanProvider.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Internal helper method to resolve the right bean and resolve the contextual reference.
 *
 * @param type the type of the bean in question
 * @param beanManager current bean-manager
 * @param beans beans in question
 * @param <T> target type
 * @return the contextual reference
 */
private static <T> T getContextualReference(Class<T> type, BeanManager beanManager, Set<Bean<?>> beans)
{
    Bean<?> bean = beanManager.resolve(beans);

    logWarningIfDependent(bean);

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

    @SuppressWarnings({ "unchecked", "UnnecessaryLocalVariable" })
    T result = (T) beanManager.getReference(bean, type, creationalContext);
    return result;
}
 
Example 11
Source File: HAAbstractUnitTest.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
protected <T> T getInstance(Type type, Annotation... qualifiers)
{
    BeanManager beanManager = CDI.current().getBeanManager();
    Set<Bean<?>> beans = beanManager.getBeans(type, qualifiers);
    Assert.assertNotNull(beans);

    Bean<?> bean = beanManager.resolve(beans);
    Assert.assertNotNull("Bean with type " + type + " could not be found!", bean);

    return (T) beanManager.getReference(bean, type, beanManager.createCreationalContext(bean));
}
 
Example 12
Source File: DynamicMBeanWrapper.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private synchronized Object instance()
{
    final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(classloader);
    try
    {
        if (instance != null)
        {
            return instance;
        }

        if (normalScope)
        {
            instance = BeanProvider.getContextualReference(clazz, qualifiers);
        }
        else
        {
            final BeanManager bm = BeanManagerProvider.getInstance().getBeanManager();
            final Set<Bean<?>> beans = bm.getBeans(clazz, qualifiers);
            if (beans == null || beans.isEmpty())
            {
                throw new IllegalStateException("Could not find beans for Type=" + clazz
                        + " and qualifiers:" + Arrays.toString(qualifiers));
            }

            final Bean<?> resolvedBean = bm.resolve(beans);
            final CreationalContext<?> creationalContext = bm.createCreationalContext(resolvedBean);
            instance = bm.getReference(resolvedBean, clazz, creationalContext);
            creationalContext.release();
        }
        return instance;
    }
    finally
    {
        Thread.currentThread().setContextClassLoader(oldCl);
    }
}
 
Example 13
Source File: CdiUtilities.java    From cdi with Apache License 2.0 5 votes vote down vote up
public static <T> T getReference(final BeanManager beanManager, final Class<T> clazz) {
    final Set<Bean<?>> beans = beanManager.getBeans(clazz);
    final Bean<?> bean = beanManager.resolve(beans);

    final CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
    return (T) beanManager.getReference(bean, clazz, creationalContext);
}
 
Example 14
Source File: CDIUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Instance<T> findBean(Class<T> clazz, Bus bus) {
    BeanManager beanManager = bus == null ? getCurrentBeanManager() : getCurrentBeanManager(bus);
    Bean<?> bean = beanManager.getBeans(clazz).iterator().next();
    CreationalContext<?> ctx = beanManager.createCreationalContext(bean);
    Instance<T> instance = new Instance<>((T) beanManager.getReference(bean, clazz, ctx), 
        beanManager.isNormalScope(bean.getScope()) ? () -> { } : ctx::release);
    return instance;
}
 
Example 15
Source File: ProgrammaticBeanLookup.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object lookup(String name, BeanManager bm) {
  Set<Bean<?>> beans = bm.getBeans(name);
  if (beans.isEmpty()) {
    throw new IllegalStateException("CDI BeanManager cannot find an instance of requested type '" + name + "'");
  }
  Bean bean = bm.resolve(beans);
  CreationalContext ctx = bm.createCreationalContext(bean);
  // select one beantype randomly. A bean has a non-empty set of
  // beantypes.
  Type type = (Type) bean.getTypes().iterator().next();
  return bm.getReference(bean, type, ctx);
}
 
Example 16
Source File: ProgrammaticBeanLookup.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T lookup(Class<T> clazz, BeanManager bm) {
  Iterator<Bean<?>> iter = bm.getBeans(clazz).iterator();
  if (!iter.hasNext()) {
    throw new IllegalStateException("CDI BeanManager cannot find an instance of requested type " + clazz.getName());
  }
  Bean<T> bean = (Bean<T>) iter.next();
  CreationalContext<T> ctx = bm.createCreationalContext(bean);
  T dao = (T) bm.getReference(bean, clazz, ctx);
  return dao;
}
 
Example 17
Source File: CdiTestRunner.java    From deltaspike with 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
Source File: Authorizer.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
void authorize(final InvocationContext ic, final Object returnValue, BeanManager beanManager)
    throws IllegalAccessException, IllegalArgumentException
{
    if (boundAuthorizerBean == null)
    {
        lazyInitTargetBean(beanManager);
    }

    final CreationalContext<?> creationalContext = beanManager.createCreationalContext(boundAuthorizerBean);

    Object reference = beanManager.getReference(boundAuthorizerBean,
        boundAuthorizerMethod.getJavaMember().getDeclaringClass(), creationalContext);

    Object result = boundAuthorizerMethodProxy.invoke(reference, creationalContext,
            new SecurityParameterValueRedefiner(creationalContext, ic, returnValue));

    if (Boolean.FALSE.equals(result))
    {
        Set<SecurityViolation> violations = new HashSet<SecurityViolation>();
        violations.add(new SecurityViolation()
        {
            private static final long serialVersionUID = 2358753444038521129L;

            @Override
            public String getReason()
            {
                return "Authorization check failed";
            }
        });

        throw new AccessDeniedException(violations);
    }
}
 
Example 19
Source File: ContainerCtrlTckTest.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
@LockedCDIImplementation(versions = {
        @LockedVersionRange(implementation = CdiImplementation.WELD11, versionRange = "[1.1.14,1.2)"),
        @LockedVersionRange(implementation = CdiImplementation.WELD20, versionRange = "[2.0.1.Final,2.1)")
    })
@Test
public void testShutdownWithInactiveContexts()
{
    CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();
    Assert.assertNotNull(cdiContainer);

    cdiContainer.boot();
    cdiContainer.getContextControl().startContexts();

    // now do some random stuff
    BeanManager beanManager = cdiContainer.getBeanManager();
    Assert.assertNotNull(beanManager);

    Set<Bean<?>> beans = beanManager.getBeans(CarRepair.class);
    Bean<?> bean = beanManager.resolve(beans);

    CarRepair carRepair = (CarRepair)
            beanManager.getReference(bean, CarRepair.class, beanManager.createCreationalContext(bean));

    Assert.assertNotNull(carRepair);

    Car car = carRepair.getCar();

    Assert.assertNotNull(car);
    Assert.assertNotNull(car.getUser());


    carRepair.getCar().getUser().setName("tester");
    Assert.assertEquals("tester", car.getUser().getName());

    Assert.assertFalse(CarRepair.isPreDestroyCalled());
    Assert.assertFalse(Car.isPreDestroyCalled());
    Assert.assertFalse(TestUser.isPreDestroyCalled());

    cdiContainer.getContextControl().stopContexts();

    Assert.assertTrue(CarRepair.isPreDestroyCalled());
    Assert.assertTrue(Car.isPreDestroyCalled());
    Assert.assertTrue(TestUser.isPreDestroyCalled());

    cdiContainer.shutdown();
}
 
Example 20
Source File: ContainerCtrlTckTest.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
@Test
public void testParallelThreadExecution() throws Exception
{
    final CdiContainer cc = CdiContainerLoader.getCdiContainer();
    Assert.assertNotNull(cc);

    cc.boot();
    cc.getContextControl().startContexts();

    final BeanManager bm = cc.getBeanManager();
    Assert.assertNotNull(bm);

    final AtomicInteger numErrors = new AtomicInteger(0);
    final ContextControl contextControl = cc.getContextControl();

    Runnable runnable = new Runnable()
    {
        @Override
        public void run()
        {
            try
            {
                contextControl.startContext(SessionScoped.class);
                contextControl.startContext(RequestScoped.class);


                Set<Bean<?>> beans = bm.getBeans(CarRepair.class);
                Bean<?> bean = bm.resolve(beans);

                CarRepair carRepair = (CarRepair)
                        bm.getReference(bean, CarRepair.class, bm.createCreationalContext(bean));
                Assert.assertNotNull(carRepair);

                for (int i = 0; i < 100000; i++)
                {
                    // we need the threads doing something ;)
                    Assert.assertNotNull(carRepair.getCar());
                    Assert.assertNotNull(carRepair.getCar().getUser());
                    Assert.assertNull(carRepair.getCar().getUser().getName());
                }
                contextControl.stopContext(RequestScoped.class);
                contextControl.stopContext(SessionScoped.class);
            }
            catch (Throwable e)
            {
                log.log(Level.SEVERE, "An exception happened on a new worker thread", e);
                numErrors.incrementAndGet();
            }
        }
    };


    Thread[] threads = new Thread[NUM_THREADS];
    for (int i = 0 ; i < NUM_THREADS; i++)
    {
        threads[i] = new Thread(runnable);
    }

    for (int i = 0 ; i < NUM_THREADS; i++)
    {
        threads[i].start();
    }

    for (int i = 0 ; i < NUM_THREADS; i++)
    {
        threads[i].join();
    }

    Assert.assertEquals("An error happened while executing parallel threads", 0, numErrors.get());


    cc.shutdown();
}