Search in sources :

Example 1 with ServletContainerService

use of org.wildfly.extension.undertow.ServletContainerService in project wildfly by wildfly.

the class UndertowDeploymentInfoService method createServletConfig.

private DeploymentInfo createServletConfig() throws StartException {
    final ComponentRegistry componentRegistry = this.componentRegistry.get();
    try {
        if (!mergedMetaData.isMetadataComplete()) {
            mergedMetaData.resolveAnnotations();
        }
        mergedMetaData.resolveRunAs();
        final DeploymentInfo d = new DeploymentInfo();
        d.setContextPath(contextPath);
        if (mergedMetaData.getDescriptionGroup() != null) {
            d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName());
        }
        d.setDeploymentName(deploymentName);
        d.setHostName(host.get().getName());
        final ServletContainerService servletContainer = container.get();
        try {
            // TODO: make the caching limits configurable
            List<String> externalOverlays = mergedMetaData.getOverlays();
            ResourceManager resourceManager = new ServletResourceManager(deploymentRoot, overlays, explodedDeployment, mergedMetaData.isSymbolicLinkingEnabled(), servletContainer.isDisableFileWatchService(), externalOverlays);
            resourceManager = new CachingResourceManager(servletContainer.getFileCacheMetadataSize(), servletContainer.getFileCacheMaxFileSize(), servletContainer.getBufferCache(), resourceManager, servletContainer.getFileCacheTimeToLive() == null ? (explodedDeployment ? 2000 : -1) : servletContainer.getFileCacheTimeToLive());
            if (externalResources != null && !externalResources.isEmpty()) {
                // TODO: we don't cache external deployments, as they are intended for development use
                // should be make this configurable or something?
                List<ResourceManager> delegates = new ArrayList<>();
                for (File resource : externalResources) {
                    delegates.add(new FileResourceManager(resource.getCanonicalFile(), 1024, true, mergedMetaData.isSymbolicLinkingEnabled(), "/"));
                }
                delegates.add(resourceManager);
                resourceManager = new DelegatingResourceManager(delegates);
            }
            d.setResourceManager(resourceManager);
        } catch (IOException e) {
            throw new StartException(e);
        }
        d.setTempDir(tempDir);
        d.setClassLoader(module.getClassLoader());
        final String servletVersion = mergedMetaData.getServletVersion();
        if (servletVersion != null) {
            d.setMajorVersion(Integer.parseInt(servletVersion.charAt(0) + ""));
            d.setMinorVersion(Integer.parseInt(servletVersion.charAt(2) + ""));
        } else {
            d.setMajorVersion(3);
            d.setMinorVersion(1);
        }
        d.setDefaultCookieVersion(servletContainer.getDefaultCookieVersion());
        // in most cases flush just hurts performance for no good reason
        d.setIgnoreFlush(servletContainer.isIgnoreFlush());
        // controls initialization of filters on start of application
        d.setEagerFilterInit(servletContainer.isEagerFilterInit());
        d.setAllowNonStandardWrappers(servletContainer.isAllowNonStandardWrappers());
        d.setServletStackTraces(servletContainer.getStackTraces());
        d.setDisableCachingForSecuredPages(servletContainer.isDisableCachingForSecuredPages());
        if (servletContainer.isDisableSessionIdReuse()) {
            d.setCheckOtherSessionManagers(false);
        }
        if (servletContainer.getSessionPersistenceManager() != null) {
            d.setSessionPersistenceManager(servletContainer.getSessionPersistenceManager());
        }
        // for 2.2 apps we do not require a leading / in path mappings
        boolean is22OrOlder;
        if (d.getMajorVersion() == 1) {
            is22OrOlder = true;
        } else if (d.getMajorVersion() == 2) {
            is22OrOlder = d.getMinorVersion() < 3;
        } else {
            is22OrOlder = false;
        }
        JSPConfig jspConfig = servletContainer.getJspConfig();
        final Set<String> seenMappings = new HashSet<>();
        // default Jakarta Server Pages servlet
        final ServletInfo jspServlet = jspConfig != null ? jspConfig.createJSPServletInfo() : null;
        if (jspServlet != null) {
            // this would be null if jsp support is disabled
            HashMap<String, JspPropertyGroup> propertyGroups = createJspConfig(mergedMetaData);
            JspServletBuilder.setupDeployment(d, propertyGroups, tldInfo, new UndertowJSPInstanceManager(new CachingWebInjectionContainer(module.getClassLoader(), componentRegistry)));
            if (mergedMetaData.getJspConfig() != null) {
                Collection<JspPropertyGroup> values = new LinkedHashSet<>(propertyGroups.values());
                d.setJspConfigDescriptor(new JspConfigDescriptorImpl(tldInfo.values(), values));
            }
            d.addServlet(jspServlet);
            final Set<String> jspPropertyGroupMappings = propertyGroups.keySet();
            for (final String mapping : jspPropertyGroupMappings) {
                if (!jspServlet.getMappings().contains(mapping)) {
                    jspServlet.addMapping(mapping);
                }
            }
            seenMappings.addAll(jspPropertyGroupMappings);
            // setup Jakarta Server Pages application context initializing listener
            d.addListener(new ListenerInfo(JspInitializationListener.class));
            d.addServletContextAttribute(JspInitializationListener.CONTEXT_KEY, expressionFactoryWrappers);
        }
        d.setClassIntrospecter(new ComponentClassIntrospector(componentRegistry));
        final Map<String, List<ServletMappingMetaData>> servletMappings = new HashMap<>();
        if (mergedMetaData.getExecutorName() != null) {
            d.setExecutor(executorsByName.get(mergedMetaData.getExecutorName()).get());
        }
        Boolean proactiveAuthentication = mergedMetaData.getProactiveAuthentication();
        if (proactiveAuthentication == null) {
            proactiveAuthentication = container.get().isProactiveAuth();
        }
        d.setAuthenticationMode(proactiveAuthentication ? AuthenticationMode.PRO_ACTIVE : AuthenticationMode.CONSTRAINT_DRIVEN);
        if (servletExtensions != null) {
            for (ServletExtension extension : servletExtensions) {
                d.addServletExtension(extension);
            }
        }
        if (mergedMetaData.getServletMappings() != null) {
            for (final ServletMappingMetaData mapping : mergedMetaData.getServletMappings()) {
                List<ServletMappingMetaData> list = servletMappings.get(mapping.getServletName());
                if (list == null) {
                    servletMappings.put(mapping.getServletName(), list = new ArrayList<>());
                }
                list.add(mapping);
            }
        }
        if (jspServlet != null) {
            // we need to clear the file attribute if it is set (WFLY-4106)
            jspServlet.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(null));
            List<ServletMappingMetaData> list = servletMappings.get(jspServlet.getName());
            if (list != null && !list.isEmpty()) {
                for (final ServletMappingMetaData mapping : list) {
                    for (String urlPattern : mapping.getUrlPatterns()) {
                        jspServlet.addMapping(urlPattern);
                    }
                    seenMappings.addAll(mapping.getUrlPatterns());
                }
            }
        }
        for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) {
            final ServletInfo s;
            if (servlet.getJspFile() != null) {
                s = new ServletInfo(servlet.getName(), JspServlet.class);
                s.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(servlet.getJspFile()));
            } else {
                if (servlet.getServletClass() == null) {
                    if (DEFAULT_SERVLET_NAME.equals(servlet.getName())) {
                        s = new ServletInfo(servlet.getName(), DefaultServlet.class);
                    } else {
                        throw UndertowLogger.ROOT_LOGGER.servletClassNotDefined(servlet.getServletName());
                    }
                } else {
                    Class<? extends Servlet> servletClass = (Class<? extends Servlet>) module.getClassLoader().loadClass(servlet.getServletClass());
                    ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(servletClass, true);
                    if (creator != null) {
                        InstanceFactory<Servlet> factory = createInstanceFactory(creator);
                        s = new ServletInfo(servlet.getName(), servletClass, factory);
                    } else {
                        s = new ServletInfo(servlet.getName(), servletClass);
                    }
                }
            }
            s.setAsyncSupported(servlet.isAsyncSupported()).setJspFile(servlet.getJspFile()).setEnabled(servlet.isEnabled());
            if (servlet.getRunAs() != null) {
                s.setRunAs(servlet.getRunAs().getRoleName());
            }
            if (servlet.getLoadOnStartupSet()) {
                // todo why not cleanup api and just use int everywhere
                s.setLoadOnStartup(servlet.getLoadOnStartupInt());
            }
            if (servlet.getExecutorName() != null) {
                s.setExecutor(executorsByName.get(servlet.getExecutorName()).get());
            }
            handleServletMappings(is22OrOlder, seenMappings, servletMappings, s);
            if (servlet.getInitParam() != null) {
                for (ParamValueMetaData initParam : servlet.getInitParam()) {
                    if (!s.getInitParams().containsKey(initParam.getParamName())) {
                        s.addInitParam(initParam.getParamName(), initParam.getParamValue());
                    }
                }
            }
            if (servlet.getServletSecurity() != null) {
                ServletSecurityInfo securityInfo = new ServletSecurityInfo();
                s.setServletSecurityInfo(securityInfo);
                securityInfo.setEmptyRoleSemantic(servlet.getServletSecurity().getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT).setTransportGuaranteeType(transportGuaranteeType(servlet.getServletSecurity().getTransportGuarantee())).addRolesAllowed(servlet.getServletSecurity().getRolesAllowed());
                if (servlet.getServletSecurity().getHttpMethodConstraints() != null) {
                    for (HttpMethodConstraintMetaData method : servlet.getServletSecurity().getHttpMethodConstraints()) {
                        securityInfo.addHttpMethodSecurityInfo(new HttpMethodSecurityInfo().setEmptyRoleSemantic(method.getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT).setTransportGuaranteeType(transportGuaranteeType(method.getTransportGuarantee())).addRolesAllowed(method.getRolesAllowed()).setMethod(method.getMethod()));
                    }
                }
            }
            if (servlet.getSecurityRoleRefs() != null) {
                for (final SecurityRoleRefMetaData ref : servlet.getSecurityRoleRefs()) {
                    s.addSecurityRoleRef(ref.getRoleName(), ref.getRoleLink());
                }
            }
            if (servlet.getMultipartConfig() != null) {
                MultipartConfigMetaData mp = servlet.getMultipartConfig();
                s.setMultipartConfig(Servlets.multipartConfig(mp.getLocation(), mp.getMaxFileSize(), mp.getMaxRequestSize(), mp.getFileSizeThreshold()));
            }
            d.addServlet(s);
        }
        if (jspServlet != null) {
            if (!seenMappings.contains("*.jsp")) {
                jspServlet.addMapping("*.jsp");
            }
            if (!seenMappings.contains("*.jspx")) {
                jspServlet.addMapping("*.jspx");
            }
        }
        // we explicitly add the default servlet, to allow it to be mapped
        if (!mergedMetaData.getServlets().containsKey(ServletPathMatches.DEFAULT_SERVLET_NAME)) {
            ServletInfo defaultServlet = Servlets.servlet(DEFAULT_SERVLET_NAME, DefaultServlet.class);
            handleServletMappings(is22OrOlder, seenMappings, servletMappings, defaultServlet);
            d.addServlet(defaultServlet);
        }
        if (servletContainer.getDirectoryListingEnabled() != null) {
            ServletInfo defaultServlet = d.getServlets().get(DEFAULT_SERVLET_NAME);
            defaultServlet.addInitParam(DefaultServlet.DIRECTORY_LISTING, servletContainer.getDirectoryListingEnabled().toString());
        }
        if (mergedMetaData.getFilters() != null) {
            for (final FilterMetaData filter : mergedMetaData.getFilters()) {
                Class<? extends Filter> filterClass = (Class<? extends Filter>) module.getClassLoader().loadClass(filter.getFilterClass());
                ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(filterClass);
                FilterInfo f;
                if (creator != null) {
                    InstanceFactory<Filter> instanceFactory = createInstanceFactory(creator);
                    f = new FilterInfo(filter.getName(), filterClass, instanceFactory);
                } else {
                    f = new FilterInfo(filter.getName(), filterClass);
                }
                f.setAsyncSupported(filter.isAsyncSupported());
                d.addFilter(f);
                if (filter.getInitParam() != null) {
                    for (ParamValueMetaData initParam : filter.getInitParam()) {
                        f.addInitParam(initParam.getParamName(), initParam.getParamValue());
                    }
                }
            }
        }
        if (mergedMetaData.getFilterMappings() != null) {
            for (final FilterMappingMetaData mapping : mergedMetaData.getFilterMappings()) {
                if (mapping.getUrlPatterns() != null) {
                    for (String url : mapping.getUrlPatterns()) {
                        if (is22OrOlder && !url.startsWith("*") && !url.startsWith("/")) {
                            url = "/" + url;
                        }
                        if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) {
                            for (DispatcherType dispatcher : mapping.getDispatchers()) {
                                d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.valueOf(dispatcher.name()));
                            }
                        } else {
                            d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.REQUEST);
                        }
                    }
                }
                if (mapping.getServletNames() != null) {
                    for (String servletName : mapping.getServletNames()) {
                        if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) {
                            for (DispatcherType dispatcher : mapping.getDispatchers()) {
                                d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.valueOf(dispatcher.name()));
                            }
                        } else {
                            d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.REQUEST);
                        }
                    }
                }
            }
        }
        if (scisMetaData != null && scisMetaData.getHandlesTypes() != null) {
            for (final ServletContainerInitializer sci : scisMetaData.getScis()) {
                final ImmediateInstanceFactory<ServletContainerInitializer> instanceFactory = new ImmediateInstanceFactory<>(sci);
                d.addServletContainerInitalizer(new ServletContainerInitializerInfo(sci.getClass(), instanceFactory, scisMetaData.getHandlesTypes().get(sci)));
            }
        }
        if (mergedMetaData.getListeners() != null) {
            Set<String> tldListeners = new HashSet<>();
            for (Map.Entry<String, TagLibraryInfo> e : tldInfo.entrySet()) {
                tldListeners.addAll(Arrays.asList(e.getValue().getListeners()));
            }
            for (ListenerMetaData listener : mergedMetaData.getListeners()) {
                addListener(module.getClassLoader(), componentRegistry, d, listener, tldListeners.contains(listener.getListenerClass()));
            }
        }
        if (mergedMetaData.getContextParams() != null) {
            for (ParamValueMetaData param : mergedMetaData.getContextParams()) {
                d.addInitParameter(param.getParamName(), param.getParamValue());
            }
        }
        if (mergedMetaData.getWelcomeFileList() != null && mergedMetaData.getWelcomeFileList().getWelcomeFiles() != null) {
            List<String> welcomeFiles = mergedMetaData.getWelcomeFileList().getWelcomeFiles();
            for (String file : welcomeFiles) {
                if (file.startsWith("/")) {
                    d.addWelcomePages(file.substring(1));
                } else {
                    d.addWelcomePages(file);
                }
            }
        } else {
            d.addWelcomePages("index.html", "index.htm", "index.jsp");
        }
        d.addWelcomePages(servletContainer.getWelcomeFiles());
        if (mergedMetaData.getErrorPages() != null) {
            for (final ErrorPageMetaData page : mergedMetaData.getErrorPages()) {
                final ErrorPage errorPage;
                if (page.getExceptionType() != null && !page.getExceptionType().isEmpty()) {
                    errorPage = new ErrorPage(page.getLocation(), (Class<? extends Throwable>) module.getClassLoader().loadClass(page.getExceptionType()));
                } else if (page.getErrorCode() != null && !page.getErrorCode().isEmpty()) {
                    errorPage = new ErrorPage(page.getLocation(), Integer.parseInt(page.getErrorCode()));
                } else {
                    errorPage = new ErrorPage(page.getLocation());
                }
                d.addErrorPages(errorPage);
            }
        }
        for (Map.Entry<String, String> entry : servletContainer.getMimeMappings().entrySet()) {
            d.addMimeMapping(new MimeMapping(entry.getKey(), entry.getValue()));
        }
        if (mergedMetaData.getMimeMappings() != null) {
            for (final MimeMappingMetaData mapping : mergedMetaData.getMimeMappings()) {
                d.addMimeMapping(new MimeMapping(mapping.getExtension(), mapping.getMimeType()));
            }
        }
        d.setDenyUncoveredHttpMethods(mergedMetaData.getDenyUncoveredHttpMethods() != null);
        Set<String> securityRoleNames = mergedMetaData.getSecurityRoleNames();
        if (mergedMetaData.getSecurityConstraints() != null) {
            for (SecurityConstraintMetaData constraint : mergedMetaData.getSecurityConstraints()) {
                SecurityConstraint securityConstraint = new SecurityConstraint().setTransportGuaranteeType(transportGuaranteeType(constraint.getTransportGuarantee()));
                List<String> roleNames = constraint.getRoleNames();
                if (constraint.getAuthConstraint() == null) {
                    // no auth constraint means we permit the empty roles
                    securityConstraint.setEmptyRoleSemantic(PERMIT);
                } else if (roleNames.size() == 1 && roleNames.contains("*") && securityRoleNames.contains("*")) {
                    // AS7-6932 - Trying to do a * to * mapping which JBossWeb passed through, for Undertow enable
                    // authentication only mode.
                    // TODO - AS7-6933 - Revisit workaround added to allow switching between JBoss Web and Undertow.
                    securityConstraint.setEmptyRoleSemantic(AUTHENTICATE);
                } else {
                    securityConstraint.addRolesAllowed(roleNames);
                }
                if (constraint.getResourceCollections() != null) {
                    for (final WebResourceCollectionMetaData resourceCollection : constraint.getResourceCollections()) {
                        securityConstraint.addWebResourceCollection(new WebResourceCollection().addHttpMethods(resourceCollection.getHttpMethods()).addHttpMethodOmissions(resourceCollection.getHttpMethodOmissions()).addUrlPatterns(resourceCollection.getUrlPatterns()));
                    }
                }
                d.addSecurityConstraint(securityConstraint);
            }
        }
        final LoginConfigMetaData loginConfig = mergedMetaData.getLoginConfig();
        if (loginConfig != null) {
            List<AuthMethodConfig> authMethod = authMethod(loginConfig.getAuthMethod());
            if (loginConfig.getFormLoginConfig() != null) {
                d.setLoginConfig(new LoginConfig(loginConfig.getRealmName(), loginConfig.getFormLoginConfig().getLoginPage(), loginConfig.getFormLoginConfig().getErrorPage()));
            } else {
                d.setLoginConfig(new LoginConfig(loginConfig.getRealmName()));
            }
            for (AuthMethodConfig method : authMethod) {
                d.getLoginConfig().addLastAuthMethod(method);
            }
        }
        d.addSecurityRoles(mergedMetaData.getSecurityRoleNames());
        Map<String, Set<String>> principalVersusRolesMap = mergedMetaData.getPrincipalVersusRolesMap();
        if (isElytronActive()) {
            Map<String, RunAsIdentityMetaData> runAsIdentityMap = mergedMetaData.getRunAsIdentity();
            applyElytronSecurity(d, runAsIdentityMap::get);
        } else {
            if (securityDomain != null) {
                throw UndertowLogger.ROOT_LOGGER.legacySecurityUnsupported();
            }
        }
        if (principalVersusRolesMap != null) {
            for (Map.Entry<String, Set<String>> entry : principalVersusRolesMap.entrySet()) {
                d.addPrincipalVsRoleMappings(entry.getKey(), entry.getValue());
            }
        }
        // Setup an deployer configured ServletContext attributes
        if (attributes != null) {
            for (ServletContextAttribute attribute : attributes) {
                d.addServletContextAttribute(attribute.getName(), attribute.getValue());
            }
        }
        // now setup websockets if they are enabled
        if (servletContainer.isWebsocketsEnabled() && webSocketDeploymentInfo != null) {
            webSocketDeploymentInfo.setBuffers(servletContainer.getWebsocketsBufferPool());
            webSocketDeploymentInfo.setWorker(servletContainer.getWebsocketsWorker());
            webSocketDeploymentInfo.setDispatchToWorkerThread(servletContainer.isDispatchWebsocketInvocationToWorker());
            if (servletContainer.isPerMessageDeflate()) {
                PerMessageDeflateHandshake perMessageDeflate = new PerMessageDeflateHandshake(false, servletContainer.getDeflaterLevel());
                webSocketDeploymentInfo.addExtension(perMessageDeflate);
            }
            final AtomicReference<ServerActivity> serverActivity = new AtomicReference<>();
            webSocketDeploymentInfo.addListener(wsc -> {
                serverActivity.set(new ServerActivity() {

                    @Override
                    public void preSuspend(ServerActivityCallback listener) {
                        listener.done();
                    }

                    @Override
                    public void suspended(final ServerActivityCallback listener) {
                        if (wsc.getConfiguredServerEndpoints().isEmpty()) {
                            // TODO: remove this once undertow bug fix is upstream
                            listener.done();
                            return;
                        }
                        wsc.pause(new ServerWebSocketContainer.PauseListener() {

                            @Override
                            public void paused() {
                                listener.done();
                            }

                            @Override
                            public void resumed() {
                            }
                        });
                    }

                    @Override
                    public void resume() {
                        wsc.resume();
                    }
                });
                suspendController.get().registerActivity(serverActivity.get());
            });
            ServletContextListener sl = new ServletContextListener() {

                @Override
                public void contextInitialized(ServletContextEvent sce) {
                }

                @Override
                public void contextDestroyed(ServletContextEvent sce) {
                    final ServerActivity activity = serverActivity.get();
                    if (activity != null) {
                        suspendController.get().unRegisterActivity(activity);
                    }
                }
            };
            d.addListener(new ListenerInfo(sl.getClass(), new ImmediateInstanceFactory<EventListener>(sl)));
            d.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo);
        }
        if (mergedMetaData.getLocalEncodings() != null && mergedMetaData.getLocalEncodings().getMappings() != null) {
            for (LocaleEncodingMetaData locale : mergedMetaData.getLocalEncodings().getMappings()) {
                d.addLocaleCharsetMapping(locale.getLocale(), locale.getEncoding());
            }
        }
        if (predicatedHandlers != null && !predicatedHandlers.isEmpty()) {
            d.addOuterHandlerChainWrapper(new RewriteCorrectingHandlerWrappers.PostWrapper());
            d.addOuterHandlerChainWrapper(new HandlerWrapper() {

                @Override
                public HttpHandler wrap(HttpHandler handler) {
                    return Handlers.predicates(predicatedHandlers, handler);
                }
            });
            d.addOuterHandlerChainWrapper(new RewriteCorrectingHandlerWrappers.PreWrapper());
        }
        if (mergedMetaData.getDefaultEncoding() != null) {
            d.setDefaultEncoding(mergedMetaData.getDefaultEncoding());
        } else if (servletContainer.getDefaultEncoding() != null) {
            d.setDefaultEncoding(servletContainer.getDefaultEncoding());
        }
        d.setCrawlerSessionManagerConfig(servletContainer.getCrawlerSessionManagerConfig());
        d.setPreservePathOnForward(servletContainer.isPreservePathOnForward());
        return d;
    } catch (ClassNotFoundException e) {
        throw new StartException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) ServletInfo(io.undertow.servlet.api.ServletInfo) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) ManagedReferenceFactory(org.jboss.as.naming.ManagedReferenceFactory) MultipartConfigMetaData(org.jboss.metadata.web.spec.MultipartConfigMetaData) DefaultServlet(io.undertow.servlet.handlers.DefaultServlet) DispatcherType(org.jboss.metadata.web.spec.DispatcherType) HttpHandler(io.undertow.server.HttpHandler) JSPConfig(org.wildfly.extension.undertow.JSPConfig) ServerActivity(org.jboss.as.server.suspend.ServerActivity) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) WebResourceCollectionMetaData(org.jboss.metadata.web.spec.WebResourceCollectionMetaData) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) HandlerWrapper(io.undertow.server.HandlerWrapper) ServletContextAttribute(org.jboss.as.web.common.ServletContextAttribute) SecurityConstraintMetaData(org.jboss.metadata.web.spec.SecurityConstraintMetaData) FileResourceManager(io.undertow.server.handlers.resource.FileResourceManager) ListenerMetaData(org.jboss.metadata.web.spec.ListenerMetaData) DefaultServlet(io.undertow.servlet.handlers.DefaultServlet) Servlet(javax.servlet.Servlet) JspServlet(org.apache.jasper.servlet.JspServlet) CachingResourceManager(io.undertow.server.handlers.resource.CachingResourceManager) StartException(org.jboss.msc.service.StartException) FilterInfo(io.undertow.servlet.api.FilterInfo) CachingWebInjectionContainer(org.jboss.as.web.common.CachingWebInjectionContainer) LoginConfigMetaData(org.jboss.metadata.web.spec.LoginConfigMetaData) ServletContainerInitializerInfo(io.undertow.servlet.api.ServletContainerInitializerInfo) FilterMetaData(org.jboss.metadata.web.spec.FilterMetaData) ServletContainerService(org.wildfly.extension.undertow.ServletContainerService) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) HttpMethodSecurityInfo(io.undertow.servlet.api.HttpMethodSecurityInfo) LocaleEncodingMetaData(org.jboss.metadata.web.spec.LocaleEncodingMetaData) ImmediateInstanceFactory(io.undertow.servlet.util.ImmediateInstanceFactory) ServerActivityCallback(org.jboss.as.server.suspend.ServerActivityCallback) LinkedHashSet(java.util.LinkedHashSet) WebResourceCollection(io.undertow.servlet.api.WebResourceCollection) ErrorPage(io.undertow.servlet.api.ErrorPage) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ServletContextListener(javax.servlet.ServletContextListener) JspPropertyGroup(org.apache.jasper.deploy.JspPropertyGroup) AuthMethodConfig(io.undertow.servlet.api.AuthMethodConfig) ArrayList(java.util.ArrayList) List(java.util.List) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) FilterMappingMetaData(org.jboss.metadata.web.spec.FilterMappingMetaData) ParamValueMetaData(org.jboss.metadata.javaee.spec.ParamValueMetaData) ErrorPageMetaData(org.jboss.metadata.web.spec.ErrorPageMetaData) ResourceManager(io.undertow.server.handlers.resource.ResourceManager) CachingResourceManager(io.undertow.server.handlers.resource.CachingResourceManager) FileResourceManager(io.undertow.server.handlers.resource.FileResourceManager) MimeMappingMetaData(org.jboss.metadata.web.spec.MimeMappingMetaData) ServletMappingMetaData(org.jboss.metadata.web.spec.ServletMappingMetaData) ListenerInfo(io.undertow.servlet.api.ListenerInfo) File(java.io.File) VirtualFile(org.jboss.vfs.VirtualFile) ServletSecurityInfo(io.undertow.servlet.api.ServletSecurityInfo) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) SecurityConstraint(io.undertow.servlet.api.SecurityConstraint) RunAsIdentityMetaData(org.jboss.metadata.javaee.jboss.RunAsIdentityMetaData) LoginConfig(io.undertow.servlet.api.LoginConfig) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) TagLibraryInfo(org.apache.jasper.deploy.TagLibraryInfo) MimeMapping(io.undertow.servlet.api.MimeMapping) JspServlet(org.apache.jasper.servlet.JspServlet) HttpMethodConstraintMetaData(org.jboss.metadata.web.spec.HttpMethodConstraintMetaData) SecurityRoleRefMetaData(org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData) ComponentRegistry(org.jboss.as.ee.component.ComponentRegistry) Filter(javax.servlet.Filter) PerMessageDeflateHandshake(io.undertow.websockets.extensions.PerMessageDeflateHandshake) ServletExtension(io.undertow.servlet.ServletExtension) ServletContextEvent(javax.servlet.ServletContextEvent)

Example 2 with ServletContainerService

use of org.wildfly.extension.undertow.ServletContainerService in project wildfly by wildfly.

the class UndertowDeploymentProcessor method processDeployment.

private void processDeployment(final WarMetaData warMetaData, final DeploymentUnit deploymentUnit, final ServiceTarget serviceTarget, final String deploymentName, final String hostName, final String serverInstanceName, final boolean isDefaultWebModule) throws DeploymentUnitProcessingException {
    ResourceRoot deploymentResourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
    final VirtualFile deploymentRoot = deploymentResourceRoot.getRoot();
    final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
    if (module == null) {
        throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failedToResolveModule(deploymentUnit));
    }
    final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData();
    final List<SetupAction> setupActions = deploymentUnit.getAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS);
    CapabilityServiceSupport capabilitySupport = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
    ScisMetaData scisMetaData = deploymentUnit.getAttachment(ScisMetaData.ATTACHMENT_KEY);
    final Set<ServiceName> dependentComponents = new HashSet<>();
    // see AS7-2077
    // basically we want to ignore components that have failed for whatever reason
    // if they are important they will be picked up when the web deployment actually starts
    final List<ServiceName> components = deploymentUnit.getAttachmentList(WebComponentDescription.WEB_COMPONENTS);
    final Set<ServiceName> failed = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.FAILED_COMPONENTS);
    for (final ServiceName component : components) {
        if (!failed.contains(component)) {
            dependentComponents.add(component);
        }
    }
    String servletContainerName = metaData.getServletContainerName();
    if (servletContainerName == null) {
        servletContainerName = defaultContainer;
    }
    final boolean componentRegistryExists = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.COMPONENT_REGISTRY) != null;
    final ComponentRegistry componentRegistry = componentRegistryExists ? deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.COMPONENT_REGISTRY) : new ComponentRegistry(null);
    final ClassLoader loader = module.getClassLoader();
    final WebInjectionContainer injectionContainer = (metaData.getDistributable() == null) ? new CachingWebInjectionContainer(loader, componentRegistry) : new SimpleWebInjectionContainer(loader, componentRegistry);
    String jaccContextId = metaData.getJaccContextID();
    if (jaccContextId == null) {
        jaccContextId = deploymentUnit.getName();
    }
    if (deploymentUnit.getParent() != null) {
        jaccContextId = deploymentUnit.getParent().getName() + "!" + jaccContextId;
    }
    String pathName = pathNameOfDeployment(deploymentUnit, metaData, isDefaultWebModule);
    final Set<ServiceName> additionalDependencies = new HashSet<>();
    for (final SetupAction setupAction : setupActions) {
        Set<ServiceName> dependencies = setupAction.dependencies();
        if (dependencies != null) {
            additionalDependencies.addAll(dependencies);
        }
    }
    SharedSessionManagerConfig sharedSessionManagerConfig = deploymentUnit.getParent() != null ? deploymentUnit.getParent().getAttachment(SharedSessionManagerConfig.ATTACHMENT_KEY) : null;
    if (!deploymentResourceRoot.isUsePhysicalCodeSource()) {
        try {
            deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY, new ServletContextAttribute(Constants.CODE_SOURCE_ATTRIBUTE_NAME, deploymentRoot.toURL()));
        } catch (MalformedURLException e) {
            throw new DeploymentUnitProcessingException(e);
        }
    }
    deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY, new ServletContextAttribute(Constants.PERMISSION_COLLECTION_ATTRIBUTE_NAME, deploymentUnit.getAttachment(Attachments.MODULE_PERMISSIONS)));
    additionalDependencies.addAll(warMetaData.getAdditionalDependencies());
    try {
        String capability = HostSingleSignOnDefinition.HOST_SSO_CAPABILITY.fromBaseCapability(serverInstanceName, hostName).getName();
        capabilitySupport.getCapabilityRuntimeAPI(capability, Object.class);
        additionalDependencies.add(capabilitySupport.getCapabilityServiceName(capability));
    } catch (CapabilityServiceSupport.NoSuchCapabilityException e) {
    // ignore
    }
    final ServiceName hostServiceName = UndertowService.virtualHostName(serverInstanceName, hostName);
    final ServiceName legacyDeploymentServiceName = UndertowService.deploymentServiceName(serverInstanceName, hostName, pathName);
    final ServiceName deploymentServiceName = UndertowService.deploymentServiceName(deploymentUnit.getServiceName());
    StartupCountdown countDown = deploymentUnit.getAttachment(STARTUP_COUNTDOWN);
    if (countDown != null) {
        deploymentUnit.addToAttachmentList(UndertowAttachments.UNDERTOW_INITIAL_HANDLER_CHAIN_WRAPPERS, handler -> new ComponentStartupCountdownHandler(handler, countDown));
    }
    String securityDomain = deploymentUnit.getAttachment(UndertowAttachments.RESOLVED_SECURITY_DOMAIN);
    TldsMetaData tldsMetaData = deploymentUnit.getAttachment(TldsMetaData.ATTACHMENT_KEY);
    final ServiceName deploymentInfoServiceName = deploymentServiceName.append(UndertowDeploymentInfoService.SERVICE_NAME);
    final ServiceName legacyDeploymentInfoServiceName = legacyDeploymentServiceName.append(UndertowDeploymentInfoService.SERVICE_NAME);
    final ServiceBuilder<?> udisBuilder = serviceTarget.addService(deploymentInfoServiceName);
    final Consumer<DeploymentInfo> diConsumer = udisBuilder.provides(deploymentInfoServiceName, legacyDeploymentInfoServiceName);
    final Supplier<UndertowService> usSupplier = udisBuilder.requires(UndertowService.UNDERTOW);
    final Supplier<SessionManagerFactory> smfSupplier;
    final Supplier<SessionIdentifierCodec> sicSupplier;
    final Supplier<ServletContainerService> scsSupplier = udisBuilder.requires(UndertowService.SERVLET_CONTAINER.append(servletContainerName));
    final Supplier<ComponentRegistry> crSupplier = componentRegistryExists ? udisBuilder.requires(ComponentRegistry.serviceName(deploymentUnit)) : new Supplier<ComponentRegistry>() {

        @Override
        public ComponentRegistry get() {
            return componentRegistry;
        }
    };
    final Supplier<Host> hostSupplier = udisBuilder.requires(hostServiceName);
    Supplier<ControlPoint> cpSupplier = null;
    final Supplier<SuspendController> scSupplier = udisBuilder.requires(capabilitySupport.getCapabilityServiceName(Capabilities.REF_SUSPEND_CONTROLLER));
    final Supplier<ServerEnvironment> serverEnvSupplier = udisBuilder.requires(ServerEnvironmentService.SERVICE_NAME);
    Supplier<SecurityDomain> sdSupplier = null;
    Supplier<HttpServerAuthenticationMechanismFactory> mechanismFactorySupplier = null;
    Supplier<BiFunction> bfSupplier = null;
    for (final ServiceName additionalDependency : additionalDependencies) {
        udisBuilder.requires(additionalDependency);
    }
    final SecurityMetaData securityMetaData = deploymentUnit.getAttachment(ATTACHMENT_KEY);
    if (isVirtualDomainRequired(deploymentUnit) || isVirtualMechanismFactoryRequired(deploymentUnit)) {
        sdSupplier = udisBuilder.requires(securityMetaData.getSecurityDomain());
    } else if (securityDomain != null) {
        if (mappedSecurityDomain.test(securityDomain)) {
            bfSupplier = udisBuilder.requires(deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT).getCapabilityServiceName(Capabilities.CAPABILITY_APPLICATION_SECURITY_DOMAIN, securityDomain));
        } else {
            throw ROOT_LOGGER.deploymentConfiguredForLegacySecurity();
        }
    }
    if (isVirtualMechanismFactoryRequired(deploymentUnit)) {
        if (securityMetaData instanceof AdvancedSecurityMetaData) {
            mechanismFactorySupplier = udisBuilder.requires(((AdvancedSecurityMetaData) securityMetaData).getHttpServerAuthenticationMechanismFactory());
        }
    }
    if (RequestControllerActivationMarker.isRequestControllerEnabled(deploymentUnit)) {
        String topLevelName;
        if (deploymentUnit.getParent() == null) {
            topLevelName = deploymentUnit.getName();
        } else {
            topLevelName = deploymentUnit.getParent().getName();
        }
        cpSupplier = udisBuilder.requires(ControlPointService.serviceName(topLevelName, UndertowExtension.SUBSYSTEM_NAME));
    }
    if (sharedSessionManagerConfig != null) {
        final ServiceName parentSN = deploymentUnit.getParent().getServiceName();
        smfSupplier = udisBuilder.requires(parentSN.append(SharedSessionManagerConfig.SHARED_SESSION_MANAGER_SERVICE_NAME));
        sicSupplier = udisBuilder.requires(parentSN.append(SharedSessionManagerConfig.SHARED_SESSION_IDENTIFIER_CODEC_SERVICE_NAME));
    } else {
        ServletContainerService servletContainer = deploymentUnit.getAttachment(UndertowAttachments.SERVLET_CONTAINER_SERVICE);
        Integer maxActiveSessions = (metaData.getMaxActiveSessions() != null) ? metaData.getMaxActiveSessions() : (servletContainer != null) ? servletContainer.getMaxSessions() : null;
        SessionConfigMetaData sessionConfig = metaData.getSessionConfig();
        int defaultSessionTimeout = ((sessionConfig != null) && sessionConfig.getSessionTimeoutSet()) ? sessionConfig.getSessionTimeout() : (servletContainer != null) ? servletContainer.getDefaultSessionTimeout() : Integer.valueOf(30);
        ServiceName factoryServiceName = deploymentServiceName.append("session");
        ServiceName codecServiceName = deploymentServiceName.append("codec");
        SessionManagementProvider provider = this.getDistributableWebDeploymentProvider(deploymentUnit, metaData);
        SessionManagerFactoryConfiguration configuration = new SessionManagerFactoryConfiguration() {

            @Override
            public String getServerName() {
                return serverInstanceName;
            }

            @Override
            public String getDeploymentName() {
                return deploymentName;
            }

            @Override
            public Module getModule() {
                return module;
            }

            @Override
            public Integer getMaxActiveSessions() {
                return maxActiveSessions;
            }

            @Override
            public Duration getDefaultSessionTimeout() {
                return Duration.ofMinutes(defaultSessionTimeout);
            }
        };
        CapabilityServiceConfigurator factoryConfigurator = provider.getSessionManagerFactoryServiceConfigurator(factoryServiceName, configuration);
        CapabilityServiceConfigurator codecConfigurator = provider.getSessionIdentifierCodecServiceConfigurator(codecServiceName, configuration);
        smfSupplier = udisBuilder.requires(factoryConfigurator.getServiceName());
        sicSupplier = udisBuilder.requires(codecConfigurator.getServiceName());
        CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
        factoryConfigurator.configure(support).build(serviceTarget).install();
        codecConfigurator.configure(support).build(serviceTarget).install();
    }
    UndertowDeploymentInfoService undertowDeploymentInfoService = UndertowDeploymentInfoService.builder().setAttributes(deploymentUnit.getAttachmentList(ServletContextAttribute.ATTACHMENT_KEY)).setContextPath(pathName).setDeploymentName(// todo: is this deployment name concept really applicable?
    deploymentName).setDeploymentRoot(deploymentRoot).setMergedMetaData(warMetaData.getMergedJBossWebMetaData()).setModule(module).setScisMetaData(scisMetaData).setJaccContextId(jaccContextId).setSecurityDomain(securityDomain).setTldInfo(createTldsInfo(tldsMetaData, tldsMetaData == null ? null : tldsMetaData.getSharedTlds(deploymentUnit))).setSetupActions(setupActions).setSharedSessionManagerConfig(sharedSessionManagerConfig).setOverlays(warMetaData.getOverlays()).setExpressionFactoryWrappers(deploymentUnit.getAttachmentList(ExpressionFactoryWrapper.ATTACHMENT_KEY)).setPredicatedHandlers(deploymentUnit.getAttachment(UndertowHandlersDeploymentProcessor.PREDICATED_HANDLERS)).setInitialHandlerChainWrappers(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_INITIAL_HANDLER_CHAIN_WRAPPERS)).setInnerHandlerChainWrappers(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_INNER_HANDLER_CHAIN_WRAPPERS)).setOuterHandlerChainWrappers(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_OUTER_HANDLER_CHAIN_WRAPPERS)).setThreadSetupActions(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_THREAD_SETUP_ACTIONS)).setServletExtensions(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_SERVLET_EXTENSIONS)).setExplodedDeployment(ExplodedDeploymentMarker.isExplodedDeployment(deploymentUnit)).setWebSocketDeploymentInfo(deploymentUnit.getAttachment(UndertowAttachments.WEB_SOCKET_DEPLOYMENT_INFO)).setTempDir(warMetaData.getTempDir()).setExternalResources(deploymentUnit.getAttachmentList(UndertowAttachments.EXTERNAL_RESOURCES)).setAllowSuspendedRequests(deploymentUnit.getAttachmentList(UndertowAttachments.ALLOW_REQUEST_WHEN_SUSPENDED)).createUndertowDeploymentInfoService(diConsumer, usSupplier, smfSupplier, sicSupplier, scsSupplier, crSupplier, hostSupplier, cpSupplier, scSupplier, serverEnvSupplier, sdSupplier, mechanismFactorySupplier, bfSupplier);
    udisBuilder.setInstance(undertowDeploymentInfoService);
    final Set<String> seenExecutors = new HashSet<String>();
    if (metaData.getExecutorName() != null) {
        final Supplier<Executor> executor = udisBuilder.requires(IOServices.WORKER.append(metaData.getExecutorName()));
        undertowDeploymentInfoService.addInjectedExecutor(metaData.getExecutorName(), executor);
        seenExecutors.add(metaData.getExecutorName());
    }
    if (metaData.getServlets() != null) {
        for (JBossServletMetaData servlet : metaData.getServlets()) {
            if (servlet.getExecutorName() != null && !seenExecutors.contains(servlet.getExecutorName())) {
                final Supplier<Executor> executor = udisBuilder.requires(IOServices.WORKER.append(servlet.getExecutorName()));
                undertowDeploymentInfoService.addInjectedExecutor(servlet.getExecutorName(), executor);
                seenExecutors.add(servlet.getExecutorName());
            }
        }
    }
    try {
        udisBuilder.install();
    } catch (DuplicateServiceException e) {
        throw UndertowLogger.ROOT_LOGGER.duplicateHostContextDeployments(deploymentInfoServiceName, e.getMessage());
    }
    final ServiceBuilder<?> udsBuilder = serviceTarget.addService(deploymentServiceName);
    final Consumer<UndertowDeploymentService> sConsumer = udsBuilder.provides(deploymentServiceName, legacyDeploymentServiceName);
    final Supplier<ServletContainerService> cSupplier = udsBuilder.requires(UndertowService.SERVLET_CONTAINER.append(defaultContainer));
    final Supplier<ExecutorService> seSupplier = Services.requireServerExecutor(udsBuilder);
    final Supplier<Host> hSupplier = udsBuilder.requires(hostServiceName);
    final Supplier<DeploymentInfo> diSupplier = udsBuilder.requires(deploymentInfoServiceName);
    for (final ServiceName webDependency : deploymentUnit.getAttachmentList(Attachments.WEB_DEPENDENCIES)) {
        udsBuilder.requires(webDependency);
    }
    for (final ServiceName dependentComponent : dependentComponents) {
        udsBuilder.requires(dependentComponent);
    }
    udsBuilder.setInstance(new UndertowDeploymentService(sConsumer, cSupplier, seSupplier, hSupplier, diSupplier, injectionContainer, true));
    udsBuilder.install();
    deploymentUnit.addToAttachmentList(Attachments.DEPLOYMENT_COMPLETE_SERVICES, deploymentServiceName);
    // adding Jakarta Authorization service
    final boolean elytronJacc = capabilitySupport.hasCapability(ELYTRON_JACC_CAPABILITY_NAME);
    final boolean legacyJacc = !elytronJacc && legacySecurityInstalled(deploymentUnit);
    if (legacyJacc || elytronJacc) {
        WarJACCDeployer deployer = new WarJACCDeployer();
        JaccService<WarMetaData> jaccService = deployer.deploy(deploymentUnit, jaccContextId);
        if (jaccService != null) {
            final ServiceName jaccServiceName = deploymentUnit.getServiceName().append(JaccService.SERVICE_NAME);
            ServiceBuilder<?> jaccBuilder = serviceTarget.addService(jaccServiceName, jaccService);
            if (deploymentUnit.getParent() != null) {
                // add dependency to parent policy
                final DeploymentUnit parentDU = deploymentUnit.getParent();
                jaccBuilder.addDependency(parentDU.getServiceName().append(JaccService.SERVICE_NAME), PolicyConfiguration.class, jaccService.getParentPolicyInjector());
            }
            jaccBuilder.addDependency(capabilitySupport.getCapabilityServiceName(elytronJacc ? ELYTRON_JACC_CAPABILITY_NAME : LEGACY_JACC_CAPABILITY_NAME));
            // add dependency to web deployment service
            jaccBuilder.requires(deploymentServiceName);
            jaccBuilder.setInitialMode(Mode.PASSIVE).install();
        }
    }
    // Process the web related mgmt information
    final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT);
    final ModelNode node = deploymentResourceSupport.getDeploymentSubsystemModel(UndertowExtension.SUBSYSTEM_NAME);
    node.get(DeploymentDefinition.CONTEXT_ROOT.getName()).set("".equals(pathName) ? "/" : pathName);
    node.get(DeploymentDefinition.VIRTUAL_HOST.getName()).set(hostName);
    node.get(DeploymentDefinition.SERVER.getName()).set(serverInstanceName);
    processManagement(deploymentUnit, metaData);
}
Also used : JBossWebMetaData(org.jboss.metadata.web.jboss.JBossWebMetaData) MalformedURLException(java.net.MalformedURLException) SimpleWebInjectionContainer(org.jboss.as.web.common.SimpleWebInjectionContainer) CapabilityServiceSupport(org.jboss.as.controller.capability.CapabilityServiceSupport) SecurityDomain(org.wildfly.security.auth.server.SecurityDomain) SharedSessionManagerConfig(org.jboss.as.web.session.SharedSessionManagerConfig) DuplicateServiceException(org.jboss.msc.service.DuplicateServiceException) ServerEnvironment(org.jboss.as.server.ServerEnvironment) StartupCountdown(org.jboss.as.ee.component.deployers.StartupCountdown) HashSet(java.util.HashSet) SessionManagerFactoryConfiguration(org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration) AdvancedSecurityMetaData(org.jboss.as.web.common.AdvancedSecurityMetaData) SetupAction(org.jboss.as.server.deployment.SetupAction) UndertowService(org.wildfly.extension.undertow.UndertowService) ServiceName(org.jboss.msc.service.ServiceName) InMemorySessionManagerFactory(io.undertow.servlet.core.InMemorySessionManagerFactory) SessionManagerFactory(io.undertow.servlet.api.SessionManagerFactory) Module(org.jboss.modules.Module) ModelNode(org.jboss.dmr.ModelNode) VirtualFile(org.jboss.vfs.VirtualFile) DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) SessionManagementProvider(org.wildfly.clustering.web.container.SessionManagementProvider) NonDistributableSessionManagementProvider(org.wildfly.extension.undertow.session.NonDistributableSessionManagementProvider) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) WarMetaData(org.jboss.as.web.common.WarMetaData) AdvancedSecurityMetaData(org.jboss.as.web.common.AdvancedSecurityMetaData) SecurityMetaData(org.jboss.as.server.security.SecurityMetaData) ServletContextAttribute(org.jboss.as.web.common.ServletContextAttribute) ResourceRoot(org.jboss.as.server.deployment.module.ResourceRoot) DeploymentResourceSupport(org.jboss.as.server.deployment.DeploymentResourceSupport) Executor(java.util.concurrent.Executor) SuspendController(org.jboss.as.server.suspend.SuspendController) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) CachingWebInjectionContainer(org.jboss.as.web.common.CachingWebInjectionContainer) SessionConfigMetaData(org.jboss.metadata.web.spec.SessionConfigMetaData) HttpServerAuthenticationMechanismFactory(org.wildfly.security.http.HttpServerAuthenticationMechanismFactory) CapabilityServiceConfigurator(org.jboss.as.clustering.controller.CapabilityServiceConfigurator) ServletContainerService(org.wildfly.extension.undertow.ServletContainerService) Host(org.wildfly.extension.undertow.Host) ControlPoint(org.wildfly.extension.requestcontroller.ControlPoint) ControlPoint(org.wildfly.extension.requestcontroller.ControlPoint) SessionIdentifierCodec(org.jboss.as.web.session.SessionIdentifierCodec) ComponentRegistry(org.jboss.as.ee.component.ComponentRegistry) BiFunction(java.util.function.BiFunction) SimpleWebInjectionContainer(org.jboss.as.web.common.SimpleWebInjectionContainer) WebInjectionContainer(org.jboss.as.web.common.WebInjectionContainer) CachingWebInjectionContainer(org.jboss.as.web.common.CachingWebInjectionContainer) ExecutorService(java.util.concurrent.ExecutorService) WarJACCDeployer(org.wildfly.extension.undertow.security.jacc.WarJACCDeployer) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit)

Example 3 with ServletContainerService

use of org.wildfly.extension.undertow.ServletContainerService in project wildfly by wildfly.

the class SharedSessionManagerDeploymentProcessor method deploy.

@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    SharedSessionManagerConfig sharedConfig = deploymentUnit.getAttachment(SharedSessionManagerConfig.ATTACHMENT_KEY);
    if (sharedConfig == null)
        return;
    String deploymentName = (deploymentUnit.getParent() == null) ? deploymentUnit.getName() : String.join(".", deploymentUnit.getParent().getName(), deploymentUnit.getName());
    WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    String serverName = Optional.ofNullable(warMetaData).map(metaData -> metaData.getMergedJBossWebMetaData().getServerInstanceName()).orElse(Optional.ofNullable(DefaultDeploymentMappingProvider.instance().getMapping(deploymentName)).map(Map.Entry::getKey).orElse(this.defaultServerName));
    SessionConfigMetaData sessionConfig = sharedConfig.getSessionConfig();
    ServletContainerService servletContainer = deploymentUnit.getAttachment(UndertowAttachments.SERVLET_CONTAINER_SERVICE);
    Integer defaultSessionTimeout = ((sessionConfig != null) && sessionConfig.getSessionTimeoutSet()) ? sessionConfig.getSessionTimeout() : (servletContainer != null) ? servletContainer.getDefaultSessionTimeout() : Integer.valueOf(30);
    CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
    Module module = deploymentUnit.getAttachment(Attachments.MODULE);
    ServiceTarget target = phaseContext.getServiceTarget();
    ServiceName deploymentServiceName = deploymentUnit.getServiceName();
    ServiceName managerServiceName = deploymentServiceName.append(SharedSessionManagerConfig.SHARED_SESSION_MANAGER_SERVICE_NAME);
    ServiceName codecServiceName = deploymentServiceName.append(SharedSessionManagerConfig.SHARED_SESSION_IDENTIFIER_CODEC_SERVICE_NAME);
    SessionManagementProvider provider = this.getDistributableWebDeploymentProvider(deploymentUnit, sharedConfig);
    SessionManagerFactoryConfiguration configuration = new SessionManagerFactoryConfiguration() {

        @Override
        public String getServerName() {
            return serverName;
        }

        @Override
        public String getDeploymentName() {
            return deploymentName;
        }

        @Override
        public Integer getMaxActiveSessions() {
            return sharedConfig.getMaxActiveSessions();
        }

        @Override
        public Module getModule() {
            return module;
        }

        @Override
        public Duration getDefaultSessionTimeout() {
            return Duration.ofMinutes(defaultSessionTimeout);
        }
    };
    provider.getSessionManagerFactoryServiceConfigurator(managerServiceName, configuration).configure(support).build(target).install();
    provider.getSessionIdentifierCodecServiceConfigurator(codecServiceName, configuration).configure(support).build(target).install();
}
Also used : SessionManagerFactoryConfiguration(org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration) SessionManagerFactory(io.undertow.servlet.api.SessionManagerFactory) DeploymentPhaseContext(org.jboss.as.server.deployment.DeploymentPhaseContext) ServletContainerService(org.wildfly.extension.undertow.ServletContainerService) Function(java.util.function.Function) SessionManagementProviderFactory(org.wildfly.extension.undertow.session.SessionManagementProviderFactory) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) SessionManagementProvider(org.wildfly.clustering.web.container.SessionManagementProvider) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) Duration(java.time.Duration) Map(java.util.Map) DeploymentUnitProcessor(org.jboss.as.server.deployment.DeploymentUnitProcessor) DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) ServiceTarget(org.jboss.msc.service.ServiceTarget) SessionConfigMetaData(org.jboss.metadata.web.spec.SessionConfigMetaData) UndertowLogger(org.wildfly.extension.undertow.logging.UndertowLogger) CapabilityServiceSupport(org.jboss.as.controller.capability.CapabilityServiceSupport) Iterator(java.util.Iterator) NonDistributableSessionManagementProvider(org.wildfly.extension.undertow.session.NonDistributableSessionManagementProvider) ServiceLoader(java.util.ServiceLoader) Module(org.jboss.modules.Module) ServiceName(org.jboss.msc.service.ServiceName) Optional(java.util.Optional) Attachments(org.jboss.as.server.deployment.Attachments) WarMetaData(org.jboss.as.web.common.WarMetaData) SharedSessionManagerConfig(org.jboss.as.web.session.SharedSessionManagerConfig) SessionConfigMetaData(org.jboss.metadata.web.spec.SessionConfigMetaData) SessionManagementProvider(org.wildfly.clustering.web.container.SessionManagementProvider) NonDistributableSessionManagementProvider(org.wildfly.extension.undertow.session.NonDistributableSessionManagementProvider) SessionManagerFactoryConfiguration(org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration) ServletContainerService(org.wildfly.extension.undertow.ServletContainerService) ServiceTarget(org.jboss.msc.service.ServiceTarget) WarMetaData(org.jboss.as.web.common.WarMetaData) CapabilityServiceSupport(org.jboss.as.controller.capability.CapabilityServiceSupport) SharedSessionManagerConfig(org.jboss.as.web.session.SharedSessionManagerConfig) ServiceName(org.jboss.msc.service.ServiceName) Module(org.jboss.modules.Module) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit)

Aggregations

ServletContainerService (org.wildfly.extension.undertow.ServletContainerService)3 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)2 SessionManagerFactory (io.undertow.servlet.api.SessionManagerFactory)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 CapabilityServiceSupport (org.jboss.as.controller.capability.CapabilityServiceSupport)2 ComponentRegistry (org.jboss.as.ee.component.ComponentRegistry)2 DeploymentUnit (org.jboss.as.server.deployment.DeploymentUnit)2 DeploymentUnitProcessingException (org.jboss.as.server.deployment.DeploymentUnitProcessingException)2 CachingWebInjectionContainer (org.jboss.as.web.common.CachingWebInjectionContainer)2 ServletContextAttribute (org.jboss.as.web.common.ServletContextAttribute)2 WarMetaData (org.jboss.as.web.common.WarMetaData)2 SharedSessionManagerConfig (org.jboss.as.web.session.SharedSessionManagerConfig)2 JBossServletMetaData (org.jboss.metadata.web.jboss.JBossServletMetaData)2 SessionConfigMetaData (org.jboss.metadata.web.spec.SessionConfigMetaData)2 Module (org.jboss.modules.Module)2 ServiceName (org.jboss.msc.service.ServiceName)2 VirtualFile (org.jboss.vfs.VirtualFile)2 SessionManagementProvider (org.wildfly.clustering.web.container.SessionManagementProvider)2 SessionManagerFactoryConfiguration (org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration)2