javax.enterprise.inject.spi.Bean Java Examples

The following examples show how to use javax.enterprise.inject.spi.Bean. 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: CDIPrototyping.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
@Test
public void appScopedTest() throws Exception {
   assertNotNull(bm);
   
   Set<Bean<?>> beans = bm.getBeans(TestPortlet1AppScoped.class);
   Bean<?> bean = bm.resolve(beans);
   assertNotNull(bean);
   
   CreationalContext<?> coco = bm.createCreationalContext(bean);
   assertNotNull(coco);
   
   Object obj = bm.getReference(bean, TestPortlet1AppScoped.class, coco);
   assertNotNull(obj);
   assertTrue(obj instanceof GenericPortlet);
   assertTrue(obj instanceof Portlet);
   assertTrue(obj instanceof HeaderPortlet);
   assertTrue(obj instanceof EventPortlet);
   assertTrue(obj instanceof ResourceServingPortlet);
   
   Object obj2 = bm.getReference(bean, TestPortlet1AppScoped.class, coco);
   assertNotNull(obj2);
   assertTrue(obj.equals(obj2));
   assertTrue(obj == obj2);
}
 
Example #2
Source File: DolphinPlatformContextualLifecycle.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
@Override
public T create(Bean<T> bean, CreationalContext<T> creationalContext) {
    Assert.requireNonNull(bean, "bean");
    Assert.requireNonNull(creationalContext, "creationalContext");
    if(interceptor == null) {
        throw new ModelInjectionException("No interceptor defined!");
    }
    try {
        T instance = injectionTarget.produce(creationalContext);
        interceptor.intercept(instance);
        injectionTarget.inject(instance, creationalContext);
        injectionTarget.postConstruct(instance);
        return instance;
    } finally {
        interceptor = null;
    }
}
 
Example #3
Source File: WebContextProducer.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
public CDIPortletWebContext(BeanManager beanManager, VariableValidator variableInspector, Models models,
	String lifecyclePhase, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
	ServletContext servletContext, Locale locale) {

	super(httpServletRequest, httpServletResponse, servletContext, locale);
	this.beanManager = beanManager;
	this.models = models;
	this.beanNames = new HashSet<>();

	boolean headerPhase = lifecyclePhase.equals(PortletRequest.HEADER_PHASE);
	boolean renderPhase = lifecyclePhase.equals(PortletRequest.RENDER_PHASE);
	boolean resourcePhase = lifecyclePhase.equals(PortletRequest.RESOURCE_PHASE);

	Set<Bean<?>> beans = beanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {
			});

	for (Bean<?> bean : beans) {
		String beanName = bean.getName();

		if ((beanName != null) &&
				variableInspector.isValidName(beanName, headerPhase, renderPhase, resourcePhase)) {
			this.beanNames.add(beanName);
		}
	}
}
 
Example #4
Source File: CollectedMediatorMetadata.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private MediatorConfiguration createMediatorConfiguration(Method met, Bean<?> bean) {
    DefaultMediatorConfiguration configuration = new DefaultMediatorConfiguration(met, bean);

    Incomings incomings = met.getAnnotation(Incomings.class);
    Incoming incoming = met.getAnnotation(Incoming.class);
    Outgoing outgoing = met.getAnnotation(Outgoing.class);
    Blocking blocking = met.getAnnotation(Blocking.class);
    if (incomings != null) {
        configuration.compute(incomings, outgoing, blocking);
    } else if (incoming != null) {
        configuration.compute(Collections.singletonList(incoming), outgoing, blocking);
    } else {
        configuration.compute(Collections.emptyList(), outgoing, blocking);
    }
    return configuration;
}
 
Example #5
Source File: TomEEOpenAPIExtension.java    From tomee with Apache License 2.0 6 votes vote down vote up
public OpenAPI getOrCreateOpenAPI(final Application application) {
    if (classes != null) {
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        return openapis.computeIfAbsent(application,
                app -> createOpenApi(application.getClass(), classes.stream().map(c -> {
                    try {
                        return loader.loadClass(c);
                    } catch (final ClassNotFoundException e) {
                        throw new IllegalArgumentException(e);
                    }
                })));
    }
    if (packages == null && (!application.getSingletons().isEmpty() || !application.getClasses().isEmpty())) {
        return openapis.computeIfAbsent(application,
                app -> createOpenApi(application.getClass(), Stream.concat(endpoints.stream().map(Bean::getBeanClass),
                        Stream.concat(app.getClasses().stream(), app.getSingletons().stream().map(Object::getClass)))));
    }
    return openapis.computeIfAbsent(application,
            app -> createOpenApi(application.getClass(), endpoints.stream().map(Bean::getBeanClass)));
}
 
Example #6
Source File: SmallRyeHealthReporter.java    From smallrye-health with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> List<T> getHealthGroupsChecks(Class<T> checkClass) {
    Iterator<Bean<?>> iterator = beanManager.getBeans(checkClass, Any.Literal.INSTANCE).iterator();

    List<T> groupHealthChecks = new ArrayList<>();

    while (iterator.hasNext()) {
        Bean<?> bean = iterator.next();
        if (bean.getQualifiers().stream().anyMatch(annotation -> annotation.annotationType().equals(HealthGroup.class))) {
            groupHealthChecks.add((T) beanManager.getReference(bean, bean.getBeanClass(),
                    beanManager.createCreationalContext(bean)));
        }
    }

    return groupHealthChecks;
}
 
Example #7
Source File: DynamoDBRepositoryExtension.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link Bean}.
 * 
 * @param <T>
 *            The type of the repository.
 * @param repositoryType
 *            The class representing the repository.
 * @param beanManager
 *            The BeanManager instance.
 * @return The bean.
 */
private <T> Bean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers, BeanManager beanManager) {

	// Determine the amazondbclient bean which matches the qualifiers of the
	// repository.
	Bean<AmazonDynamoDB> amazonDynamoDBBean = amazonDynamoDBs.get(qualifiers);

	// Determine the dynamo db mapper configbean which matches the
	// qualifiers of the repository.
	Bean<DynamoDBMapperConfig> dynamoDBMapperConfigBean = dbMapperConfigs.get(qualifiers);
	
	if (amazonDynamoDBBean == null) {
		throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.",
				AmazonDynamoDBClient.class.getName(), qualifiers));
	}
	
	Bean<DynamoDBOperations> dynamoDBOperationsBean = dynamoDBOperationss.get(qualifiers);

	
	// Construct and return the repository bean.
	return new DynamoDBRepositoryBean<T>(beanManager, amazonDynamoDBBean, dynamoDBMapperConfigBean,dynamoDBOperationsBean,qualifiers,
			repositoryType);
}
 
Example #8
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 #9
Source File: WebappBeanManager.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public boolean accept(final Bean<?> bean) {
    if (BuiltInOwbBean.class.isInstance(bean) || ExtensionBean.class.isInstance(bean)) {
        return false;
    }
    if (OwbBean.class.isInstance(bean)) {
        final OwbBean owbBean = OwbBean.class.cast(bean);
        if (owbBean.isPassivationCapable())
        {
            if (hasBean(owbBean.getId()))
            {
                return false;
            }
        }
    } else if (PassivationCapable.class.isInstance(bean)) {
        if (hasBean(PassivationCapable.class.cast(bean).getId())) {
            return false;
        }
    }

    final Set<Annotation> qualifiers = bean.getQualifiers();
    return beanManager.getBeans(
            bean.getBeanClass(),
            qualifiers.isEmpty() ? EMPTY_ANNOTATIONS : qualifiers.toArray(new Annotation[qualifiers.size()])).isEmpty();
}
 
Example #10
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 #11
Source File: ConverterAndValidatorProxyExtension.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public <X> void createBeans(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager)
{
    if (!this.isActivated)
    {
        return;
    }

    for (Class<?> originalClass : this.classesToProxy)
    {
        Bean bean = createBean(originalClass, beanManager);

        if (bean != null)
        {
            afterBeanDiscovery.addBean(bean);
        }
    }

    this.classesToProxy.clear();
}
 
Example #12
Source File: MessageHandlingBeanDefinition.java    From cdi with Apache License 2.0 6 votes vote down vote up
static Optional<MessageHandlingBeanDefinition> inspect(Bean<?> bean, Annotated annotated) {
    if (!(annotated instanceof AnnotatedType)) {
        return Optional.empty();
    }
    AnnotatedType at = (AnnotatedType) annotated;
    boolean isEventHandler = CdiUtilities.hasAnnotatedMethod(at, EventHandler.class);
    boolean isQueryHandler = CdiUtilities.hasAnnotatedMethod(at, QueryHandler.class);
    boolean isCommandHandler = CdiUtilities.hasAnnotatedMethod(at, CommandHandler.class);

    if (isEventHandler || isQueryHandler || isCommandHandler) {
        return Optional.of(new MessageHandlingBeanDefinition(bean,
                isEventHandler, isQueryHandler, isCommandHandler));
    }

    return Optional.empty();
}
 
Example #13
Source File: CDIPrototyping.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
@Test
public void beanMgrTest() throws Exception {
   assertNotNull(bm);
   
   Set<Bean<?>> beans = bm.getBeans(TestPortlet1.class);
   Bean<?> bean = bm.resolve(beans);
   assertNotNull(bean);
   
   CreationalContext<?> coco = bm.createCreationalContext(bean);
   assertNotNull(coco);
   
   Object obj = bm.getReference(bean, TestPortlet1.class, coco);
   assertNotNull(obj);
   assertTrue(obj instanceof GenericPortlet);
   assertTrue(obj instanceof Portlet);
   assertTrue(obj instanceof HeaderPortlet);
   assertTrue(obj instanceof EventPortlet);
   assertTrue(obj instanceof ResourceServingPortlet);
   
   Object obj2 = bm.getReference(bean, TestPortlet1.class, coco);
   assertNotNull(obj2);
   assertFalse(obj.equals(obj2));
   assertFalse(obj == obj2);
}
 
Example #14
Source File: BeanProvider.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Get a Contextual Reference by its EL Name.
 * This only works for beans with the &#064;Named annotation.</p>
 *
 * <p><b>Attention:</b> please see the notes on manually resolving &#064;Dependent bean
 * in {@link #getContextualReference(Class, boolean, java.lang.annotation.Annotation...)}!</p>
 *
 *
 * @param beanManager the BeanManager to use
 * @param name the EL name of the bean
 * @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 type the type of the bean in question - use {@link #getContextualReference(String, boolean)}
 *             if the type is unknown e.g. in dyn. use-cases
 * @param <T> target type
 * @return the resolved Contextual Reference
 */
public static <T> T getContextualReference(BeanManager beanManager, String name, boolean optional, Class<T> type)
{
    Set<Bean<?>> beans = beanManager.getBeans(name);

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

        throw new IllegalStateException("Could not find beans for Type=" + type
                + " and name:" + name);
    }

    return getContextualReference(type, beanManager, beans);
}
 
Example #15
Source File: PortletStateScopedBeanHolder.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
/**
 * Remove & destroy all beans. if a response is provided, store the bean state.
 * 
 * @param   resp     The state aware response
 */
protected void removeAll(StateAwareResponse resp) {
   for (Contextual<?> bean : beans.keySet()) {
      if (resp != null) {
         PortletSerializable thisBean = (PortletSerializable) beans.get(bean).instance;
         String[] vals = thisBean.serialize();
         String pn = config.getParamName((Bean<?>) bean);
         resp.getRenderParameters().setValues(pn, vals);
         
         if (isTrace) {
            StringBuilder txt = new StringBuilder(128);
            txt.append("Stored parameter for portlet with namespace: ");
            txt.append(resp.getNamespace());
            txt.append(", paramName: ").append(pn);
            txt.append(", Values: ").append(Arrays.toString(vals));
            LOG.trace(txt.toString());
         }
      }
      remove(bean);
   }
}
 
Example #16
Source File: AddBeanTest.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
static Bean<?> createSequenceBean() {
    return MockBean.<Integer> builder()
            .types(Integer.class)
            .qualifiers(Meaty.Literal.INSTANCE)
            .create(ctx -> SEQUENCE.incrementAndGet())
            .build();
}
 
Example #17
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 #18
Source File: CdiParameterResolverFactory.java    From cdi with Apache License 2.0 5 votes vote down vote up
@Override
public ParameterResolver<?> createInstance(final Executable executable,
        final Parameter[] parameters, final int parameterIndex) {
    final Parameter parameter = parameters[parameterIndex];

    if (this.beanManager == null) {
        logger.error(
                "BeanManager was null. This is a fatal error, an instance of {} {} is not created.",
                parameter.getType(),
                parameter.getAnnotations());
        return null;
    }

    logger.trace("Create instance for {} {}.", parameter.getType(), 
            parameter.getAnnotations());
    
    final Set<Bean<?>> beansFound = beanManager.getBeans(parameter.getType(), 
            parameter.getAnnotations());
    
    if (beansFound.isEmpty()) {
        return null;
    } else if (beansFound.size() > 1) {
        if (logger.isWarnEnabled()) {
            logger.warn("Ambiguous reference for parameter type {} with qualifiers {}.", 
                    parameter.getType().getName(), parameter.getAnnotations());
        }
        
        return null;
    } else {
        return new CdiParameterResolver(beanManager, 
                beansFound.iterator().next(), parameter.getType());
    }
}
 
Example #19
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 #20
Source File: BusinessProcessContext.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> arg1) {

  Bean<T> bean = (Bean<T>) contextual;
  String variableName = bean.getName();

  BusinessProcess businessProcess = getBusinessProcess();
  Object variable = businessProcess.getVariable(variableName);
  if (variable != null) {

    if (logger.isLoggable(Level.FINE)) {
      if(businessProcess.isAssociated()) {        
        logger.fine("Getting instance of bean '" + variableName + "' from Execution[" + businessProcess.getExecutionId() + "].");
      } else {
        logger.fine("Getting instance of bean '" + variableName + "' from transient bean store");
      }
    }

    return (T) variable;
  } else {
    if (logger.isLoggable(Level.FINE)) {
      if(businessProcess.isAssociated()) {        
        logger.fine("Creating instance of bean '" + variableName + "' in business process context representing Execution["
                + businessProcess.getExecutionId() + "].");
      } else {
        logger.fine("Creating instance of bean '" + variableName + "' in transient bean store");
      }
    }

    T beanInstance = bean.create(arg1);
    businessProcess.setVariable(variableName, beanInstance);
    return beanInstance;
  }

}
 
Example #21
Source File: JoynrIntegrationBean.java    From joynr with Apache License 2.0 5 votes vote down vote up
private Set<Class<?>> getServiceProviderInterfaceClasses(Set<Bean<?>> serviceProviderBeans) {
    Set<Class<?>> result = new HashSet<>();
    for (Bean<?> bean : serviceProviderBeans) {
        result.add(bean.getBeanClass().getAnnotation(ServiceProvider.class).serviceInterface());
    }
    return result;
}
 
Example #22
Source File: RestClientCdiTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({"unchecked", "rawTypes"})
public void testCreationalContextsReleasedOnClientClose() throws Exception {
    IMocksControl control = EasyMock.createStrictControl();
    BeanManager mockedBeanMgr = control.createMock(BeanManager.class);
    CreationalContext<?> mockedCreationalCtx = control.createMock(CreationalContext.class);
    Bean<?> mockedBean = control.createMock(Bean.class);
    List<String> stringList = new ArrayList<>(Collections.singleton("abc"));

    EasyMock.expect(mockedBeanMgr.getBeans(List.class))
            .andReturn(Collections.singleton(mockedBean));
    EasyMock.expect(mockedBeanMgr.createCreationalContext(mockedBean))
            .andReturn((CreationalContext) mockedCreationalCtx);
    EasyMock.expect(mockedBeanMgr.getReference(mockedBean, List.class, mockedCreationalCtx))
            .andReturn(stringList);
    EasyMock.expect(mockedBean.getScope())
            .andReturn((Class) ApplicationScoped.class);
    EasyMock.expect(mockedBeanMgr.isNormalScope(ApplicationScoped.class))
            .andReturn(false);
    mockedCreationalCtx.release();
    EasyMock.expectLastCall().once();
    control.replay();

    Bus bus = new ExtensionManagerBus();
    bus.setExtension(mockedBeanMgr, BeanManager.class);

    Instance<List> i = CDIUtils.getInstanceFromCDI(List.class, bus);
    assertEquals(stringList, i.getValue());
    i.release();

    control.verify();
}
 
Example #23
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 #24
Source File: WeldCDIExtension.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
void afterBeandiscovery(@Observes AfterBeanDiscovery event, BeanManager beanManager) {
    if (scopesToActivate != null) {
        for (Class<? extends Annotation> scope : scopesToActivate) {
            ContextImpl ctx = new ContextImpl(scope, beanManager);
            contexts.add(ctx);
            event.addContext(ctx);
        }
    }
    if (beans != null) {
        for (Bean<?> bean : beans) {
            event.addBean(bean);
        }
    }
}
 
Example #25
Source File: ClaimBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
private T getClaimValue(final String name) {
    final Bean<?> bean = bm.resolve(bm.getBeans(Principal.class));
    final Principal principal = Principal.class.cast(bm.getReference(bean, Principal.class, null));

    if (principal == null) {
        logger.fine(String.format("Can't retrieve claim %s. No active principal.", name));
        return null;
    }

    // TomEE sometimes wraps the principal with a proxy so we may have a non null principal even if we aren't authenticated
    // we could merge this test with previous sanity check, but it would make it less readable
    final boolean isProxy = Proxy.isProxyClass(principal.getClass())
            && ManagedSecurityService.PrincipalInvocationHandler.class.isInstance(Proxy.getInvocationHandler(principal));
    if (isProxy) {
        if (!ManagedSecurityService.PrincipalInvocationHandler.class.cast(Proxy.getInvocationHandler(principal)).isLogged()) {
            logger.fine(String.format("Can't retrieve claim %s. No active principal.", name));
            return null;
        }
    }

    JsonWebToken jsonWebToken = null;
    if (!JsonWebToken.class.isInstance(principal)) {
        logger.fine(String.format("Can't retrieve claim %s. Active principal is not a JWT.", name));
        return null;
    }

    jsonWebToken = JsonWebToken.class.cast(principal);

    final Optional<T> claimValue = jsonWebToken.claim(name);
    logger.finest(String.format("Found ClaimValue=%s for name=%s", claimValue, name));
    return claimValue.orElse(null);
}
 
Example #26
Source File: RestClientCdiTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({"unchecked", "rawTypes"})
public void testCreationalContextsNotReleasedOnClientCloseUsingNormalScope() throws Exception {
    IMocksControl control = EasyMock.createStrictControl();
    BeanManager mockedBeanMgr = control.createMock(BeanManager.class);
    CreationalContext<?> mockedCreationalCtx = control.createMock(CreationalContext.class);
    Bean<?> mockedBean = control.createMock(Bean.class);
    List<String> stringList = new ArrayList<>(Collections.singleton("xyz"));

    EasyMock.expect(mockedBeanMgr.getBeans(List.class))
            .andReturn(Collections.singleton(mockedBean));
    EasyMock.expect(mockedBeanMgr.createCreationalContext(mockedBean))
            .andReturn((CreationalContext) mockedCreationalCtx);
    EasyMock.expect(mockedBeanMgr.getReference(mockedBean, List.class, mockedCreationalCtx))
            .andReturn(stringList);
    EasyMock.expect(mockedBean.getScope())
            .andReturn((Class) NormalScope.class);
    EasyMock.expect(mockedBeanMgr.isNormalScope(NormalScope.class))
            .andReturn(true);
    control.replay();

    Bus bus = new ExtensionManagerBus();
    bus.setExtension(mockedBeanMgr, BeanManager.class);

    Instance<List> i = CDIUtils.getInstanceFromCDI(List.class, bus);

    i.release();

    control.verify();
}
 
Example #27
Source File: CdiEjbBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
public CdiEjbBean(final BeanContext bc, final WebBeansContext webBeansContext, final Class beanClass, final AnnotatedType<T> at,
                  final InjectionTargetFactoryImpl<T> factory, final BeanAttributes<T> attributes) {
    super(webBeansContext, toSessionType(bc.getComponentType()), at,
            new EJBBeanAttributesImpl<T>(bc, attributes),
            beanClass, factory);
    this.beanContext = bc;
    bc.set(Bean.class, this);
    passivatingId = bc.getDeploymentID() + getReturnType().getName();

    final boolean stateful = BeanType.STATEFUL.equals(bc.getComponentType());
    final boolean isDependent = getScope().equals(Dependent.class);
    isDependentAndStateful = isDependent && stateful;
    if (webBeansContext.getBeanManagerImpl().isPassivatingScope(getScope()) && stateful) {
        if (!getBeanContext().isPassivable()) {
            throw new DefinitionException(
                    getBeanContext().getBeanClass()
                            + " is a not apssivation-capable @Stateful with a scope "
                            + getScope().getSimpleName() + " which need passivation");
        }
        passivable = true;
    } else {
        passivable = false;
    }
    if (!isDependent) {
        for (final Type type : attributes.getTypes()) {
            if (ParameterizedType.class.isInstance(type)) {
                throw new DefinitionException("Parameterized session bean should be @Dependent: " + beanClass);
            }
        }
    }
    if (getAnnotatedType().isAnnotationPresent(Interceptor.class) || getAnnotatedType().isAnnotationPresent(Decorator.class)) {
        throw new DefinitionException("An EJB can't be an interceptor or a decorator: " + beanClass);
    }
}
 
Example #28
Source File: InterfaceExtension.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager beanManager) throws Exception {

    List<SimpleKey> configuredInterfaces = this.configView.simpleSubkeys(ROOT);

    for (SimpleKey interfaceName : configuredInterfaces) {

        Set<Bean<?>> ifaces = beanManager.getBeans(Interface.class, Any.Literal.INSTANCE);

        if (ifaces
                .stream()
                .noneMatch(e -> e.getQualifiers()
                        .stream()
                        .anyMatch(anno -> anno instanceof Named && ((Named) anno).value().equals(interfaceName + "-interface")))) {

            Interface iface = new Interface(interfaceName.name(), "0.0.0.0");
            applyConfiguration(iface);
            CommonBean<Interface> interfaceBean = CommonBeanBuilder.newBuilder(Interface.class)
                        .beanClass(InterfaceExtension.class)
                        .scope(ApplicationScoped.class)
                        .addQualifier(Any.Literal.INSTANCE)
                        .addQualifier(NamedLiteral.of(interfaceName.name() + "-interface"))
                        .createSupplier(() -> iface)
                        .addType(Interface.class)
                        .addType(Object.class)
                        .build();

            abd.addBean(interfaceBean);
        }
    }
}
 
Example #29
Source File: CdiCamelBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected CamelContext get(String name) {
      BeanManager beanManager = BeanManagerLookup.getBeanManager();
      Set<Bean<?>> beans = beanManager.getBeans(name);
      if(beans.isEmpty())
      	return null;
@SuppressWarnings("unchecked")
      Bean<CamelContext> bean = (Bean<CamelContext>) beans.iterator().next();
      CreationalContext<CamelContext> ctx = beanManager.createCreationalContext(bean);
      return (CamelContext) beanManager.getReference(bean, CamelContext.class, ctx);
  }
 
Example #30
Source File: WebappBeanManager.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Bean<?> getPassivationCapableBean(final String id) {
    final Bean<?> bean = super.getPassivationCapableBean(id);
    if (bean == null && getParentBm() != null) {
        return getParentBm().getPassivationCapableBean(id);
    }
    return bean;
}