javax.enterprise.inject.spi.BeanManager Java Examples
The following examples show how to use
javax.enterprise.inject.spi.BeanManager.
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: BeanManagerTest.java From quarkus with Apache License 2.0 | 6 votes |
@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 #2
Source File: OzarkServletContextListenerTest.java From ozark with Apache License 2.0 | 6 votes |
@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 #3
Source File: SmallRyeJWTAuthCDIExtension.java From smallrye-jwt with Apache License 2.0 | 6 votes |
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 #4
Source File: CdiServiceDiscovery.java From crnk-framework with Apache License 2.0 | 6 votes |
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 File: JtaExtension.java From openwebbeans-meecrowave with Apache License 2.0 | 6 votes |
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
Source File: SubscriptionPublisherInjectionWrapper.java From joynr with Apache License 2.0 | 6 votes |
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 File: AxonCdiExtension.java From cdi with Apache License 2.0 | 6 votes |
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 #8
Source File: ProgrammaticBeanLookup.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@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 #9
Source File: BeanProvider.java From deltaspike with Apache License 2.0 | 6 votes |
/** * {@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 #10
Source File: PartialBeanBindingExtension.java From deltaspike with Apache License 2.0 | 5 votes |
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 #11
Source File: CDIInterceptorWrapperImpl.java From cxf with Apache License 2.0 | 5 votes |
private static List<Annotation> getBindings(Set<Annotation> annotations, BeanManager beanManager) { if (annotations == null || annotations.isEmpty()) { return Collections.emptyList(); } List<Annotation> bindings = new ArrayList<>(); for (Annotation annotation : annotations) { if (beanManager.isInterceptorBinding(annotation.annotationType())) { bindings.add(annotation); } } return bindings; }
Example #12
Source File: ImmutableInjectionPoint.java From deltaspike with Apache License 2.0 | 5 votes |
/** * 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 #13
Source File: CdiEventListener.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
protected BeanManager getBeanManager() { BeanManager bm = BeanManagerLookup.getBeanManager(); if (bm == null) { throw new ProcessEngineException("No cdi bean manager available, cannot publish event."); } return bm; }
Example #14
Source File: HashServlet.java From tomee with Apache License 2.0 | 5 votes |
@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 #15
Source File: OpenEJBScripter.java From tomee with Apache License 2.0 | 5 votes |
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 #16
Source File: DeltaSpikeProxyFactory.java From deltaspike with Apache License 2.0 | 5 votes |
public <T> Class<T> getProxyClass(BeanManager beanManager, Class<T> targetClass) { // check if a proxy is already defined for this class Class<T> proxyClass = resolveAlreadyDefinedProxyClass(targetClass); if (proxyClass == null) { proxyClass = createProxyClass(beanManager, targetClass.getClassLoader(), targetClass); } return proxyClass; }
Example #17
Source File: MockAwareProducerWrapper.java From deltaspike with Apache License 2.0 | 5 votes |
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 #18
Source File: BatchCDIInjectionExtension.java From incubator-batchee with Apache License 2.0 | 5 votes |
private static BeanManager resolveBeanManagerViaJndi() { try { return BeanManager.class.cast(new InitialContext().lookup("java:comp/BeanManager")); } catch (final NamingException e) { return null; } }
Example #19
Source File: ConfiguredChannelFactory.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
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 #20
Source File: DeltaspikeRepositoryTest.java From HotswapAgent with GNU General Public License v2.0 | 5 votes |
@SuppressWarnings("unchecked") public <T> T getBeanInstance(Class<T> beanClass) { BeanManager beanManager = CDI.current().getBeanManager(); Bean<T> bean = (Bean<T>) beanManager.resolve(beanManager.getBeans(beanClass)); T result = beanManager.getContext(bean.getScope()).get(bean, beanManager.createCreationalContext(bean)); return result; }
Example #21
Source File: BridgeExceptionHandlerWrapper.java From deltaspike with Apache License 2.0 | 5 votes |
public BridgeExceptionHandlerWrapper(ExceptionHandler wrapped, BeanManager beanManager, Annotation exceptionQualifier) { this.wrapped = wrapped; this.beanManager = beanManager; this.exceptionQualifier = exceptionQualifier; }
Example #22
Source File: JPAHasBeanManagerTest.java From tomee with Apache License 2.0 | 5 votes |
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 #23
Source File: CdiTestRunner.java From deltaspike with Apache License 2.0 | 5 votes |
@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 #24
Source File: BuiltInBeansAreResolvableTest.java From quarkus with Apache License 2.0 | 5 votes |
@Test public void testBeanManagerBean() { // use dynamic resolution to test it Instance<Object> instance = Arc.container().beanManager().createInstance(); // basic BM is resolvable assertTrue(instance.select(BeanManager.class).isResolvable()); // invoke something on the BM assertEquals(1, instance.select(BeanManager.class).get().getBeans(DummyBean.class).size()); // you shouldn't be able to select BM with qualifiers assertFalse(instance.select(BeanManager.class, new DummyQualifier.Literal()).isResolvable()); }
Example #25
Source File: PortletAnnotationRecognizer.java From portals-pluto with Apache License 2.0 | 5 votes |
/** * To be called by the CDI extension afterDeploymentValidation method to * verify that the stored methods are consistent and to create the bean references. * * @param bm BeanManager needed to activate the beans. * @throws InvalidAnnotationException If the deployment is inconsistent or if the * beans cannot be instantiated. */ @Override protected void activateCustomScopes(BeanManager bm) { // Activate the custom scoped beans redirectScopedConfig.activate(bm); stateScopedConfig.activate(bm); sessionScopedConfig.activate(bm); }
Example #26
Source File: RestClientCdiTest.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testProvidersRegisteredViaMPConfigProperty() throws Exception { Map<String, String> configValues = new HashMap<>(); configValues.put(InterfaceWithoutProvidersDefined.class.getName() + "/mp-rest/providers", HighPriorityClientReqFilter.class.getName() + "," + LowPriorityClientReqFilter.class.getName() + "," + InvokedMethodClientRequestFilter.class.getName()); configValues.put(InterfaceWithoutProvidersDefined.class.getName() + "/mp-rest/providers/" + LowPriorityClientReqFilter.class.getName() + "/priority", "3"); ((MockConfigProviderResolver)ConfigProviderResolver.instance()).setConfigValues(configValues); IMocksControl control = EasyMock.createNiceControl(); BeanManager mockedBeanMgr = control.createMock(BeanManager.class); mockedBeanMgr.isScope(Path.class); EasyMock.expectLastCall().andReturn(false); mockedBeanMgr.isScope(Produces.class); EasyMock.expectLastCall().andReturn(false); mockedBeanMgr.isScope(Consumes.class); EasyMock.expectLastCall().andReturn(false); control.replay(); RestClientBean bean = new RestClientBean(InterfaceWithoutProvidersDefined.class, mockedBeanMgr); List<Class<?>> registeredProviders = bean.getConfiguredProviders(); assertEquals(3, registeredProviders.size()); assertTrue(registeredProviders.contains(HighPriorityClientReqFilter.class)); assertTrue(registeredProviders.contains(LowPriorityClientReqFilter.class)); assertTrue(registeredProviders.contains(InvokedMethodClientRequestFilter.class)); Map<Class<?>, Integer> priorities = bean.getConfiguredProviderPriorities(registeredProviders); assertEquals(3, priorities.size()); assertEquals(3, (int) priorities.get(LowPriorityClientReqFilter.class)); assertEquals(10, (int) priorities.get(HighPriorityClientReqFilter.class)); assertEquals(Priorities.USER, (int) priorities.get(InvokedMethodClientRequestFilter.class)); control.verify(); }
Example #27
Source File: JAXRSCdiResourceExtension.java From cxf with Apache License 2.0 | 5 votes |
/** * 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; }
Example #28
Source File: TransactionBeanWithEvents.java From quarkus with Apache License 2.0 | 5 votes |
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 #29
Source File: JoynrIntegrationBean.java From joynr with Apache License 2.0 | 5 votes |
@Inject public JoynrIntegrationBean(BeanManager beanManager, JoynrRuntimeFactory joynrRuntimeFactory, ServiceProviderDiscovery serviceProviderDiscovery, CallbackHandlerDiscovery callbackHandlerDiscovery) { this.beanManager = beanManager; this.joynrRuntimeFactory = joynrRuntimeFactory; this.serviceProviderDiscovery = serviceProviderDiscovery; this.callbackHandlerDiscovery = callbackHandlerDiscovery; }
Example #30
Source File: RedirectScopedConfig.java From portals-pluto with Apache License 2.0 | 5 votes |
/** * 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()); } }