Search in sources :

Example 1 with WeldManager

use of org.jboss.weld.manager.api.WeldManager in project core by weld.

the class WeldServletLifecycle method initialize.

/**
 * @param context
 * @return <code>true</code> if initialized properly, <code>false</code> otherwise
 */
boolean initialize(ServletContext context) {
    isDevModeEnabled = Boolean.valueOf(context.getInitParameter(CONTEXT_PARAM_DEV_MODE));
    WeldManager manager = (WeldManager) context.getAttribute(BEAN_MANAGER_ATTRIBUTE_NAME);
    if (manager != null) {
        isBootstrapNeeded = false;
        String contextId = BeanManagerProxy.unwrap(manager).getContextId();
        context.setInitParameter(org.jboss.weld.Container.CONTEXT_ID_KEY, contextId);
    } else {
        Object container = context.getAttribute(Listener.CONTAINER_ATTRIBUTE_NAME);
        if (container instanceof ContainerInstanceFactory) {
            ContainerInstanceFactory factory = (ContainerInstanceFactory) container;
            // start the container
            ContainerInstance containerInstance = factory.initialize();
            container = containerInstance;
            // we are in charge of shutdown also
            this.shutdownAction = () -> containerInstance.shutdown();
        }
        if (container instanceof ContainerInstance) {
            // the container instance was either passed to us directly or was created in the block above
            ContainerInstance containerInstance = (ContainerInstance) container;
            manager = BeanManagerProxy.unwrap(containerInstance.getBeanManager());
            context.setInitParameter(org.jboss.weld.Container.CONTEXT_ID_KEY, containerInstance.getId());
            isBootstrapNeeded = false;
        }
    }
    final CDI11Bootstrap bootstrap = new WeldBootstrap();
    if (isBootstrapNeeded) {
        final CDI11Deployment deployment = createDeployment(context, bootstrap);
        deployment.getServices().add(ExternalConfiguration.class, new ExternalConfigurationBuilder().add(BEAN_IDENTIFIER_INDEX_OPTIMIZATION.get(), Boolean.FALSE.toString()).build());
        if (deployment.getBeanDeploymentArchives().isEmpty()) {
            // Skip initialization - there is no bean archive in the deployment
            CommonLogger.LOG.initSkippedNoBeanArchiveFound();
            return false;
        }
        ResourceInjectionServices resourceInjectionServices = new ServletResourceInjectionServices() {
        };
        try {
            for (BeanDeploymentArchive archive : deployment.getBeanDeploymentArchives()) {
                archive.getServices().add(ResourceInjectionServices.class, resourceInjectionServices);
            }
        } catch (NoClassDefFoundError e) {
            // Support GAE
            WeldServletLogger.LOG.resourceInjectionNotAvailable();
        }
        String id = context.getInitParameter(org.jboss.weld.Container.CONTEXT_ID_KEY);
        if (id != null) {
            bootstrap.startContainer(id, Environments.SERVLET, deployment);
        } else {
            bootstrap.startContainer(Environments.SERVLET, deployment);
        }
        bootstrap.startInitialization();
        /*
             * Determine the BeanManager used for example for EL resolution - this should work fine as all bean archives share the same classloader. The only
             * difference this can make is per-BDA (CDI 1.0 style) enablement of alternatives, interceptors and decorators. Nothing we can do about that.
             *
             * First try to find the bean archive for WEB-INF/classes. If not found, take the first one available.
             */
        for (BeanDeploymentArchive bda : deployment.getBeanDeploymentArchives()) {
            if (bda.getId().contains(ManagerObjectFactory.WEB_INF_CLASSES_FILE_PATH) || bda.getId().contains(ManagerObjectFactory.WEB_INF_CLASSES)) {
                manager = bootstrap.getManager(bda);
                break;
            }
        }
        if (manager == null) {
            manager = bootstrap.getManager(deployment.getBeanDeploymentArchives().iterator().next());
        }
        // Push the manager into the servlet context so we can access in JSF
        context.setAttribute(BEAN_MANAGER_ATTRIBUTE_NAME, manager);
    }
    ContainerContext containerContext = new ContainerContext(context, manager);
    StringBuilder dump = new StringBuilder();
    Container container = findContainer(containerContext, dump);
    if (container == null) {
        WeldServletLogger.LOG.noSupportedServletContainerDetected();
        WeldServletLogger.LOG.debugv("Exception dump from Container lookup: {0}", dump);
    } else {
        container.initialize(containerContext);
        this.container = container;
    }
    if (Reflections.isClassLoadable(WeldClassLoaderResourceLoader.INSTANCE, JSP_FACTORY_CLASS_NAME) && JspFactory.getDefaultFactory() != null) {
        JspApplicationContext jspApplicationContext = JspFactory.getDefaultFactory().getJspApplicationContext(context);
        // Register the ELResolver with JSP
        jspApplicationContext.addELResolver(manager.getELResolver());
        // Register ELContextListener with JSP
        try {
            jspApplicationContext.addELContextListener(new WeldELContextListener());
        } catch (Exception e) {
            throw WeldServletLogger.LOG.errorLoadingWeldELContextListener(e);
        }
        // Push the wrapped expression factory into the servlet context so that Tomcat or Jetty can hook it in using a container code
        context.setAttribute(EXPRESSION_FACTORY_NAME, manager.wrapExpressionFactory(jspApplicationContext.getExpressionFactory()));
    }
    if (isBootstrapNeeded) {
        bootstrap.deployBeans().validateBeans().endInitialization();
        if (isDevModeEnabled) {
            FilterRegistration.Dynamic filterDynamic = context.addFilter("Weld Probe Filter", DevelopmentMode.PROBE_FILTER_CLASS_NAME);
            filterDynamic.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), true, "/*");
        }
        this.shutdownAction = () -> bootstrap.shutdown();
    }
    return true;
}
Also used : ServletResourceInjectionServices(org.jboss.weld.environment.servlet.services.ServletResourceInjectionServices) ResourceInjectionServices(org.jboss.weld.injection.spi.ResourceInjectionServices) JspApplicationContext(javax.servlet.jsp.JspApplicationContext) CDI11Bootstrap(org.jboss.weld.bootstrap.api.CDI11Bootstrap) WeldBootstrap(org.jboss.weld.bootstrap.WeldBootstrap) ExternalConfigurationBuilder(org.jboss.weld.configuration.spi.helpers.ExternalConfigurationBuilder) CDI11Deployment(org.jboss.weld.bootstrap.spi.CDI11Deployment) WeldManager(org.jboss.weld.manager.api.WeldManager) ContainerInstance(org.jboss.weld.environment.ContainerInstance) UndertowContainer(org.jboss.weld.environment.undertow.UndertowContainer) JettyContainer(org.jboss.weld.environment.jetty.JettyContainer) TomcatContainer(org.jboss.weld.environment.tomcat.TomcatContainer) GwtDevHostedModeContainer(org.jboss.weld.environment.gwtdev.GwtDevHostedModeContainer) ContainerInstanceFactory(org.jboss.weld.environment.ContainerInstanceFactory) WeldBeanDeploymentArchive(org.jboss.weld.environment.deployment.WeldBeanDeploymentArchive) BeanDeploymentArchive(org.jboss.weld.bootstrap.spi.BeanDeploymentArchive) WeldELContextListener(org.jboss.weld.module.web.el.WeldELContextListener) ServletResourceInjectionServices(org.jboss.weld.environment.servlet.services.ServletResourceInjectionServices) FilterRegistration(javax.servlet.FilterRegistration)

Example 2 with WeldManager

use of org.jboss.weld.manager.api.WeldManager in project core by weld.

the class ProbeExtension method processBeanAttributes.

public <T> void processBeanAttributes(@Observes ProcessBeanAttributes<T> event, BeanManager beanManager) {
    probe.getBootstrapStats().increment(EventType.PBA);
    final BeanAttributes<T> beanAttributes = event.getBeanAttributes();
    final WeldManager weldManager = (WeldManager) beanManager;
    if (isMonitored(event.getAnnotated(), beanAttributes, weldManager)) {
        event.setBeanAttributes(new ForwardingBeanAttributes<T>() {

            @Override
            public Set<Class<? extends Annotation>> getStereotypes() {
                return ImmutableSet.<Class<? extends Annotation>>builder().addAll(attributes().getStereotypes()).add(MonitoredComponent.class).build();
            }

            @Override
            protected BeanAttributes<T> attributes() {
                return beanAttributes;
            }

            @Override
            public String toString() {
                return beanAttributes.toString();
            }
        });
        ProbeLogger.LOG.monitoringStereotypeAdded(event.getAnnotated());
    }
    if (eventMonitorContainerLifecycleEvents) {
        addContainerLifecycleEvent(event, "Types: [" + Formats.formatTypes(event.getBeanAttributes().getTypes()) + "], qualifiers: [" + Formats.formatAnnotations(event.getBeanAttributes().getQualifiers()) + "]", beanManager);
    }
}
Also used : ImmutableSet(org.jboss.weld.util.collections.ImmutableSet) Set(java.util.Set) ForwardingBeanAttributes(org.jboss.weld.util.bean.ForwardingBeanAttributes) ProcessBeanAttributes(javax.enterprise.inject.spi.ProcessBeanAttributes) BeanAttributes(javax.enterprise.inject.spi.BeanAttributes) Annotation(java.lang.annotation.Annotation) WeldManager(org.jboss.weld.manager.api.WeldManager)

Example 3 with WeldManager

use of org.jboss.weld.manager.api.WeldManager in project HotswapAgent by HotswapProjects.

the class BeanReloadExecutor method doReloadBean.

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
private static void doReloadBean(String bdaId, Class<?> beanClass, String oldSignatureByStrategy, BeanReloadStrategy reloadStrategy) {
    BeanManagerImpl beanManager = null;
    BeanManager bm = CDI.current().getBeanManager();
    if (bm instanceof WeldManager) {
        bm = ((WeldManager) bm).unwrap();
    }
    if (bm instanceof BeanManagerImpl) {
        beanManager = (BeanManagerImpl) bm;
    }
    // TODO: check if archive is excluded
    Set<Bean<?>> beans = beanManager.getBeans(beanClass, new AnnotationLiteral<Any>() {
    });
    if (beans != null && !beans.isEmpty()) {
        for (Bean<?> bean : beans) {
            if (bean instanceof AbstractClassBean) {
                EnhancedAnnotatedType eat = createAnnotatedTypeForExistingBeanClass(bdaId, beanClass);
                if (!eat.isAbstract() || !eat.getJavaClass().isInterface()) {
                    // injectionTargetCannotBeCreatedForInterface
                    ((AbstractClassBean) bean).setProducer(beanManager.getLocalInjectionTargetFactory(eat).createInjectionTarget(eat, bean, false));
                    if (isReinjectingContext(bean)) {
                        doReloadAbstractClassBean(beanManager, beanClass, (AbstractClassBean) bean, oldSignatureByStrategy, reloadStrategy);
                        LOGGER.debug("Bean reloaded '{}'", beanClass.getName());
                        continue;
                    }
                }
                LOGGER.info("Bean '{}' redefined", beanClass.getName());
            } else {
                LOGGER.warning("Bean '{}' reloading not supported.", beanClass.getName());
            }
        }
    } else {
        doDefineNewManagedBean(beanManager, bdaId, beanClass);
    }
}
Also used : EnhancedAnnotatedType(org.jboss.weld.annotated.enhanced.EnhancedAnnotatedType) BeanManagerImpl(org.jboss.weld.manager.BeanManagerImpl) AbstractClassBean(org.jboss.weld.bean.AbstractClassBean) BeanManager(javax.enterprise.inject.spi.BeanManager) Any(javax.enterprise.inject.Any) WeldManager(org.jboss.weld.manager.api.WeldManager) AbstractClassBean(org.jboss.weld.bean.AbstractClassBean) ManagedBean(org.jboss.weld.bean.ManagedBean) Bean(javax.enterprise.inject.spi.Bean)

Example 4 with WeldManager

use of org.jboss.weld.manager.api.WeldManager in project Payara by payara.

the class JCDIServiceImpl method _createJCDIInjectionContext.

// instance could be null. If null, create a new one
@SuppressWarnings("unchecked")
private <T> JCDIInjectionContext<T> _createJCDIInjectionContext(EjbDescriptor ejb, T instance, Map<Class<?>, Object> ejbInfo) {
    BaseContainer baseContainer = null;
    EJBContextImpl ejbContext = null;
    JCDIInjectionContextImpl<T> jcdiCtx = null;
    CreationalContext<T> creationalContext = null;
    if (ejbInfo != null) {
        baseContainer = (BaseContainer) ejbInfo.get(BaseContainer.class);
        ejbContext = (EJBContextImpl) ejbInfo.get(EJBContextImpl.class);
    }
    BundleDescriptor topLevelBundleDesc = (BundleDescriptor) ejb.getEjbBundleDescriptor().getModuleDescriptor().getDescriptor();
    // First get BeanDeploymentArchive for this ejb
    BeanDeploymentArchive bda = getBDAForBeanClass(topLevelBundleDesc, ejb.getEjbClassName());
    WeldBootstrap bootstrap = weldDeployer.getBootstrapForApp(ejb.getEjbBundleDescriptor().getApplication());
    WeldManager weldManager = bootstrap.getManager(bda);
    // when calling _createJCDIInjectionContext
    if (weldManager == null) {
        logger.severe("The reference for weldManager is not available, this is an un-sync state of the container");
        return null;
    }
    org.jboss.weld.ejb.spi.EjbDescriptor<T> ejbDesc = weldManager.getEjbDescriptor(ejb.getName());
    // get or create the ejb's creational context
    if (null != ejbInfo) {
        jcdiCtx = (JCDIInjectionContextImpl<T>) ejbInfo.get(JCDIService.JCDIInjectionContext.class);
    }
    if (null != jcdiCtx) {
        creationalContext = jcdiCtx.getCreationalContext();
    }
    if (null != jcdiCtx && creationalContext == null) {
        // The creational context may have been created by interceptors because they are created first
        // (see createInterceptorInstance below.)
        // And we only want to create the ejb's creational context once or we will have a memory
        // leak there too.
        Bean<T> bean = weldManager.getBean(ejbDesc);
        creationalContext = weldManager.createCreationalContext(bean);
        jcdiCtx.setCreationalContext(creationalContext);
    }
    // Create the injection target
    InjectionTarget<T> it = null;
    if (ejbDesc.isMessageDriven()) {
        // message driven beans are non-contextual and therefore createInjectionTarget is not appropriate
        it = createMdbInjectionTarget(weldManager, ejbDesc);
    } else {
        it = weldManager.createInjectionTarget(ejbDesc);
    }
    if (null != jcdiCtx) {
        jcdiCtx.setInjectionTarget(it);
    }
    // JJS: 7/20/17 We must perform the around_construct interception because Weld does not know about
    // interceptors defined by descriptors.
    WeldCreationalContext<T> weldCreationalContext = (WeldCreationalContext<T>) creationalContext;
    weldCreationalContext.setConstructorInterceptionSuppressed(true);
    JCDIAroundConstructCallback<T> aroundConstructCallback = new JCDIAroundConstructCallback<>(baseContainer, ejbContext);
    weldCreationalContext.registerAroundConstructCallback(aroundConstructCallback);
    if (null != jcdiCtx) {
        jcdiCtx.setJCDIAroundConstructCallback(aroundConstructCallback);
    }
    T beanInstance = instance;
    if (null != jcdiCtx) {
        jcdiCtx.setInstance(beanInstance);
    }
    return jcdiCtx;
// Injection is not performed yet. Separate injectEJBInstance() call is required.
}
Also used : JCDIService(com.sun.enterprise.container.common.spi.JCDIService) EJBContextImpl(com.sun.ejb.containers.EJBContextImpl) WeldBootstrap(org.jboss.weld.bootstrap.WeldBootstrap) javax.enterprise.inject.spi(javax.enterprise.inject.spi) WeldManager(org.jboss.weld.manager.api.WeldManager) BaseContainer(com.sun.ejb.containers.BaseContainer) BundleDescriptor(com.sun.enterprise.deployment.BundleDescriptor) WeldCreationalContext(org.jboss.weld.contexts.WeldCreationalContext) BeanDeploymentArchive(org.jboss.weld.bootstrap.spi.BeanDeploymentArchive)

Aggregations

WeldManager (org.jboss.weld.manager.api.WeldManager)4 WeldBootstrap (org.jboss.weld.bootstrap.WeldBootstrap)2 BeanDeploymentArchive (org.jboss.weld.bootstrap.spi.BeanDeploymentArchive)2 BaseContainer (com.sun.ejb.containers.BaseContainer)1 EJBContextImpl (com.sun.ejb.containers.EJBContextImpl)1 JCDIService (com.sun.enterprise.container.common.spi.JCDIService)1 BundleDescriptor (com.sun.enterprise.deployment.BundleDescriptor)1 Annotation (java.lang.annotation.Annotation)1 Set (java.util.Set)1 Any (javax.enterprise.inject.Any)1 javax.enterprise.inject.spi (javax.enterprise.inject.spi)1 Bean (javax.enterprise.inject.spi.Bean)1 BeanAttributes (javax.enterprise.inject.spi.BeanAttributes)1 BeanManager (javax.enterprise.inject.spi.BeanManager)1 ProcessBeanAttributes (javax.enterprise.inject.spi.ProcessBeanAttributes)1 FilterRegistration (javax.servlet.FilterRegistration)1 JspApplicationContext (javax.servlet.jsp.JspApplicationContext)1 EnhancedAnnotatedType (org.jboss.weld.annotated.enhanced.EnhancedAnnotatedType)1 AbstractClassBean (org.jboss.weld.bean.AbstractClassBean)1 ManagedBean (org.jboss.weld.bean.ManagedBean)1