/** Manages unused conversations */ public OpenEJBLifecycle(final WebBeansContext webBeansContext) { this.webBeansContext = webBeansContext; this.beanManager = webBeansContext.getBeanManagerImpl(); this.deployer = new BeansDeployer(webBeansContext); this.jndiService = webBeansContext.getService(JNDIService.class); this.scannerService = webBeansContext.getScannerService(); this.contextsService = webBeansContext.getContextsService(); }
private void ensureRequestScope() { final Context reqCtx = webBeansContext.getContextsService().getCurrentContext(RequestScoped.class); if (reqCtx == null || !webBeansContext .getContextsService() .getCurrentContext(RequestScoped.class) .isActive()) { requestInitialized(null); EndWebBeansListener.FAKE_REQUEST.set(true); } }
@Override public T get() { if (webBeansContext == null) { webBeansContext = WebBeansContext.currentInstance(); } return (T) SystemInstance.get().getComponent(type); }
public static void initializeServletContext( final ServletContext servletContext, final WebBeansContext context) { if (context == null || !context.getBeanManagerImpl().isInUse()) { return; } final ELAdaptor elAdaptor = context.getService(ELAdaptor.class); final ELResolver resolver = elAdaptor.getOwbELResolver(); // Application is configured as JSP if (context.getOpenWebBeansConfiguration().isJspApplication()) { logger.debug("Application is configured as JSP. Adding EL Resolver."); setJspELFactory(servletContext, resolver); } // Add BeanManager to the 'javax.enterprise.inject.spi.BeanManager' servlet context attribute servletContext.setAttribute(BeanManager.class.getName(), context.getBeanManagerImpl()); }
@Test public void checkOnlyConfiguredExtensionsArePresent() { final Map<?, ?> extensions = Map.class.cast( Reflections.get(WebBeansContext.currentInstance().getExtensionLoader(), "extensions")); assertEquals(1, extensions.size()); assertEquals( ThisTestExtensionWithoutSPIFiles.class, extensions.values().iterator().next().getClass()); }
@Test public void run() { WebBeansFinder.clearInstances(WebBeansUtil.getCurrentClassLoader()); final OpenWebBeansTestLifeCycle testLifecycle = new OpenWebBeansTestLifeCycle(); final WebBeansContext ctx = WebBeansContext.currentInstance(); final OpenWebBeansTestMetaDataDiscoveryService discoveryService = OpenWebBeansTestMetaDataDiscoveryService.class.cast(ctx.getScannerService()); discoveryService.deployClasses(asList(Service.class, ModelAdapter.class)); testLifecycle.startApplication(null); try { Jsonb jsonb = JsonbBuilder.create(); assertEquals("{\"model\":\"5\"}", jsonb.toJson(new Root(new Model(5)))); try { AutoCloseable.class.cast(jsonb).close(); } catch (final Exception e) { fail(e.getMessage()); } } finally { testLifecycle.stopApplication(null); } }
@Override public Enumeration<URL> getResources(final String name) throws IOException { if (!getState().isAvailable()) { return null; } if ("META-INF/services/javax.servlet.ServletContainerInitializer".equals(name)) { final Collection<URL> list = new ArrayList<>(Collections.list(super.getResources(name))); final Iterator<URL> it = list.iterator(); while (it.hasNext()) { final URL next = it.next(); final File file = Files.toFile(next); if (!file.isFile() && NewLoaderLogic.skip(next)) { it.remove(); } } return Collections.enumeration(list); } if ("META-INF/services/javax.websocket.ContainerProvider".equals(name)) { final Collection<URL> list = new ArrayList<>(Collections.list(super.getResources(name))); final Iterator<URL> it = list.iterator(); while (it.hasNext()) { final URL next = it.next(); final File file = Files.toFile(next); if (!file.isFile() && NewLoaderLogic.skip(next)) { it.remove(); } } return Collections.enumeration(list); } if ("META-INF/faces-config.xml".equals(name)) { // mojarra workaround try { if (WebBeansContext.currentInstance() == null && Boolean.parseBoolean( SystemInstance.get().getProperty("tomee.jsf.ignore-owb", "true"))) { final Collection<URL> list = new HashSet<>(Collections.list(super.getResources(name))); final Iterator<URL> it = list.iterator(); while (it.hasNext()) { final String fileName = Files.toFile(it.next()).getName(); if (fileName.startsWith("openwebbeans-" /*jsf|el22*/) && fileName.endsWith(".jar")) { it.remove(); } } return Collections.enumeration(list); } } catch (final Throwable th) { // no-op } } return URLClassLoaderFirst.filterResources(name, super.getResources(name)); }
private static <T> T newInstance(final OpenEjbConfig config, final Class<T> clazz) throws Exception { final WebBeansContext webBeansContext = WebBeansContext.currentInstance(); if (webBeansContext == null) { return clazz.newInstance(); } final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl(); if (!beanManager.isInUse()) { return clazz.newInstance(); } final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz); final InjectionTarget<T> it = beanManager.createInjectionTarget(annotatedType); final CreationalContext<T> context = beanManager.createCreationalContext(null); final T instance = it.produce(context); it.inject(instance, context); it.postConstruct(instance); config.releasables.add(new Releasable<T>(context, it, instance)); return instance; }
@Override public void stopApplication(final Object endObject) { logger.debug("OpenWebBeans Container is stopping."); try { // Fire shut down if (WebappBeanManager.class.isInstance(beanManager)) { WebappBeanManager.class.cast(beanManager).beforeStop(); } webBeansContext.getContextsService().endContext(RequestScoped.class, endObject); webBeansContext.getContextsService().endContext(ConversationScoped.class, endObject); webBeansContext.getContextsService().endContext(SessionScoped.class, endObject); webBeansContext.getContextsService().endContext(ApplicationScoped.class, endObject); webBeansContext.getContextsService().endContext(Singleton.class, endObject); // clean up the EL caches after each request ELContextStore elStore = ELContextStore.getInstance(false); if (elStore != null) { elStore.destroyELContextStore(); } this.beanManager.fireEvent(new BeforeShutdownImpl(), true); // this will now even destroy the ExtensionBeans and other internal stuff this.contextsService.destroy(endObject); // Unbind BeanManager if (jndiService != null) { jndiService.unbind(WebBeansConstants.WEB_BEANS_MANAGER_JNDI_NAME); } // Free all plugin resources ((CdiPlugin) webBeansContext.getPluginLoader().getEjbPlugin()).clearProxies(); webBeansContext.getPluginLoader().shutDown(); // Clear extensions webBeansContext.getExtensionLoader().clear(); // Delete Resolutions Cache beanManager.getInjectionResolver().clearCaches(); // Delete AnnotateTypeCache webBeansContext.getAnnotatedElementFactory().clear(); // After Stop // Clear the resource injection service final ResourceInjectionService injectionServices = webBeansContext.getService(ResourceInjectionService.class); if (injectionServices != null) { injectionServices.clear(); } // Comment out for commit OWB-502 // ContextFactory.cleanUpContextFactory(); CdiAppContextsService.class.cast(contextsService).removeThreadLocals(); WebBeansFinder.clearInstances(WebBeansUtil.getCurrentClassLoader()); // Clear BeanManager this.beanManager.clear(); // Clear singleton list WebBeansFinder.clearInstances(WebBeansUtil.getCurrentClassLoader()); } catch (final Exception e) { logger.error("An error occured while stopping the container.", e); } }
@Override public void startApplication(final Object startupObject) { if (ServletContextEvent.class.isInstance(startupObject)) { startServletContext( ServletContext.class.cast( getServletContext(startupObject))); // TODO: check it is relevant return; } else if (!StartupObject.class.isInstance(startupObject)) { logger.debug("startupObject is not of StartupObject type; ignored"); return; } final StartupObject stuff = (StartupObject) startupObject; final ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); // Initalize Application Context logger.info("OpenWebBeans Container is starting..."); final long begin = System.currentTimeMillis(); try { Thread.currentThread().setContextClassLoader(stuff.getClassLoader()); final AppContext appContext = stuff.getAppContext(); if (stuff.getWebContext() == null) { // do it before any other things to keep our singleton finder working appContext.setWebBeansContext(webBeansContext); } // Load all plugins webBeansContext.getPluginLoader().startUp(); // Get Plugin final CdiPlugin cdiPlugin = (CdiPlugin) webBeansContext.getPluginLoader().getEjbPlugin(); cdiPlugin.setClassLoader(stuff.getClassLoader()); cdiPlugin.setWebBeansContext(webBeansContext); // Configure EJB Deployments cdiPlugin.configureDeployments(stuff.getBeanContexts()); // Resournce Injection Service final CdiResourceInjectionService injectionService = (CdiResourceInjectionService) webBeansContext.getService(ResourceInjectionService.class); // todo use startupObject allDeployments to find Comp in priority (otherwise we can keep N // times comps and loose time at injection time injectionService.setAppContext( stuff.getAppContext(), stuff.getBeanContexts() != null ? stuff.getBeanContexts() : Collections.<BeanContext>emptyList()); // Deploy the beans CdiScanner cdiScanner = null; try { // Scanning process logger.debug("Scanning classpaths for beans artifacts."); if (CdiScanner.class.isInstance(scannerService)) { cdiScanner = CdiScanner.class.cast(scannerService); cdiScanner.setContext(webBeansContext); cdiScanner.init(startupObject); } else { cdiScanner = new CdiScanner(); cdiScanner.setContext(webBeansContext); cdiScanner.init(startupObject); } // Scan this.scannerService.scan(); // just to let us write custom CDI Extension using our internals easily CURRENT_APP_INFO.set(stuff.getAppInfo()); addInternalBeans(); // before next event which can register custom beans (JAX-RS) SystemInstance.get().fireEvent(new WebBeansContextBeforeDeploy(webBeansContext)); // Deploy bean from XML. Also configures deployments, interceptors, decorators. deployer.deploy(scannerService); contextsService.init( startupObject); // fire app event and also starts SingletonContext and // ApplicationContext } catch (final Exception e1) { SystemInstance.get() .getComponent(Assembler.class) .logger .error("CDI Beans module deployment failed", e1); throw new OpenEJBRuntimeException(e1); } finally { CURRENT_APP_INFO.remove(); } final Collection<Class<?>> ejbs = new ArrayList<>(stuff.getBeanContexts().size()); for (final BeanContext bc : stuff.getBeanContexts()) { final CdiEjbBean cdiEjbBean = bc.get(CdiEjbBean.class); if (cdiEjbBean == null) { continue; } ejbs.add(bc.getManagedClass()); if (AbstractProducer.class.isInstance(cdiEjbBean)) { AbstractProducer.class .cast(cdiEjbBean) .defineInterceptorStack( cdiEjbBean, cdiEjbBean.getAnnotatedType(), cdiEjbBean.getWebBeansContext()); } bc.mergeOWBAndOpenEJBInfo(); bc.set( InterceptorResolutionService.BeanInterceptorInfo.class, InjectionTargetImpl.class.cast(cdiEjbBean.getInjectionTarget()).getInterceptorInfo()); cdiEjbBean.initInternals(); } // Start actual starting on sub-classes if (beanManager instanceof WebappBeanManager) { ((WebappBeanManager) beanManager).afterStart(); } for (final Class<?> clazz : cdiScanner.getStartupClasses()) { if (ejbs.contains(clazz)) { continue; } starts(beanManager, clazz); } } finally { Thread.currentThread().setContextClassLoader(oldCl); // cleanup threadlocal used to enrich cdi context manually OptimizedLoaderService.ADDITIONAL_EXTENSIONS.remove(); } logger.info( "OpenWebBeans Container has started, it took {0} ms.", Long.toString(System.currentTimeMillis() - begin)); }
/** * Default constructor * * @param webBeansContext the OWB context */ public BeginWebBeansListener(WebBeansContext webBeansContext) { this.webBeansContext = webBeansContext; this.failoverService = this.webBeansContext.getService(FailOverService.class); this.contextKey = "org.apache.tomee.catalina.WebBeansListener@" + webBeansContext.hashCode(); }
@Override public void init(final Object object) { if (!(object instanceof StartupObject)) { return; } final StartupObject startupObject = (StartupObject) object; final AppInfo appInfo = startupObject.getAppInfo(); final ClassLoader classLoader = startupObject.getClassLoader(); final ClassLoaderComparator comparator; if (classLoader instanceof ClassLoaderComparator) { comparator = (ClassLoaderComparator) classLoader; } else { comparator = new DefaultClassLoaderComparator(classLoader); } final WebBeansContext webBeansContext = startupObject.getWebBeansContext(); final AlternativesManager alternativesManager = webBeansContext.getAlternativesManager(); final DecoratorsManager decoratorsManager = webBeansContext.getDecoratorsManager(); final InterceptorsManager interceptorsManager = webBeansContext.getInterceptorsManager(); final AnnotationManager annotationManager = webBeansContext.getAnnotationManager(); for (final EjbJarInfo ejbJar : appInfo.ejbJars) { final BeansInfo beans = ejbJar.beans; if (beans == null) { continue; } if (startupObject.isFromWebApp()) { // deploy only the related ejbmodule if (!ejbJar.moduleId.equals(startupObject.getWebContext().getId())) { continue; } } else if (ejbJar.webapp && !appInfo.webAppAlone) { continue; } // fail fast final StringBuilder errors = new StringBuilder("You can't define multiple times the same class in beans.xml: "); if (addErrors(errors, "alternative classes", beans.duplicatedAlternativeClasses) || addErrors(errors, "alternative stereotypes", beans.duplicatedAlternativeStereotypes) || addErrors(errors, "decorators", beans.duplicatedDecorators) || addErrors(errors, "interceptors", beans.duplicatedInterceptors)) { throw new WebBeansConfigurationException(errors.toString()); } // no more need of errors so clear them beans.duplicatedAlternativeStereotypes.clear(); beans.duplicatedAlternativeClasses.clear(); beans.duplicatedDecorators.clear(); beans.duplicatedInterceptors.clear(); for (final String className : beans.interceptors) { final Class<?> clazz = load(PropertyPlaceHolderHelper.simpleValue(className), classLoader); if (clazz != null) { // TODO: Move check to validation phase if (AnnotationUtil.hasAnnotation(clazz.getDeclaredAnnotations(), Interceptor.class) && !annotationManager.hasInterceptorBindingMetaAnnotation( clazz.getDeclaredAnnotations())) { throw new WebBeansConfigurationException( "Interceptor class : " + clazz.getName() + " must have at least one @InterceptorBindingType"); } if (!interceptorsManager.isInterceptorClassEnabled(clazz)) { interceptorsManager.addEnabledInterceptorClass(clazz); classes.add(clazz); } /* else { don't do it, check is done when we know the beans.xml path --> org.apache.openejb.config.DeploymentLoader.addBeansXmls throw new WebBeansConfigurationException("Interceptor class : " + clazz.getName() + " is already defined"); }*/ } else if (shouldThrowCouldNotLoadException(startupObject)) { throw new WebBeansConfigurationException( "Could not load interceptor class: " + className); } } for (final String className : beans.decorators) { final Class<?> clazz = load(PropertyPlaceHolderHelper.simpleValue(className), classLoader); if (clazz != null) { if (!decoratorsManager.isDecoratorEnabled(clazz)) { decoratorsManager.addEnabledDecorator(clazz); classes.add(clazz); } // same than interceptors regarding throw new WebBeansConfigurationException("Decorator // class : " + clazz.getName() + " is already defined"); } else if (shouldThrowCouldNotLoadException(startupObject)) { throw new WebBeansConfigurationException("Could not load decorator class: " + className); } } for (final String className : beans.alternativeStereotypes) { final Class<?> clazz = load(PropertyPlaceHolderHelper.simpleValue(className), classLoader); if (clazz != null) { alternativesManager.addStereoTypeAlternative(clazz, null, null); classes.add(clazz); } else if (shouldThrowCouldNotLoadException(startupObject)) { throw new WebBeansConfigurationException( "Could not load alternativeStereotype class: " + className); } } for (final String className : beans.alternativeClasses) { final Class<?> clazz = load(PropertyPlaceHolderHelper.simpleValue(className), classLoader); if (clazz != null) { alternativesManager.addClazzAlternative(clazz, null, null); classes.add(clazz); } else if (shouldThrowCouldNotLoadException(startupObject)) { throw new WebBeansConfigurationException( "Could not load alternative class: " + className); } } // here for ears we need to skip classes in the parent classloader final ClassLoader scl = ClassLoader.getSystemClassLoader(); final boolean filterByClassLoader = "true".equals(SystemInstance.get().getProperty(OPENEJB_CDI_FILTER_CLASSLOADER, "true")); final Iterator<String> it = beans.managedClasses.iterator(); while (it.hasNext()) { process(classLoader, it, startupObject, comparator, scl, filterByClassLoader); } final Collection<String> otherClasses = ADDITIONAL_CLASSES.get(); if (otherClasses != null) { final Iterator<String> it2 = otherClasses.iterator(); while (it2.hasNext()) { process(classLoader, it2, startupObject, comparator, scl, filterByClassLoader); } } if (startupObject.getBeanContexts() != null) { // ensure ejbs are in managed beans otherwise they will not be deployed in CDI for (final BeanContext bc : startupObject.getBeanContexts()) { final String name = bc.getBeanClass().getName(); if (BeanContext.Comp.class.getName().equals(name)) { continue; } final Class<?> load = load(name, classLoader); if (load != null && !classes.contains(load)) { classes.add(load); } } } addContainerCdiClasses(classLoader, appInfo, ejbJar); } }