Search in sources :

Example 11 with WebBeansContext

use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.

the class ThreadSingletonServiceImpl method clear.

@Override
public void clear(final Object key) {
    final WebBeansContext ctx = getContext((ClassLoader) key);
    if (logger.isDebugEnabled()) {
        logger.debug("Clearing:'" + ctx + "'");
    }
    contextByClassLoader.remove(key);
    if (ctx != null) {
        ctx.clear();
    }
}
Also used : WebBeansContext(org.apache.webbeans.config.WebBeansContext)

Example 12 with WebBeansContext

use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.

the class HandlerResolverImpl method buildHandlers.

private List<Handler> buildHandlers(final PortInfo portInfo, final HandlerChainData handlerChain) {
    if (!matchServiceName(portInfo, handlerChain.getServiceNamePattern()) || !matchPortName(portInfo, handlerChain.getPortNamePattern()) || !matchBinding(portInfo, handlerChain.getProtocolBindings())) {
        return Collections.emptyList();
    }
    final List<Handler> handlers = new ArrayList<Handler>(handlerChain.getHandlers().size());
    for (final HandlerData handler : handlerChain.getHandlers()) {
        final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb(Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE);
        if (webBeansContext != null) {
            // cdi
            final BeanManagerImpl bm = webBeansContext.getBeanManagerImpl();
            if (bm.isInUse()) {
                try {
                    final Set<Bean<?>> beans = bm.getBeans(handler.getHandlerClass());
                    final Bean<?> bean = bm.resolve(beans);
                    if (bean != null) {
                        // proxy so faster to do it
                        final boolean normalScoped = bm.isNormalScope(bean.getScope());
                        final CreationalContextImpl<?> creationalContext = bm.createCreationalContext(bean);
                        final Handler instance = Handler.class.cast(bm.getReference(bean, bean.getBeanClass(), creationalContext));
                        // hack for destroyHandlers()
                        handlers.add(instance);
                        handlerInstances.add(new InjectionProcessor<Handler>(instance, Collections.<Injection>emptySet(), null) {

                            @Override
                            public void preDestroy() {
                                if (!normalScoped) {
                                    creationalContext.release();
                                }
                            }
                        });
                        continue;
                    }
                } catch (final InjectionException ie) {
                    LOGGER.info(ie.getMessage(), ie);
                }
            }
        }
        try {
            // old way
            final Class<? extends Handler> handlerClass = handler.getHandlerClass().asSubclass(Handler.class);
            final InjectionProcessor<Handler> processor = new InjectionProcessor<Handler>(handlerClass, injections, handler.getPostConstruct(), handler.getPreDestroy(), unwrap(context));
            processor.createInstance();
            processor.postConstruct();
            final Handler handlerInstance = processor.getInstance();
            handlers.add(handlerInstance);
            handlerInstances.add(processor);
        } catch (final Exception e) {
            throw new WebServiceException("Failed to instantiate handler", e);
        }
    }
    return handlers;
}
Also used : WebServiceException(javax.xml.ws.WebServiceException) ArrayList(java.util.ArrayList) LogicalHandler(javax.xml.ws.handler.LogicalHandler) Handler(javax.xml.ws.handler.Handler) Injection(org.apache.openejb.Injection) InjectionProcessor(org.apache.openejb.InjectionProcessor) InjectionException(javax.enterprise.inject.InjectionException) WebServiceException(javax.xml.ws.WebServiceException) Bean(javax.enterprise.inject.spi.Bean) InjectionException(javax.enterprise.inject.InjectionException) WebBeansContext(org.apache.webbeans.config.WebBeansContext) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl)

Example 13 with WebBeansContext

use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.

the class Assembler method ensureWebBeansContext.

private void ensureWebBeansContext(final AppContext appContext) {
    WebBeansContext webBeansContext = appContext.get(WebBeansContext.class);
    if (webBeansContext == null) {
        webBeansContext = appContext.getWebBeansContext();
    } else {
        if (null == appContext.getWebBeansContext()) {
            appContext.setWebBeansContext(webBeansContext);
        }
        return;
    }
    if (webBeansContext == null) {
        final Map<Class<?>, Object> services = new HashMap<Class<?>, Object>();
        services.put(JNDIService.class, new OpenEJBJndiService());
        services.put(AppContext.class, appContext);
        services.put(ScannerService.class, new CdiScanner());
        services.put(BeanArchiveService.class, new OpenEJBBeanInfoService());
        services.put(ELAdaptor.class, new CustomELAdapter(appContext));
        services.put(LoaderService.class, new OptimizedLoaderService(appContext.getProperties()));
        final Properties properties = new Properties();
        properties.setProperty(org.apache.webbeans.spi.SecurityService.class.getName(), ManagedSecurityService.class.getName());
        properties.setProperty(ContextsService.class.getName(), CdiAppContextsService.class.getName());
        properties.setProperty(ResourceInjectionService.class.getName(), CdiResourceInjectionService.class.getName());
        properties.setProperty(TransactionService.class.getName(), OpenEJBTransactionService.class.getName());
        webBeansContext = new WebBeansContext(services, properties);
        appContext.setCdiEnabled(false);
        appContext.set(WebBeansContext.class, webBeansContext);
        appContext.setWebBeansContext(webBeansContext);
    }
}
Also used : ContextsService(org.apache.webbeans.spi.ContextsService) CdiAppContextsService(org.apache.openejb.cdi.CdiAppContextsService) OpenEJBJndiService(org.apache.openejb.cdi.OpenEJBJndiService) TransactionService(org.apache.webbeans.spi.TransactionService) OpenEJBTransactionService(org.apache.openejb.cdi.OpenEJBTransactionService) HashMap(java.util.HashMap) CdiAppContextsService(org.apache.openejb.cdi.CdiAppContextsService) ManagedSecurityService(org.apache.openejb.cdi.ManagedSecurityService) OpenEJBTransactionService(org.apache.openejb.cdi.OpenEJBTransactionService) SuperProperties(org.apache.openejb.util.SuperProperties) Properties(java.util.Properties) CdiResourceInjectionService(org.apache.openejb.cdi.CdiResourceInjectionService) ResourceInjectionService(org.apache.webbeans.spi.ResourceInjectionService) WebBeansContext(org.apache.webbeans.config.WebBeansContext) CustomELAdapter(org.apache.openejb.cdi.CustomELAdapter) OptimizedLoaderService(org.apache.openejb.cdi.OptimizedLoaderService) ManagedSecurityService(org.apache.openejb.cdi.ManagedSecurityService) SecurityService(org.apache.openejb.spi.SecurityService) CdiScanner(org.apache.openejb.cdi.CdiScanner) OpenEJBBeanInfoService(org.apache.openejb.cdi.OpenEJBBeanInfoService) CdiResourceInjectionService(org.apache.openejb.cdi.CdiResourceInjectionService)

Example 14 with WebBeansContext

use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.

the class BeanContext method inject.

@SuppressWarnings("unchecked")
public <T> void inject(final T instance, CreationalContext<T> ctx) {
    final WebBeansContext webBeansContext = getWebBeansContext();
    if (webBeansContext == null) {
        return;
    }
    InjectionTargetBean<T> beanDefinition = get(CdiEjbBean.class);
    if (beanDefinition == null) {
        beanDefinition = InjectionTargetBean.class.cast(createConstructorInjectionBean(webBeansContext));
    }
    if (!(ctx instanceof CreationalContextImpl)) {
        ctx = webBeansContext.getCreationalContextFactory().wrappedCreationalContext(ctx, beanDefinition);
    }
    beanDefinition.getInjectionTarget().inject(instance, ctx);
}
Also used : WebBeansContext(org.apache.webbeans.config.WebBeansContext) CreationalContextImpl(org.apache.webbeans.context.creational.CreationalContextImpl) InjectionTargetBean(org.apache.webbeans.component.InjectionTargetBean)

Example 15 with WebBeansContext

use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.

the class BeanContext method newInstance.

@SuppressWarnings("unchecked")
public InstanceContext newInstance() throws Exception {
    final ThreadContext callContext = new ThreadContext(this, null, Operation.INJECTION);
    final ThreadContext oldContext = ThreadContext.enter(callContext);
    final boolean dynamicallyImplemented = isDynamicallyImplemented();
    final WebBeansContext webBeansContext = getWebBeansContext();
    if (dynamicallyImplemented) {
        if (!InvocationHandler.class.isAssignableFrom(getProxyClass())) {
            throw new OpenEJBException("proxy class can only be InvocationHandler");
        }
    }
    try {
        final Context ctx = getJndiEnc();
        final Class beanClass = getBeanClass();
        final CurrentCreationalContext<Object> currentCreationalContext = get(CurrentCreationalContext.class);
        CreationalContext<Object> creationalContext = currentCreationalContext != null ? currentCreationalContext.get() : null;
        final CdiEjbBean cdiEjbBean = get(CdiEjbBean.class);
        if (!CreationalContextImpl.class.isInstance(creationalContext) && webBeansContext != null) {
            if (creationalContext == null) {
                creationalContext = webBeansContext.getCreationalContextFactory().getCreationalContext(cdiEjbBean);
            } else {
                creationalContext = webBeansContext.getCreationalContextFactory().wrappedCreationalContext(creationalContext, cdiEjbBean);
            }
        }
        final Object rootInstance;
        if (cdiEjbBean != null && !dynamicallyImplemented && CdiEjbBean.EjbInjectionTargetImpl.class.isInstance(cdiEjbBean.getInjectionTarget())) {
            rootInstance = CdiEjbBean.EjbInjectionTargetImpl.class.cast(cdiEjbBean.getInjectionTarget()).createNewPojo(creationalContext);
        } else {
            // not a cdi bean
            rootInstance = getManagedClass().newInstance();
        }
        // Create bean instance
        Object beanInstance;
        final InjectionProcessor injectionProcessor;
        if (!dynamicallyImplemented) {
            injectionProcessor = new InjectionProcessor(rootInstance, getInjections(), InjectionProcessor.unwrap(ctx));
            beanInstance = injectionProcessor.createInstance();
            inject(beanInstance, creationalContext);
        } else {
            // update target
            final List<Injection> newInjections = new ArrayList<Injection>();
            for (final Injection injection : getInjections()) {
                if (beanClass.equals(injection.getTarget())) {
                    final Injection updated = new Injection(injection.getJndiName(), injection.getName(), proxyClass);
                    newInjections.add(updated);
                } else {
                    newInjections.add(injection);
                }
            }
            injections.clear();
            injections.addAll(newInjections);
            injectionProcessor = new InjectionProcessor(rootInstance, injections, InjectionProcessor.unwrap(ctx));
            final InvocationHandler handler = (InvocationHandler) injectionProcessor.createInstance();
            beanInstance = DynamicProxyImplFactory.newProxy(this, handler);
            inject(handler, creationalContext);
        }
        // Create interceptors
        final Map<String, Object> interceptorInstances = new LinkedHashMap<String, Object>();
        // Add the stats interceptor instance and other already created interceptor instances
        for (final InterceptorInstance interceptorInstance : this.getUserAndSystemInterceptors()) {
            final Class clazz = interceptorInstance.getData().getInterceptorClass();
            interceptorInstances.put(clazz.getName(), interceptorInstance.getInterceptor());
        }
        for (final InterceptorData interceptorData : this.getInstanceScopedInterceptors()) {
            if (interceptorData.getInterceptorClass().equals(beanClass)) {
                continue;
            }
            final Class clazz = interceptorData.getInterceptorClass();
            final Object iInstance;
            if (webBeansContext != null) {
                ConstructorInjectionBean interceptorConstructor = interceptorData.get(ConstructorInjectionBean.class);
                if (interceptorConstructor == null) {
                    synchronized (this) {
                        interceptorConstructor = interceptorData.get(ConstructorInjectionBean.class);
                        if (interceptorConstructor == null) {
                            interceptorConstructor = new ConstructorInjectionBean(webBeansContext, clazz, webBeansContext.getAnnotatedElementFactory().newAnnotatedType(clazz));
                            interceptorData.set(ConstructorInjectionBean.class, interceptorConstructor);
                        }
                    }
                }
                iInstance = interceptorConstructor.create(creationalContext);
            } else {
                iInstance = clazz.newInstance();
            }
            final InjectionProcessor interceptorInjector = new InjectionProcessor(iInstance, this.getInjections(), InjectionProcessor.unwrap(ctx));
            try {
                final Object interceptorInstance = interceptorInjector.createInstance();
                if (webBeansContext != null) {
                    try {
                        OWBInjector.inject(webBeansContext.getBeanManagerImpl(), interceptorInstance, creationalContext);
                    } catch (final Throwable t) {
                    // TODO handle this differently
                    // this is temporary till the injector can be rewritten
                    }
                }
                interceptorInstances.put(clazz.getName(), interceptorInstance);
            } catch (final ConstructionException e) {
                throw new Exception("Failed to create interceptor: " + clazz.getName(), e);
            }
        }
        interceptorInstances.put(beanClass.getName(), beanInstance);
        // Invoke post construct method
        callContext.setCurrentOperation(Operation.POST_CONSTRUCT);
        final List<InterceptorData> callbackInterceptors = this.getCallbackInterceptors();
        final InterceptorStack postConstruct = new InterceptorStack(beanInstance, null, Operation.POST_CONSTRUCT, callbackInterceptors, interceptorInstances);
        //Transaction Demarcation for Singleton PostConstruct method
        TransactionType transactionType;
        if (componentType == BeanType.SINGLETON || componentType == BeanType.STATEFUL) {
            final Set<Method> callbacks = callbackInterceptors.get(callbackInterceptors.size() - 1).getPostConstruct();
            if (callbacks.isEmpty()) {
                transactionType = TransactionType.RequiresNew;
            } else {
                // TODO: we should take the last one I think
                transactionType = getTransactionType(callbacks.iterator().next());
                if (transactionType == TransactionType.Required) {
                    transactionType = TransactionType.RequiresNew;
                }
            }
        } else {
            transactionType = isBeanManagedTransaction() ? TransactionType.BeanManaged : TransactionType.NotSupported;
        }
        final TransactionPolicy transactionPolicy = EjbTransactionUtil.createTransactionPolicy(transactionType, callContext);
        try {
            //Call the chain
            if (cdiEjbBean != null) {
                // call it, it has no postconstruct but extensions can add stuff here, TODO: see if it should be called before or after effective postconstruct
                cdiEjbBean.getInjectionTarget().postConstruct(beanInstance);
            }
            postConstruct.invoke();
        } catch (final Throwable e) {
            //RollBack Transaction
            EjbTransactionUtil.handleSystemException(transactionPolicy, e, callContext);
        } finally {
            EjbTransactionUtil.afterInvoke(transactionPolicy, callContext);
        }
        // handle cdi decorators
        if (cdiEjbBean != null) {
            final Class<?> proxyClass = Class.class.cast(Reflections.get(cdiEjbBean.getInjectionTarget(), "proxyClass"));
            if (proxyClass != null) {
                // means interception
                final InterceptorResolutionService.BeanInterceptorInfo interceptorInfo = cdiEjbBean.getBeanContext().get(InterceptorResolutionService.BeanInterceptorInfo.class);
                if (interceptorInfo.getDecorators() != null && !interceptorInfo.getDecorators().isEmpty()) {
                    final InterceptorDecoratorProxyFactory pf = webBeansContext.getInterceptorDecoratorProxyFactory();
                    // decorators
                    final Object instance = beanInstance;
                    final List<Decorator<?>> decorators = interceptorInfo.getDecorators();
                    final Map<Decorator<?>, Object> instances = new HashMap<Decorator<?>, Object>();
                    for (int i = decorators.size(); i > 0; i--) {
                        final Decorator<?> decorator = decorators.get(i - 1);
                        CreationalContextImpl.class.cast(creationalContext).putDelegate(beanInstance);
                        final Object decoratorInstance = decorator.create(CreationalContext.class.cast(creationalContext));
                        instances.put(decorator, decoratorInstance);
                        beanInstance = pf.createProxyInstance(proxyClass, instance, new DecoratorHandler(interceptorInfo, decorators, instances, i - 1, instance, cdiEjbBean.getId()));
                    }
                }
            }
        }
        return new InstanceContext(this, beanInstance, interceptorInstances, creationalContext);
    } finally {
        ThreadContext.exit(oldContext);
    }
}
Also used : TransactionType(org.apache.openejb.core.transaction.TransactionType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) CdiEjbBean(org.apache.openejb.cdi.CdiEjbBean) ArrayList(java.util.ArrayList) CreationalContextImpl(org.apache.webbeans.context.creational.CreationalContextImpl) DecoratorHandler(org.apache.webbeans.intercept.DecoratorHandler) LinkedHashMap(java.util.LinkedHashMap) WebBeansContext(org.apache.webbeans.config.WebBeansContext) InstanceContext(org.apache.openejb.core.InstanceContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) CurrentCreationalContext(org.apache.openejb.cdi.CurrentCreationalContext) CreationalContext(javax.enterprise.context.spi.CreationalContext) Context(javax.naming.Context) InstanceContext(org.apache.openejb.core.InstanceContext) ThreadContext(org.apache.openejb.core.ThreadContext) InterceptorResolutionService(org.apache.webbeans.intercept.InterceptorResolutionService) ConstructorInjectionBean(org.apache.openejb.cdi.ConstructorInjectionBean) ThreadContext(org.apache.openejb.core.ThreadContext) TransactionPolicy(org.apache.openejb.core.transaction.TransactionPolicy) InterceptorInstance(org.apache.openejb.core.interceptor.InterceptorInstance) Method(java.lang.reflect.Method) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) InvocationHandler(java.lang.reflect.InvocationHandler) ApplicationException(javax.ejb.ApplicationException) ConstructionException(org.apache.xbean.recipe.ConstructionException) Decorator(javax.enterprise.inject.spi.Decorator) CurrentCreationalContext(org.apache.openejb.cdi.CurrentCreationalContext) CreationalContext(javax.enterprise.context.spi.CreationalContext) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) InterceptorStack(org.apache.openejb.core.interceptor.InterceptorStack) TimedObject(javax.ejb.TimedObject) EJBLocalObject(javax.ejb.EJBLocalObject) EJBObject(javax.ejb.EJBObject) ConstructionException(org.apache.xbean.recipe.ConstructionException) InterceptorDecoratorProxyFactory(org.apache.webbeans.proxy.InterceptorDecoratorProxyFactory)

Aggregations

WebBeansContext (org.apache.webbeans.config.WebBeansContext)39 AppContext (org.apache.openejb.AppContext)11 BeanContext (org.apache.openejb.BeanContext)10 WebContext (org.apache.openejb.core.WebContext)9 Context (javax.naming.Context)8 OpenEJBException (org.apache.openejb.OpenEJBException)8 BeanManagerImpl (org.apache.webbeans.container.BeanManagerImpl)8 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 Properties (java.util.Properties)6 NamingException (javax.naming.NamingException)6 ServletContext (javax.servlet.ServletContext)6 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)6 InitialContext (javax.naming.InitialContext)5 ContextsService (org.apache.webbeans.spi.ContextsService)5 MalformedURLException (java.net.MalformedURLException)4 CreationalContext (javax.enterprise.context.spi.CreationalContext)4 InjectionProcessor (org.apache.openejb.InjectionProcessor)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3