Java Code Examples for javax.enterprise.inject.spi.Bean#getBeanClass()

The following examples show how to use javax.enterprise.inject.spi.Bean#getBeanClass() . 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: 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 2
Source File: CdiServiceDiscovery.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Override
public <A extends Annotation> List<Object> getInstancesByAnnotation(Class<A> annotationClass) {
	BeanManager beanManager = CDI.current().getBeanManager();
	Set<Bean<?>> beans = beanManager.getBeans(Object.class);
	List<Object> list = new ArrayList<>();
	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 3
Source File: AuthorizationProcessingFilter.java    From oxTrust with MIT License 6 votes vote down vote up
/**
 * Builds a map around url patterns and service beans that are aimed to perform
 * actual protection
 */
@SuppressWarnings("unchecked")
@PostConstruct
private void init() {
	protectionMapping = new HashMap<String, Class<BaseUmaProtectionService>>();
	Set<Bean<?>> beans = beanManager.getBeans(BaseUmaProtectionService.class, Any.Literal.INSTANCE);
	
	for (Bean bean : beans) {
		Class beanClass = bean.getBeanClass();
		Annotation beanAnnotation = beanClass.getAnnotation(BindingUrls.class);
		if (beanAnnotation != null) {
			for (String pattern : ((BindingUrls) beanAnnotation).value()) {
				if (pattern.length() > 0) {
					protectionMapping.put(pattern, beanClass);
				}
			}
		}
	}
}
 
Example 4
Source File: ImmutableBeanWrapper.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate a new {@link ImmutableBeanWrapper}.
 *
 * @param bean        the bean to wrapped the lifecycle to
 * @param name        the name of the bean
 * @param qualifiers  the qualifiers of the bean
 * @param scope       the scope of the bean
 * @param stereotypes the bean's stereotypes
 * @param types       the types of the bean
 * @param alternative whether the bean is an alternative
 * @param nullable    true if the bean is nullable
 * @param toString    the string which should be returned by #{@link #toString()}
 */
public ImmutableBeanWrapper(Bean<T> bean,
                            String name,
                            Set<Annotation> qualifiers,
                            Class<? extends Annotation> scope,
                            Set<Class<? extends Annotation>> stereotypes,
                            Set<Type> types,
                            boolean alternative,
                            boolean nullable,
                            String toString)
{
    super(bean.getBeanClass(), name, qualifiers, scope, stereotypes,
            types, alternative, nullable, bean.getInjectionPoints(), toString);

    wrapped = bean;
}
 
Example 5
Source File: CDIBatchArtifactFactory.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
@Override
public Instance load(final String batchId) {
    final BeanManager bm = getBeanManager();
    if (bm == null) {
        return super.load(batchId);
    }

    final Set<Bean<?>> beans = bm.getBeans(batchId);
    final Bean<?> bean = bm.resolve(beans);
    if (bean == null) { // fallback to try to instantiate it from TCCL as per the spec
        return super.load(batchId);
    }
    final Class<?> clazz = bean.getBeanClass();
    final CreationalContext creationalContext = bm.createCreationalContext(bean);
    final Object artifactInstance = bm.getReference(bean, clazz, creationalContext);
    if (Dependent.class.equals(bean.getScope()) || !bm.isNormalScope(bean.getScope())) { // need to be released
        return new Instance(artifactInstance, new Closeable() {
            @Override
            public void close() throws IOException {
                creationalContext.release();
            }
        });
    }
    return new Instance(artifactInstance, null);
}
 
Example 6
Source File: HessianExtension.java    From tomee with Apache License 2.0 6 votes vote down vote up
protected <X> void findHessianWebServices(final @Observes ProcessBean<X> processBean) {
    if (ProcessSessionBean.class.isInstance(processBean)) {
        return;
    }

    final Bean<X> bean = processBean.getBean();
    final Class<?> beanClass = bean.getBeanClass();
    for (final Class<?> itf : beanClass.getInterfaces()) {
        final Hessian hessian = itf.getAnnotation(Hessian.class);
        final String key = "openejb.hessian." + beanClass.getName() + "_" + itf.getName() + ".path";
        final String path = appInfo.properties.getProperty(key, SystemInstance.get().getProperty(key));
        if (hessian != null || path != null) {
            toDeploy.add(new Deployment(itf, path, bean));
        }
    }
}
 
Example 7
Source File: SubscriptionPublisherInjectionWrapper.java    From joynr with Apache License 2.0 6 votes vote down vote up
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 8
Source File: ConversationUtils.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
public static ConversationKey convertToConversationKey(Contextual<?> contextual, BeanManager beanManager)
{
    if (!(contextual instanceof Bean))
    {
        if (contextual instanceof PassivationCapable)
        {
            contextual = beanManager.getPassivationCapableBean(((PassivationCapable) contextual).getId());
        }
        else
        {
            throw new IllegalArgumentException(
                contextual.getClass().getName() + " is not of type " + Bean.class.getName());
        }
    }

    Bean<?> bean = (Bean<?>) contextual;

    //don't cache it (due to the support of different producers)
    ConversationGroup conversationGroupAnnotation = findConversationGroupAnnotation(bean);

    Class<?> conversationGroup;
    if (conversationGroupAnnotation != null)
    {
        conversationGroup = conversationGroupAnnotation.value();
    }
    else
    {
        conversationGroup = bean.getBeanClass();
    }

    Set<Annotation> qualifiers = bean.getQualifiers();
    return new ConversationKey(conversationGroup, qualifiers.toArray(new Annotation[qualifiers.size()]));
}
 
Example 9
Source File: BeanProvider.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
public static <T> DependentProvider<T> getDependent(BeanManager beanManager, String name)
{
    Set<Bean<?>> beans = beanManager.getBeans(name);
    @SuppressWarnings("unchecked")
    Bean<T> bean = (Bean<T>) beanManager.resolve(beans);
    @SuppressWarnings("unchecked")
    Class<T> beanClass = (Class<T>) bean.getBeanClass();

    return createDependentProvider(beanManager, beanClass, bean);
}
 
Example 10
Source File: WebappWebBeansContext.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public boolean findMissingAnnotatedType(final Class<?> missing) {
    // annotated element caches are empty at this point
    for (final Bean<?> b : getParent().getBeanManagerImpl().getBeans()) {
        if (b.getBeanClass() == missing) {
            return true;
        }
    }
    return false;
}
 
Example 11
Source File: RepositoryRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private static <T> Bean<T> resolve(BeanManager beanManager, Class<T> beanClass) {
    Set<Bean<?>> beans = beanManager.getBeans(beanClass);

    for (Bean<?> bean : beans) {
        if (bean.getBeanClass() == beanClass) {
            return (Bean<T>) beanManager.resolve(Collections.<Bean<?>> singleton(bean));
        }
    }
    return (Bean<T>) beanManager.resolve(beans);
}
 
Example 12
Source File: HaCdiCommons.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
public static boolean isInExtraScope(Bean<?> bean) {
    Class<?> beanClass = bean.getBeanClass();
    for (HaCdiExtraContext extraContext: extraContexts.keySet()) {
        if (extraContext.containsBeanInstances(beanClass)) {
            return true;
        }
    }
    return false;
}
 
Example 13
Source File: JAXRSCdiResourceExtension.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * JAX-RS application has defined singletons as being classes of any providers, resources and features.
 * In the JAXRSServerFactoryBean, those should be split around several method calls depending on instance
 * type. At the moment, only the Feature is CXF-specific and should be replaced by JAX-RS Feature implementation.
 * @param application the application instance
 * @return classified instances of classes by instance types
 */
private ClassifiedClasses classes2singletons(final Application application, final BeanManager beanManager) {
    final ClassifiedClasses classified = new ClassifiedClasses();

    // now loop through the classes
    Set<Class<?>> classes = application.getClasses();
    if (!classes.isEmpty()) {
        classified.addProviders(loadProviders(beanManager, classes));
        classified.addFeatures(loadFeatures(beanManager, classes));

        for (final Bean< ? > bean: serviceBeans) {
            if (classes.contains(bean.getBeanClass())) {
                // normal scoped beans will return us a proxy in getInstance so it is singletons for us,
                // @Singleton is indeed a singleton
                // @Dependent should be a request scoped instance but for backward compat we kept it a singleton
                //
                // other scopes are considered request scoped (for jaxrs)
                // and are created per request (getInstance/releaseInstance)
                final ResourceProvider resourceProvider;
                if (isCxfSingleton(beanManager, bean)) {
                    final Lifecycle lifecycle = new Lifecycle(beanManager, bean);
                    resourceProvider = new SingletonResourceProvider(lifecycle, bean.getBeanClass());

                    // if not a singleton we manage it per request
                    // if @Singleton the container handles it
                    // so we only need this case here
                    if (Dependent.class == bean.getScope()) {
                        disposableLifecycles.add(lifecycle);
                    }
                } else {
                    resourceProvider = new PerRequestResourceProvider(
                    () -> new Lifecycle(beanManager, bean), bean.getBeanClass());
                }
                classified.addResourceProvider(resourceProvider);
            }
        }
    }

    return classified;
}
 
Example 14
Source File: JoynrIntegrationBean.java    From joynr with Apache License 2.0 4 votes vote down vote up
private void registerProviders(Set<Bean<?>> serviceProviderBeans, JoynrRuntime runtime) {
    Set<ProviderRegistrationSettingsFactory> providerSettingsFactories = getProviderRegistrationSettingsFactories();

    for (Bean<?> bean : serviceProviderBeans) {
        Class<?> beanClass = bean.getBeanClass();
        Class<?> serviceInterface = beanClass.getAnnotation(ServiceProvider.class).serviceInterface();
        Class<?> providerInterface = serviceProviderDiscovery.getProviderInterfaceFor(serviceInterface);
        if (logger.isDebugEnabled()) {
            logger.debug(format("Registering in joynr runtime the bean %s as provider %s for service %s.",
                                bean,
                                providerInterface,
                                serviceInterface));
        }
        JoynrProvider provider = (JoynrProvider) Proxy.newProxyInstance(beanClass.getClassLoader(),
                                                                        new Class<?>[]{ providerInterface,
                                                                                JoynrProvider.class },
                                                                        new ProviderWrapper(bean,
                                                                                            beanManager,
                                                                                            joynrRuntimeFactory.getInjector()));

        // try to find customized settings for the registration
        ProviderQos providerQos = null;
        String[] gbids = null;

        for (ProviderRegistrationSettingsFactory factory : providerSettingsFactories) {
            if (factory.providesFor(serviceInterface)) {
                providerQos = factory.createProviderQos();
                gbids = factory.createGbids();
                break;
            }
        }

        if (providerQos == null) {
            providerQos = new ProviderQos();
        }

        if (gbids == null) {
            // empty array for default registration (i.e. in default backend)
            gbids = new String[0];
        }

        runtime.getProviderRegistrar(getDomainForProvider(beanClass), provider)
               .withProviderQos(providerQos)
               .withGbids(gbids)
               .register();

        registeredProviders.add(provider);
    }
}
 
Example 15
Source File: PartialBeanBindingExtension.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
protected List<Bean> createPartialProducersDefinedIn(
    Bean partialBean, AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager)
{
    Class currentClass = partialBean.getBeanClass();
    return createPartialProducersDefinedIn(partialBean, afterBeanDiscovery, beanManager, currentClass);
}
 
Example 16
Source File: PartialBeanBindingExtension.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
private List<Bean> createPartialProducersDefinedIn(
    Bean partialBean, AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager, Class currentClass)
{
    List<Bean> result = new ArrayList<Bean>();

    while (currentClass != null && !Object.class.getName().equals(currentClass.getName()))
    {
        for (Class interfaceClass : currentClass.getInterfaces())
        {
            if (interfaceClass.getName().startsWith("java.") || interfaceClass.getName().startsWith("javax."))
            {
                continue;
            }
            result.addAll(
                createPartialProducersDefinedIn(partialBean, afterBeanDiscovery, beanManager, interfaceClass));
        }

        for (Method currentMethod : currentClass.getDeclaredMethods())
        {
            if (currentMethod.isAnnotationPresent(Produces.class))
            {
                if (currentMethod.getParameterTypes().length > 0)
                {
                    afterBeanDiscovery.addDefinitionError(
                        new IllegalStateException(
                            "Producer-methods in partial-beans currently don't support injection-points. " +
                            "Please remove the parameters from " +
                            currentMethod.toString() + " in " + currentClass.getName()));
                }

                DeltaSpikePartialProducerLifecycle lifecycle =
                    new DeltaSpikePartialProducerLifecycle(partialBean.getBeanClass(), currentMethod);

                Class<? extends Annotation> scopeClass =
                    extractScope(currentMethod.getDeclaredAnnotations(), beanManager);

                Class<?> producerResultType = currentMethod.getReturnType();

                boolean passivationCapable =
                    Serializable.class.isAssignableFrom(producerResultType) || producerResultType.isPrimitive();

                Set<Annotation> qualifiers = extractQualifiers(currentMethod.getDeclaredAnnotations(), beanManager);

                BeanBuilder<?> beanBuilder = new BeanBuilder(beanManager)
                        .beanClass(producerResultType)
                        .types(Object.class, producerResultType)
                        .qualifiers(qualifiers)
                        .passivationCapable(passivationCapable)
                        .scope(scopeClass)
                        .id(createPartialProducerId(currentClass, currentMethod, qualifiers))
                        .beanLifecycle(lifecycle);

                result.add(beanBuilder.create());
            }
        }

        currentClass = currentClass.getSuperclass();
    }

    return result;
}
 
Example 17
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
}