Search in sources :

Example 1 with BeanManagerImpl

use of org.apache.webbeans.container.BeanManagerImpl in project tomee by apache.

the class CxfRSService method contextCDIIntegration.

private void contextCDIIntegration(final WebBeansContext wbc) {
    if (!enabled) {
        return;
    }
    final BeanManagerImpl beanManagerImpl = wbc.getBeanManagerImpl();
    if (!beanManagerImpl.getAdditionalQualifiers().contains(Context.class)) {
        beanManagerImpl.addAdditionalQualifier(Context.class);
    }
    if (!hasBean(beanManagerImpl, SecurityContext.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(SecurityContext.class, ThreadLocalContextManager.SECURITY_CONTEXT));
    }
    if (!hasBean(beanManagerImpl, UriInfo.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(UriInfo.class, ThreadLocalContextManager.URI_INFO));
    }
    if (!hasBean(beanManagerImpl, HttpServletResponse.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(HttpServletResponse.class, ThreadLocalContextManager.HTTP_SERVLET_RESPONSE));
    }
    if (!hasBean(beanManagerImpl, HttpHeaders.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(HttpHeaders.class, ThreadLocalContextManager.HTTP_HEADERS));
    }
    if (!hasBean(beanManagerImpl, Request.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(Request.class, ThreadLocalContextManager.REQUEST));
    }
    if (!hasBean(beanManagerImpl, ServletConfig.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ServletConfig.class, ThreadLocalContextManager.SERVLET_CONFIG));
    }
    if (!hasBean(beanManagerImpl, Providers.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(Providers.class, ThreadLocalContextManager.PROVIDERS));
    }
    if (!hasBean(beanManagerImpl, ContextResolver.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ContextResolver.class, ThreadLocalContextManager.CONTEXT_RESOLVER));
    }
    if (!hasBean(beanManagerImpl, ResourceInfo.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ResourceInfo.class, ThreadLocalContextManager.RESOURCE_INFO));
    }
    if (!hasBean(beanManagerImpl, ResourceContext.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ResourceContext.class, ThreadLocalContextManager.RESOURCE_CONTEXT));
    }
    if (!hasBean(beanManagerImpl, HttpServletRequest.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(HttpServletRequest.class, ThreadLocalContextManager.HTTP_SERVLET_REQUEST));
    }
    if (!hasBean(beanManagerImpl, ServletRequest.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ServletRequest.class, ThreadLocalContextManager.SERVLET_REQUEST));
    }
    if (!hasBean(beanManagerImpl, ServletContext.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ServletContext.class, ThreadLocalContextManager.SERVLET_CONTEXT));
    }
    // hasBean() usage can have cached several things
    beanManagerImpl.getInjectionResolver().clearCaches();
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) Context(javax.ws.rs.core.Context) WebBeansContext(org.apache.webbeans.config.WebBeansContext) CreationalContext(javax.enterprise.context.spi.CreationalContext) ResourceContext(javax.ws.rs.container.ResourceContext) ServletContext(javax.servlet.ServletContext) HttpHeaders(javax.ws.rs.core.HttpHeaders) ResourceInfo(javax.ws.rs.container.ResourceInfo) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ResourceContext(javax.ws.rs.container.ResourceContext) Request(javax.ws.rs.core.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ServletConfig(javax.servlet.ServletConfig) HttpServletResponse(javax.servlet.http.HttpServletResponse) Providers(javax.ws.rs.ext.Providers) HttpServletRequest(javax.servlet.http.HttpServletRequest) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) SecurityContext(javax.ws.rs.core.SecurityContext) ServletContext(javax.servlet.ServletContext) ContextResolver(javax.ws.rs.ext.ContextResolver) UriInfo(javax.ws.rs.core.UriInfo)

Example 2 with BeanManagerImpl

use of org.apache.webbeans.container.BeanManagerImpl in project tomee by apache.

the class Assembler method postConstructResources.

private void postConstructResources(final Set<String> resourceIds, final ClassLoader classLoader, final Context containerSystemContext, final AppContext appContext) throws NamingException, OpenEJBException {
    final Thread thread = Thread.currentThread();
    final ClassLoader oldCl = thread.getContextClassLoader();
    try {
        thread.setContextClassLoader(classLoader);
        final List<ResourceInfo> resourceList = config.facilities.resources;
        for (final ResourceInfo resourceInfo : resourceList) {
            if (!resourceIds.contains(resourceInfo.id)) {
                continue;
            }
            if (isTemplatizedResource(resourceInfo)) {
                continue;
            }
            try {
                Class<?> clazz;
                try {
                    clazz = classLoader.loadClass(resourceInfo.className);
                } catch (final ClassNotFoundException cnfe) {
                    // custom classpath
                    clazz = containerSystemContext.lookup(OPENEJB_RESOURCE_JNDI_PREFIX + resourceInfo.id).getClass();
                }
                final boolean initialize = "true".equalsIgnoreCase(String.valueOf(resourceInfo.properties.remove("InitializeAfterDeployment")));
                final AnnotationFinder finder = Proxy.isProxyClass(clazz) ? null : new AnnotationFinder(new ClassesArchive(ancestors(clazz)));
                final List<Method> postConstructs = finder == null ? Collections.<Method>emptyList() : finder.findAnnotatedMethods(PostConstruct.class);
                final List<Method> preDestroys = finder == null ? Collections.<Method>emptyList() : finder.findAnnotatedMethods(PreDestroy.class);
                resourceInfo.postConstructMethods = new ArrayList<>();
                resourceInfo.preDestroyMethods = new ArrayList<>();
                addMethodsToResourceInfo(resourceInfo.postConstructMethods, PostConstruct.class, postConstructs);
                addMethodsToResourceInfo(resourceInfo.preDestroyMethods, PreDestroy.class, preDestroys);
                CreationalContext<?> creationalContext = null;
                Object originalResource = null;
                if (!postConstructs.isEmpty() || initialize) {
                    originalResource = containerSystemContext.lookup(OPENEJB_RESOURCE_JNDI_PREFIX + resourceInfo.id);
                    Object resource = originalResource;
                    if (resource instanceof Reference) {
                        resource = unwrapReference(resource);
                        this.bindResource(resourceInfo.id, resource, true);
                    }
                    try {
                        // wire up CDI
                        if (appContext != null && appContext.getWebBeansContext() != null) {
                            final BeanManagerImpl beanManager = appContext.getWebBeansContext().getBeanManagerImpl();
                            if (beanManager.isInUse()) {
                                creationalContext = beanManager.createCreationalContext(null);
                                OWBInjector.inject(beanManager, resource, creationalContext);
                            }
                        }
                        if (!"none".equals(resourceInfo.postConstruct)) {
                            if (resourceInfo.postConstruct != null) {
                                final Method p = clazz.getDeclaredMethod(resourceInfo.postConstruct);
                                if (!p.isAccessible()) {
                                    SetAccessible.on(p);
                                }
                                p.invoke(resource);
                            }
                            for (final Method m : postConstructs) {
                                if (!m.isAccessible()) {
                                    SetAccessible.on(m);
                                }
                                m.invoke(resource);
                            }
                        }
                    } catch (final Exception e) {
                        logger.fatal("Error calling @PostConstruct method on " + resource.getClass().getName());
                        throw new OpenEJBException(e);
                    }
                }
                if (!"none".equals(resourceInfo.preDestroy)) {
                    if (resourceInfo.preDestroy != null) {
                        final Method p = clazz.getDeclaredMethod(resourceInfo.preDestroy);
                        if (!p.isAccessible()) {
                            SetAccessible.on(p);
                        }
                        preDestroys.add(p);
                    }
                    if (!preDestroys.isEmpty() || creationalContext != null) {
                        final String name = OPENEJB_RESOURCE_JNDI_PREFIX + resourceInfo.id;
                        if (originalResource == null) {
                            originalResource = containerSystemContext.lookup(name);
                        }
                        this.bindResource(resourceInfo.id, new ResourceInstance(name, originalResource, preDestroys, creationalContext), true);
                    }
                }
                // log unused now for these resources now we built the resource completely and @PostConstruct can have used injected properties
                if (resourceInfo.unsetProperties != null && !isPassthroughType(resourceInfo)) {
                    final Set<String> unsetKeys = resourceInfo.unsetProperties.stringPropertyNames();
                    for (final String key : unsetKeys) {
                        // don't use keySet to auto filter txMgr for instance and not real properties!
                        unusedProperty(resourceInfo.id, logger, key);
                    }
                }
            } catch (final Exception e) {
                logger.fatal("Error calling PostConstruct method on " + resourceInfo.id);
                logger.fatal("Resource " + resourceInfo.id + " could not be initialized. Application will be undeployed.");
                throw new OpenEJBException(e);
            }
        }
    } finally {
        thread.setContextClassLoader(oldCl);
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) ConnectorReference(org.apache.openejb.core.ConnectorReference) ContextualJndiReference(org.apache.openejb.core.ivm.naming.ContextualJndiReference) JndiUrlReference(org.apache.openejb.core.ivm.naming.JndiUrlReference) Reference(org.apache.openejb.core.ivm.naming.Reference) ResourceReference(org.apache.webbeans.spi.api.ResourceReference) LazyObjectReference(org.apache.openejb.core.ivm.naming.LazyObjectReference) AtomicReference(java.util.concurrent.atomic.AtomicReference) Method(java.lang.reflect.Method) InvalidObjectException(java.io.InvalidObjectException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ObjectStreamException(java.io.ObjectStreamException) ResourceAdapterInternalException(javax.resource.spi.ResourceAdapterInternalException) URISyntaxException(java.net.URISyntaxException) UndeployException(org.apache.openejb.UndeployException) DefinitionException(javax.enterprise.inject.spi.DefinitionException) ConstructionException(org.apache.xbean.recipe.ConstructionException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ValidationException(javax.validation.ValidationException) MalformedObjectNameException(javax.management.MalformedObjectNameException) DuplicateDeploymentIdException(org.apache.openejb.DuplicateDeploymentIdException) TimeoutException(java.util.concurrent.TimeoutException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) DeploymentException(javax.enterprise.inject.spi.DeploymentException) NoSuchApplicationException(org.apache.openejb.NoSuchApplicationException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) ClassesArchive(org.apache.xbean.finder.archive.ClassesArchive) ContainerSystemPreDestroy(org.apache.openejb.assembler.classic.event.ContainerSystemPreDestroy) PreDestroy(javax.annotation.PreDestroy) PostConstruct(javax.annotation.PostConstruct) AnnotationFinder(org.apache.xbean.finder.AnnotationFinder)

Example 3 with BeanManagerImpl

use of org.apache.webbeans.container.BeanManagerImpl in project tomee by apache.

the class CdiPlugin method defineSessionBean.

@Override
public <T> Bean<T> defineSessionBean(final Class<T> clazz, final BeanAttributes<T> attributes, final AnnotatedType<T> annotatedType) {
    final BeanContext bc = findBeanContext(webBeansContext, clazz);
    final Class<?> superClass = bc.getManagedClass().getSuperclass();
    if (annotatedType.isAnnotationPresent(Specializes.class)) {
        if (superClass != Object.class && !isSessionBean(superClass)) {
            throw new DefinitionException("You can only specialize another EJB: " + clazz);
        }
        final BeanContext parentBc = findBeanContext(webBeansContext, superClass);
        final List<Class> businessLocalInterfaces = new ArrayList<>(parentBc.getBusinessLocalInterfaces());
        for (final Class<?> api : bc.getBusinessLocalInterfaces()) {
            businessLocalInterfaces.removeAll(GenericsUtil.getTypeClosure(api));
        }
        if (!businessLocalInterfaces.isEmpty()) {
            throw new DefinitionException("You can only specialize another EJB with at least the same API: " + clazz);
        }
    }
    final CdiEjbBean<T> bean = new OpenEJBBeanBuilder<T>(bc, webBeansContext, annotatedType, attributes).createBean(clazz, !annotatedType.isAnnotationPresent(Vetoed.class));
    bc.set(CdiEjbBean.class, bean);
    bc.set(CurrentCreationalContext.class, new CurrentCreationalContext());
    validateDisposeMethods(bean);
    validateScope(bean);
    final Set<ObserverMethod<?>> observerMethods;
    if (bean.isEnabled()) {
        observerMethods = new ObserverMethodsBuilder<T>(webBeansContext, bean.getAnnotatedType()).defineObserverMethods(bean);
    } else {
        observerMethods = new HashSet<>();
    }
    final WebBeansUtil webBeansUtil = webBeansContext.getWebBeansUtil();
    final Set<ProducerFieldBean<?>> producerFields = new ProducerFieldBeansBuilder(bean.getWebBeansContext(), bean.getAnnotatedType()).defineProducerFields(bean);
    final Set<ProducerMethodBean<?>> producerMethods = new ProducerMethodBeansBuilder(bean.getWebBeansContext(), bean.getAnnotatedType()).defineProducerMethods(bean, producerFields);
    final Map<ProducerMethodBean<?>, AnnotatedMethod<?>> annotatedMethods = new HashMap<>();
    for (final ProducerMethodBean<?> producerMethod : producerMethods) {
        final AnnotatedMethod<?> method = webBeansContext.getAnnotatedElementFactory().newAnnotatedMethod(producerMethod.getCreatorMethod(), annotatedType);
        webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducer event observers for " + "ProducerMethods. Look at logs for further details");
        annotatedMethods.put(producerMethod, method);
    }
    final Map<ProducerFieldBean<?>, AnnotatedField<?>> annotatedFields = new HashMap<>();
    for (final ProducerFieldBean<?> producerField : producerFields) {
        if (!Modifier.isStatic(producerField.getCreatorField().getModifiers())) {
            throw new DefinitionException("In an EJB all producer fields should be static");
        }
        webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducer event observers for" + " ProducerFields. Look at logs for further details");
        annotatedFields.put(producerField, webBeansContext.getAnnotatedElementFactory().newAnnotatedField(producerField.getCreatorField(), webBeansContext.getAnnotatedElementFactory().newAnnotatedType(producerField.getBeanClass())));
    }
    final Map<ObserverMethod<?>, AnnotatedMethod<?>> observerMethodsMap = new HashMap<>();
    for (final ObserverMethod<?> observerMethod : observerMethods) {
        final ObserverMethodImpl<?> impl = (ObserverMethodImpl<?>) observerMethod;
        final AnnotatedMethod<?> method = impl.getObserverMethod();
        observerMethodsMap.put(observerMethod, method);
    }
    validateProduceMethods(bean, producerMethods);
    validateObserverMethods(bean, observerMethodsMap);
    final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl();
    // Fires ProcessManagedBean
    final GProcessSessionBean event = new GProcessSessionBean(Bean.class.cast(bean), annotatedType, bc.getEjbName(), bean.getEjbType());
    beanManager.fireEvent(event, true);
    event.setStarted();
    webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessSessionBean event observers for managed beans. Look at logs for further details");
    // Fires ProcessProducerMethod
    webBeansUtil.fireProcessProducerMethodBeanEvent(annotatedMethods, annotatedType);
    webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducerMethod event observers for producer method beans. Look at logs for further details");
    // Fires ProcessProducerField
    webBeansUtil.fireProcessProducerFieldBeanEvent(annotatedFields);
    webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducerField event observers for producer field beans. Look at logs for further details");
    // Fire ObservableMethods
    webBeansUtil.fireProcessObservableMethodBeanEvent(observerMethodsMap);
    webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessObserverMethod event observers for observer methods. Look at logs for further details");
    if (!webBeansUtil.isAnnotatedTypeDecoratorOrInterceptor(annotatedType)) {
        for (final ProducerMethodBean<?> producerMethod : producerMethods) {
            beanManager.addBean(producerMethod);
        }
        for (final ProducerFieldBean<?> producerField : producerFields) {
            beanManager.addBean(producerField);
        }
    }
    beanManager.addBean(bean);
    return bean;
}
Also used : AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) ArrayList(java.util.ArrayList) ProducerFieldBean(org.apache.webbeans.component.ProducerFieldBean) GProcessSessionBean(org.apache.webbeans.portable.events.generics.GProcessSessionBean) ProducerMethodBean(org.apache.webbeans.component.ProducerMethodBean) Bean(javax.enterprise.inject.spi.Bean) OwbBean(org.apache.webbeans.component.OwbBean) AbstractOwbBean(org.apache.webbeans.component.AbstractOwbBean) ProducerFieldBeansBuilder(org.apache.webbeans.component.creation.ProducerFieldBeansBuilder) GProcessSessionBean(org.apache.webbeans.portable.events.generics.GProcessSessionBean) ObserverMethodsBuilder(org.apache.webbeans.component.creation.ObserverMethodsBuilder) ObserverMethodImpl(org.apache.webbeans.event.ObserverMethodImpl) DefinitionException(javax.enterprise.inject.spi.DefinitionException) ProducerMethodBean(org.apache.webbeans.component.ProducerMethodBean) ObserverMethod(javax.enterprise.inject.spi.ObserverMethod) ProducerFieldBean(org.apache.webbeans.component.ProducerFieldBean) BeanContext(org.apache.openejb.BeanContext) WebBeansUtil(org.apache.webbeans.util.WebBeansUtil) ProducerMethodBeansBuilder(org.apache.webbeans.component.creation.ProducerMethodBeansBuilder) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) AnnotatedField(javax.enterprise.inject.spi.AnnotatedField)

Example 4 with BeanManagerImpl

use of org.apache.webbeans.container.BeanManagerImpl in project tomee by apache.

the class CdiScanner method isBean.

// TODO: reusing our finder would be a good idea to avoid reflection we already did!
private boolean isBean(final Class clazz) {
    try {
        for (final Annotation a : clazz.getAnnotations()) {
            final Class<? extends Annotation> annotationType = a.annotationType();
            final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl();
            if (beanManager.isScope(annotationType) || beanManager.isStereotype(annotationType) || beanManager.isInterceptorBinding(annotationType) || Decorator.class == a.annotationType()) {
                return true;
            }
        }
    } catch (final Throwable e) {
    // no-op
    }
    return false;
}
Also used : Decorator(javax.decorator.Decorator) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) Annotation(java.lang.annotation.Annotation)

Example 5 with BeanManagerImpl

use of org.apache.webbeans.container.BeanManagerImpl in project tomee by apache.

the class WebappBeanManager method getInjectableReference.

@Override
public Object getInjectableReference(final InjectionPoint injectionPoint, final CreationalContext<?> ctx) {
    Asserts.assertNotNull(injectionPoint, "injectionPoint parameter");
    if (injectionPoint == null) {
        return null;
    }
    final BeanManagerImpl parentBm = getParentBm();
    final Boolean existing = USE_PARENT_BM.get();
    if (existing != null && existing) {
        // shortcut the whole logic to keep the threadlocal set up correctly
        if (parentBm == null) {
            return null;
        }
        return parentBm.getInjectableReference(injectionPoint, ctx);
    }
    // we can do it cause there is caching but we shouldn't - easy way to overide OWB actually
    final Bean<Object> injectedBean = (Bean<Object>) getInjectionResolver().getInjectionPointBean(injectionPoint);
    try {
        if (parentBm != null && injectedBean != null && injectedBean == parentBm.getInjectionResolver().getInjectionPointBean(injectionPoint)) {
            USE_PARENT_BM.set(true);
            try {
                return parentBm.getInjectableReference(injectionPoint, ctx);
            } finally {
                USE_PARENT_BM.remove();
            }
        }
    } catch (final UnsatisfiedResolutionException ure) {
    // skip, use this bean
    }
    return super.getInjectableReference(injectionPoint, ctx);
}
Also used : BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) UnsatisfiedResolutionException(javax.enterprise.inject.UnsatisfiedResolutionException) OwbBean(org.apache.webbeans.component.OwbBean) ExtensionBean(org.apache.webbeans.component.ExtensionBean) BuiltInOwbBean(org.apache.webbeans.component.BuiltInOwbBean) Bean(javax.enterprise.inject.spi.Bean)

Aggregations

BeanManagerImpl (org.apache.webbeans.container.BeanManagerImpl)19 Bean (javax.enterprise.inject.spi.Bean)8 WebBeansContext (org.apache.webbeans.config.WebBeansContext)8 ArrayList (java.util.ArrayList)4 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)4 IOException (java.io.IOException)3 OpenEJBException (org.apache.openejb.OpenEJBException)3 OwbBean (org.apache.webbeans.component.OwbBean)3 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 BeanManager (javax.enterprise.inject.spi.BeanManager)2 DefinitionException (javax.enterprise.inject.spi.DefinitionException)2 DeploymentException (javax.enterprise.inject.spi.DeploymentException)2 ObserverMethod (javax.enterprise.inject.spi.ObserverMethod)2 NamingException (javax.naming.NamingException)2 ServletException (javax.servlet.ServletException)2 BusException (org.apache.cxf.BusException)2 EndpointException (org.apache.cxf.endpoint.EndpointException)2 JAXRSServerFactoryBean (org.apache.cxf.jaxrs.JAXRSServerFactoryBean)2 ResponseConstraintViolationException (org.apache.cxf.validation.ResponseConstraintViolationException)2