Search in sources :

Example 6 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);
                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 7 with BeanManagerImpl

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

the class OpenEJBEnricher method enrich.

public static void enrich(final Object testInstance, final AppContext appCtx) {
    // don't rely on arquillian since this enrichment should absolutely be done before the following ones
    new MockitoEnricher().enrich(testInstance);
    AppContext ctx = appCtx;
    if (ctx == null) {
        ctx = AppFinder.findAppContextOrWeb(Thread.currentThread().getContextClassLoader(), AppFinder.AppContextTransformer.INSTANCE);
        if (ctx == null) {
            return;
        }
    }
    final BeanContext context = SystemInstance.get().getComponent(ContainerSystem.class).getBeanContext(ctx.getId() + "_" + testInstance.getClass().getName());
    final WebBeansContext appWBC = ctx.getWebBeansContext();
    final BeanManagerImpl bm = appWBC == null ? null : appWBC.getBeanManagerImpl();
    boolean ok = false;
    for (final WebContext web : ctx.getWebContexts()) {
        final WebBeansContext webBeansContext = web.getWebBeansContext();
        if (webBeansContext == null) {
            continue;
        }
        final BeanManagerImpl webAppBm = webBeansContext.getBeanManagerImpl();
        if (webBeansContext != appWBC && webAppBm.isInUse()) {
            try {
                doInject(testInstance, context, webAppBm);
                ok = true;
                break;
            } catch (final Exception e) {
            // no-op, try next
            }
        }
    }
    if (bm != null && bm.isInUse() && !ok) {
        try {
            doInject(testInstance, context, bm);
        } catch (final Exception e) {
            LOGGER.log(Level.SEVERE, "Failed injection on: " + testInstance.getClass(), e);
            if (RuntimeException.class.isInstance(e)) {
                throw RuntimeException.class.cast(e);
            }
            throw new OpenEJBRuntimeException(e);
        }
    }
    if (context != null) {
        final ThreadContext callContext = new ThreadContext(context, null, Operation.INJECTION);
        final ThreadContext oldContext = ThreadContext.enter(callContext);
        try {
            final InjectionProcessor processor = new InjectionProcessor<>(testInstance, context.getInjections(), context.getJndiContext());
            processor.createInstance();
        } catch (final OpenEJBException e) {
        // ignored
        } finally {
            ThreadContext.exit(oldContext);
        }
    }
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) OpenEJBException(org.apache.openejb.OpenEJBException) WebContext(org.apache.openejb.core.WebContext) AppContext(org.apache.openejb.AppContext) ThreadContext(org.apache.openejb.core.ThreadContext) InjectionProcessor(org.apache.openejb.InjectionProcessor) OpenEJBException(org.apache.openejb.OpenEJBException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanContext(org.apache.openejb.BeanContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) MockitoEnricher(org.apache.openejb.arquillian.common.mockito.MockitoEnricher)

Example 8 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 9 with BeanManagerImpl

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

the class CxfRsHttpListener method providers.

private List<Object> providers(final Collection<ServiceInfo> services, final Collection<Object> additionalProviders, final WebBeansContext ctx) {
    final List<Object> instances = new ArrayList<>();
    final BeanManagerImpl bm = ctx == null ? null : ctx.getBeanManagerImpl();
    for (final Object o : additionalProviders) {
        if (o instanceof Class<?>) {
            final Class<?> clazz = (Class<?>) o;
            if (isNotServerProvider(clazz)) {
                continue;
            }
            final String name = clazz.getName();
            if (shouldSkipProvider(name)) {
                continue;
            }
            if (bm != null && bm.isInUse()) {
                try {
                    final Set<Bean<?>> beans = bm.getBeans(clazz);
                    if (beans != null && !beans.isEmpty()) {
                        final Bean<?> bean = bm.resolve(beans);
                        final CreationalContextImpl<?> creationalContext = bm.createCreationalContext(bean);
                        instances.add(bm.getReference(bean, clazz, creationalContext));
                        toRelease.add(creationalContext);
                        continue;
                    }
                } catch (final Throwable th) {
                    LOGGER.info("Can't use CDI to create provider " + name);
                }
            }
            final Collection<Object> instance = ServiceInfos.resolve(services, new String[] { name }, OpenEJBProviderFactory.INSTANCE);
            if (instance != null && !instance.isEmpty()) {
                instances.add(instance.iterator().next());
            } else {
                try {
                    instances.add(newProvider(clazz));
                } catch (final Exception e) {
                    LOGGER.error("can't instantiate " + name, e);
                }
            }
        } else {
            final Class<?> clazz = o.getClass();
            if (isNotServerProvider(clazz)) {
                continue;
            }
            final String name = clazz.getName();
            if (shouldSkipProvider(name)) {
                continue;
            }
            instances.add(o);
        }
    }
    return instances;
}
Also used : CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) ResponseConstraintViolationException(org.apache.cxf.validation.ResponseConstraintViolationException) IOException(java.io.IOException) EndpointException(org.apache.cxf.endpoint.EndpointException) ServletException(javax.servlet.ServletException) BusException(org.apache.cxf.BusException) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) MBean(org.apache.openejb.api.jmx.MBean) Bean(javax.enterprise.inject.spi.Bean) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl)

Example 10 with BeanManagerImpl

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

the class CxfRsHttpListener method findProviderComparator.

private Comparator<?> findProviderComparator(final ServiceConfiguration serviceConfiguration, final WebBeansContext ctx) {
    final String comparatorKey = CXF_JAXRS_PREFIX + "provider-comparator";
    final String comparatorClass = serviceConfiguration.getProperties().getProperty(comparatorKey, SystemInstance.get().getProperty(comparatorKey));
    Comparator<Object> comparator = null;
    if (comparatorClass == null) {
        // try to rely on CXF behavior otherwise just reactivate DefaultProviderComparator.INSTANCE if it is an issue
        return null;
    } else {
        final BeanManagerImpl bm = ctx == null ? null : ctx.getBeanManagerImpl();
        if (bm != null && bm.isInUse()) {
            try {
                final Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(comparatorClass);
                final Set<Bean<?>> beans = bm.getBeans(clazz);
                if (beans != null && !beans.isEmpty()) {
                    final Bean<?> bean = bm.resolve(beans);
                    final CreationalContextImpl<?> creationalContext = bm.createCreationalContext(bean);
                    comparator = Comparator.class.cast(bm.getReference(bean, clazz, creationalContext));
                    toRelease.add(creationalContext);
                }
            } catch (final Throwable th) {
                LOGGER.debug("Can't use CDI to load comparator " + comparatorClass);
            }
        }
        if (comparator == null) {
            comparator = Comparator.class.cast(ServiceInfos.resolve(serviceConfiguration.getAvailableServices(), comparatorClass));
        }
        if (comparator == null) {
            try {
                comparator = Comparator.class.cast(Thread.currentThread().getContextClassLoader().loadClass(comparatorClass).newInstance());
            } catch (final Exception e) {
                throw new IllegalArgumentException(e);
            }
        }
        for (final Type itf : comparator.getClass().getGenericInterfaces()) {
            if (!ParameterizedType.class.isInstance(itf)) {
                continue;
            }
            final ParameterizedType pt = ParameterizedType.class.cast(itf);
            if (Comparator.class == pt.getRawType() && pt.getActualTypeArguments().length > 0) {
                final Type t = pt.getActualTypeArguments()[0];
                if (Class.class.isInstance(t) && ProviderInfo.class == t) {
                    return comparator;
                }
                if (ParameterizedType.class.isInstance(t) && ProviderInfo.class == ParameterizedType.class.cast(t).getRawType()) {
                    return comparator;
                }
            }
        }
        return new ProviderComparatorWrapper(comparator);
    }
}
Also used : ResponseConstraintViolationException(org.apache.cxf.validation.ResponseConstraintViolationException) IOException(java.io.IOException) EndpointException(org.apache.cxf.endpoint.EndpointException) ServletException(javax.servlet.ServletException) BusException(org.apache.cxf.BusException) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) MBean(org.apache.openejb.api.jmx.MBean) Bean(javax.enterprise.inject.spi.Bean) ResourceComparator(org.apache.cxf.jaxrs.ext.ResourceComparator) Comparator(java.util.Comparator) ParameterizedType(java.lang.reflect.ParameterizedType) MediaType(javax.ws.rs.core.MediaType) RuntimeType(javax.ws.rs.RuntimeType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl)

Aggregations

BeanManagerImpl (org.apache.webbeans.container.BeanManagerImpl)17 WebBeansContext (org.apache.webbeans.config.WebBeansContext)8 Bean (javax.enterprise.inject.spi.Bean)7 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 DefinitionException (javax.enterprise.inject.spi.DefinitionException)2 DeploymentException (javax.enterprise.inject.spi.DeploymentException)2 ObserverMethod (javax.enterprise.inject.spi.ObserverMethod)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 BeanContext (org.apache.openejb.BeanContext)2 InjectionProcessor (org.apache.openejb.InjectionProcessor)2