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

The following examples show how to use javax.enterprise.inject.spi.BeanManager#createCreationalContext() . 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: CDIInstanceManager.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@Override
public void newInstance(final Object o) throws IllegalAccessException, InvocationTargetException, NamingException {
    if (WebBeansConfigurationListener.class.isInstance(o) || o.getClass().getName().startsWith("org.apache.catalina.servlets.")) {
        return;
    }

    final BeanManager bm = CDI.current().getBeanManager();
    final AnnotatedType<?> annotatedType = bm.createAnnotatedType(o.getClass());
    final InjectionTarget injectionTarget = bm.createInjectionTarget(annotatedType);
    final CreationalContext<Object> creationalContext = bm.createCreationalContext(null);
    injectionTarget.inject(o, creationalContext);
    try {
        injectionTarget.postConstruct(o);
    } catch (final RuntimeException e) {
        creationalContext.release();
        throw e;
    }
    destroyables.put(o, () -> {
        try {
            injectionTarget.preDestroy(o);
        } finally {
            creationalContext.release();
        }
    });
}
 
Example 2
Source File: PushSocket.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
public PushSocket() {
    try {
        // Since @Inject does not work with WebSocket ...
        InitialContext initialContext = new InitialContext();
        BeanManager bm = (BeanManager) initialContext.lookup("java:comp/env/BeanManager");
        Bean bean;
        CreationalContext ctx;

        bean = bm.getBeans(INotificationService.class).iterator().next();
        ctx = bm.createCreationalContext(bean);
        notificationService = (INotificationService) bm.getReference(bean, INotificationService.class, ctx);

        bean = bm.getBeans(ITicketingService.class).iterator().next();
        ctx = bm.createCreationalContext(bean);
        ticketingServices = (ITicketingService) bm.getReference(bean, ITicketingService.class, ctx);

    } catch (NamingException e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: CdiServiceDiscovery.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> List<T> getInstancesByType(Class<T> clazz) {
	BeanManager beanManager = getBeanManager();
	List<T> list = new ArrayList<>();
	if (beanManager != null) {
		Type type = clazz;
		if (clazz == ExceptionMapper.class) {
			TypeLiteral<ExceptionMapper<?>> typeLiteral = new TypeLiteral<ExceptionMapper<?>>() {
			};
			type = typeLiteral.getType();
		}

		Set<Bean<?>> beans = beanManager.getBeans(type);
		for (Bean<?> bean : beans) {
			CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
			T object = (T) beanManager.getReference(bean, type, creationalContext);
			list.add(object);
		}
	}
	return list;
}
 
Example 4
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 5
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 6
Source File: Injector.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
public static CreationalContext<?> inject(final Object testInstance) {
    if (testInstance == null) {
        return null;
    }
    final BeanManager bm = CDI.current().getBeanManager();
    final AnnotatedType<?> annotatedType = bm.createAnnotatedType(testInstance.getClass());
    final InjectionTarget injectionTarget = bm.createInjectionTarget(annotatedType);
    final CreationalContext<?> creationalContext = bm.createCreationalContext(null);
    injectionTarget.inject(testInstance, creationalContext);
    return creationalContext;
}
 
Example 7
Source File: ProgrammaticBeanLookup.java    From flowable-engine 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 8
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 9
Source File: JAXRSCdiResourceExtension.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and collects the CreationalContext instances for future releasing.
 * @param beanManager bean manager instance
 * @param bean bean instance to create CreationalContext for
 * @return CreationalContext instance
 */
private<T> CreationalContext< T > createCreationalContext(final BeanManager beanManager, Bean< T > bean) {
    final CreationalContext< T > creationalContext = beanManager.createCreationalContext(bean);
    
    if (!(bean instanceof DefaultApplicationBean)) {
        synchronized (disposableCreationalContexts) {
            disposableCreationalContexts.add(creationalContext);
        }
    }
    
    return creationalContext;
}
 
Example 10
Source File: RouteExtension.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
HandlerInstance(AnnotatedType<T> annotatedType, BeanManager beanManager) {
    this.annotatedType = annotatedType;
    this.injectionTarget = beanManager.getInjectionTargetFactory(annotatedType).createInjectionTarget(null);
    this.creationalContext = beanManager.createCreationalContext(null);
    this.instance = injectionTarget.produce(creationalContext);
    injectionTarget.inject(instance, creationalContext);
    injectionTarget.postConstruct(instance);
}
 
Example 11
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 12
Source File: OpenEJBLifecycle.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void starts(final BeanManager beanManager, final Class<?> clazz) {
    final Bean<?> bean = beanManager.resolve(beanManager.getBeans(clazz));
    if (!beanManager.isNormalScope(bean.getScope())) {
        throw new IllegalStateException("Only normal scoped beans can use @Startup - likely @ApplicationScoped");
    }

    final CreationalContext<Object> creationalContext = beanManager.createCreationalContext(null);
    beanManager.getReference(bean, clazz, creationalContext).toString();
    // don't release now, will be done by the context - why we restrict it to normal scoped beans
}
 
Example 13
Source File: BeanProvider.java    From datawave with Apache License 2.0 5 votes vote down vote up
/**
 * Perform CDI injection on the non-managed object {@code bean}.
 */
public static void injectFields(Object bean) {
    if (instance == null) {
        throw new IllegalStateException("BeanManager is null. Cannot perform injection.");
    }
    
    BeanManager beanManager = instance.getBeanManager();
    CreationalContext creationalContext = beanManager.createCreationalContext(null);
    AnnotatedType annotatedType = beanManager.createAnnotatedType(bean.getClass());
    InjectionTarget injectionTarget = beanManager.createInjectionTarget(annotatedType);
    // noinspection unchecked
    injectionTarget.inject(bean, creationalContext);
}
 
Example 14
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 15
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 16
Source File: BeanManagerTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetReference() {
    Fool.DESTROYED.set(false);
    Legacy.DESTROYED.set(false);

    BeanManager beanManager = Arc.container().instance(Legacy.class).get().getBeanManager();

    Set<Bean<?>> foolBeans = beanManager.getBeans(Fool.class);
    assertEquals(1, foolBeans.size());
    @SuppressWarnings("unchecked")
    Bean<Fool> foolBean = (Bean<Fool>) foolBeans.iterator().next();
    Fool fool1 = (Fool) beanManager.getReference(foolBean, Fool.class, beanManager.createCreationalContext(foolBean));

    ManagedContext requestContext = Arc.container().requestContext();
    requestContext.activate();
    assertEquals(fool1.getId(),
            ((Fool) beanManager.getReference(foolBean, Fool.class, beanManager.createCreationalContext(foolBean))).getId());
    requestContext.terminate();
    assertTrue(Fool.DESTROYED.get());

    Set<Bean<?>> legacyBeans = beanManager.getBeans(AlternativeLegacy.class);
    assertEquals(1, legacyBeans.size());
    @SuppressWarnings("unchecked")
    Bean<AlternativeLegacy> legacyBean = (Bean<AlternativeLegacy>) legacyBeans.iterator().next();
    CreationalContext<AlternativeLegacy> ctx = beanManager.createCreationalContext(legacyBean);
    Legacy legacy = (Legacy) beanManager.getReference(legacyBean, Legacy.class, ctx);
    assertNotNull(legacy.getBeanManager());
    ctx.release();
    assertTrue(Legacy.DESTROYED.get());
}
 
Example 17
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 18
Source File: ApplicationLifecycleManager.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static void run(Application application, Class<? extends QuarkusApplication> quarkusApplication,
        Consumer<Integer> exitCodeHandler, String... args) {
    stateLock.lock();
    //in tests we might pass this method an already started application
    //in this case we don't shut it down at the end
    boolean alreadyStarted = application.isStarted();
    if (!hooksRegistered) {
        registerHooks();
        hooksRegistered = true;
    }
    if (currentApplication != null && !shutdownRequested) {
        throw new IllegalStateException("Quarkus already running");
    }
    try {
        exitCode = -1;
        shutdownRequested = false;
        currentApplication = application;
    } finally {
        stateLock.unlock();
    }
    try {
        application.start(args);
        //now we are started, we either run the main application or just wait to exit
        if (quarkusApplication != null) {
            BeanManager beanManager = CDI.current().getBeanManager();
            Set<Bean<?>> beans = beanManager.getBeans(quarkusApplication, Any.Literal.INSTANCE);
            Bean<?> bean = null;
            for (Bean<?> i : beans) {
                if (i.getBeanClass() == quarkusApplication) {
                    bean = i;
                    break;
                }
            }
            QuarkusApplication instance;
            if (bean == null) {
                instance = quarkusApplication.newInstance();
            } else {
                CreationalContext<?> ctx = beanManager.createCreationalContext(bean);
                instance = (QuarkusApplication) beanManager.getReference(bean, quarkusApplication, ctx);
            }
            int result = -1;
            try {
                result = instance.run(args);//TODO: argument filtering?
            } finally {
                stateLock.lock();
                try {
                    //now we exit
                    if (exitCode == -1 && result != -1) {
                        exitCode = result;
                    }
                    shutdownRequested = true;
                    stateCond.signalAll();
                } finally {
                    stateLock.unlock();
                }
            }
        } else {
            stateLock.lock();
            try {
                while (!shutdownRequested) {
                    Thread.interrupted();
                    stateCond.await();
                }
            } finally {
                stateLock.unlock();
            }
        }
    } catch (Exception e) {
        Logger.getLogger(Application.class).error("Error running Quarkus application", e);
        stateLock.lock();
        try {
            shutdownRequested = true;
            stateCond.signalAll();
        } finally {
            stateLock.unlock();
        }
        application.stop();
        (exitCodeHandler == null ? defaultExitCodeHandler : exitCodeHandler).accept(1);
        return;
    }
    if (!alreadyStarted) {
        application.stop(); //this could have already been called
    }
    (exitCodeHandler == null ? defaultExitCodeHandler : exitCodeHandler).accept(getExitCode()); //this may not be called if shutdown was initiated by a signal
}
 
Example 19
Source File: CdiUtils.java    From ozark with Apache License 2.0 3 votes vote down vote up
/**
 * Create a new CDI bean given its class and a bean manager. The bean is created
 * in the context defined by the scope annotation on the class.
 *
 * @param bm    The BeanManager.
 * @param clazz CDI class.
 * @param <T>   class parameter.
 * @return newly allocated CDI bean.
 */
public static <T> T newBean(BeanManager bm, Class<T> clazz) {
    Set<Bean<?>> beans = bm.getBeans(clazz);
    final Bean<T> bean = (Bean<T>) bm.resolve(beans);
    final CreationalContext<T> ctx = bm.createCreationalContext(bean);
    return (T) bm.getReference(bean, clazz, ctx);
}
 
Example 20
Source File: CdiUtils.java    From krazo with Apache License 2.0 3 votes vote down vote up
/**
 * Create a new CDI bean given its class and a bean manager. The bean is created
 * in the context defined by the scope annotation on the class.
 *
 * @param bm    The BeanManager.
 * @param clazz CDI class.
 * @param <T>   class parameter.
 * @return newly allocated CDI bean.
 */
public static <T> T newBean(BeanManager bm, Class<T> clazz) {
    Set<Bean<?>> beans = bm.getBeans(clazz);
    final Bean<T> bean = (Bean<T>) bm.resolve(beans);
    final CreationalContext<T> ctx = bm.createCreationalContext(bean);
    return (T) bm.getReference(bean, clazz, ctx);
}