Search in sources :

Example 1 with ErrorPage

use of io.undertow.servlet.api.ErrorPage in project indy by Commonjava.

the class DeploymentInfoUtils method merge.

public static void merge(final DeploymentInfo into, final DeploymentInfo from) {
    final Map<String, AuthenticationMechanismFactory> authMechs = from.getAuthenticationMechanisms();
    if (authMechs != null) {
        for (final Map.Entry<String, AuthenticationMechanismFactory> entry : authMechs.entrySet()) {
            logger.debug("Found authentication mechanism: {}", entry.getKey());
            into.addAuthenticationMechanism(entry.getKey(), entry.getValue());
        }
    }
    if (from.getAuthorizationManager() != null) {
        logger.debug("Found authorization manager: {}", from.getAuthorizationManager());
        into.setAuthorizationManager(from.getAuthorizationManager());
    }
    if (from.getConfidentialPortManager() != null) {
        logger.debug("Found confidential port manager: {}", from.getConfidentialPortManager());
        into.setConfidentialPortManager(from.getConfidentialPortManager());
    }
    final List<ErrorPage> errorPages = from.getErrorPages();
    if (errorPages != null) {
        logger.debug("Found error pages: {}", errorPages);
        into.addErrorPages(errorPages);
    }
    if (from.getExceptionHandler() != null) {
        logger.debug("Found exception handler: {}", from.getExceptionHandler());
        into.setExceptionHandler(from.getExceptionHandler());
    }
    final List<FilterMappingInfo> filterMappings = from.getFilterMappings();
    if (filterMappings != null) {
        for (final FilterMappingInfo fmi : filterMappings) {
            switch(fmi.getMappingType()) {
                case SERVLET:
                    {
                        logger.debug("Found servlet-name filter mapping: {} -> {}({})", fmi.getFilterName(), fmi.getMapping(), fmi.getDispatcher());
                        into.addFilterServletNameMapping(fmi.getFilterName(), fmi.getMapping(), fmi.getDispatcher());
                        break;
                    }
                default:
                    {
                        logger.debug("Found URL filter mapping: {} -> {}({})", fmi.getFilterName(), fmi.getMapping(), fmi.getDispatcher());
                        into.addFilterUrlMapping(fmi.getFilterName(), fmi.getMapping(), fmi.getDispatcher());
                    }
            }
        }
    }
    final Map<String, FilterInfo> filterInfos = from.getFilters();
    if (filterInfos != null) {
        logger.debug("Found filters: {}", filterInfos.keySet());
        into.addFilters(filterInfos.values());
    }
    if (from.getIdentityManager() != null) {
        logger.debug("Found identity manager: {}", from.getIdentityManager());
        into.setIdentityManager(from.getIdentityManager());
    }
    final Map<String, String> initParameters = from.getInitParameters();
    if (initParameters != null) {
        for (final Map.Entry<String, String> entry : initParameters.entrySet()) {
            logger.debug("Init-Param: {} = {} from: {}", entry.getKey(), entry.getValue(), from);
            into.addInitParameter(entry.getKey(), entry.getValue());
        }
    }
    final List<LifecycleInterceptor> lifecycleInterceptors = from.getLifecycleInterceptors();
    if (lifecycleInterceptors != null) {
        for (final LifecycleInterceptor lifecycleInterceptor : lifecycleInterceptors) {
            logger.debug("Found lifecycle interceptor: {}", lifecycleInterceptor);
            into.addLifecycleInterceptor(lifecycleInterceptor);
        }
    }
    final List<ListenerInfo> listeners = from.getListeners();
    if (listeners != null) {
        logger.debug("Found listeners: {}", listeners.stream().map(li -> li.getListenerClass().getName()).collect(Collectors.toList()));
        into.addListeners(listeners);
    }
    if (from.getMetricsCollector() != null) {
        logger.debug("Found metrics collector: {}", from.getMetricsCollector());
        into.setMetricsCollector(from.getMetricsCollector());
    }
    final List<MimeMapping> mimeMappings = from.getMimeMappings();
    if (mimeMappings != null) {
        logger.debug("Found mime mappings: {}", mimeMappings.stream().map(mm -> mm.getMimeType() + " -> " + mm.getExtension()).collect(Collectors.toList()));
        into.addMimeMappings(mimeMappings);
    }
    final List<NotificationReceiver> notificationReceivers = from.getNotificationReceivers();
    if (notificationReceivers != null) {
        logger.debug("Found notification receivers: {}", notificationReceivers);
        into.addNotificationReceivers(notificationReceivers);
    }
    final Map<String, Set<String>> principalVersusRolesMap = from.getPrincipalVersusRolesMap();
    if (principalVersusRolesMap != null) {
        for (final Map.Entry<String, Set<String>> entry : principalVersusRolesMap.entrySet()) {
            logger.debug("Found principle-roles mapping: {} -> {}", entry.getKey(), entry.getValue());
            into.addPrincipalVsRoleMappings(entry.getKey(), entry.getValue());
        }
    }
    final List<SecurityConstraint> securityConstraints = from.getSecurityConstraints();
    if (securityConstraints != null) {
        if (logger.isDebugEnabled()) {
            for (final SecurityConstraint sc : securityConstraints) {
                logger.debug("Security Constraint: {} from: {}", sc, from);
            }
        }
        into.addSecurityConstraints(securityConstraints);
    }
    final LoginConfig loginConfig = from.getLoginConfig();
    if (loginConfig != null) {
        logger.debug("Login Config with realm: {} and mechanism: {} from: {}", loginConfig.getRealmName(), loginConfig.getAuthMethods(), from);
        if (into.getLoginConfig() != null) {
            throw new IllegalStateException("Two or more deployment providers are attempting to provide login configurations! Enable debug logging to see more.");
        }
        into.setLoginConfig(loginConfig);
    }
    if (from.getSecurityContextFactory() != null) {
        logger.debug("Found security context factory: {}", from.getSecurityContextFactory());
        into.setSecurityContextFactory(from.getSecurityContextFactory());
    }
    final Set<String> securityRoles = from.getSecurityRoles();
    if (securityRoles != null) {
        logger.debug("Found security roles: {}", securityRoles);
        into.addSecurityRoles(securityRoles);
    }
    final List<ServletContainerInitializerInfo> servletContainerInitializers = from.getServletContainerInitializers();
    if (servletContainerInitializers != null) {
        logger.debug("Found servlet container initializers: {}", servletContainerInitializers.stream().map(sci -> sci.getServletContainerInitializerClass().getName()).collect(Collectors.toList()));
        into.addServletContainerInitalizers(servletContainerInitializers);
    }
    final Map<String, Object> servletContextAttributes = from.getServletContextAttributes();
    if (servletContextAttributes != null) {
        for (final Map.Entry<String, Object> entry : servletContextAttributes.entrySet()) {
            logger.debug("Found servlet context attribute: {} -> {}", entry.getKey(), entry.getValue());
            into.addServletContextAttribute(entry.getKey(), entry.getValue());
        }
    }
    final List<ServletExtension> servletExtensions = from.getServletExtensions();
    if (servletExtensions != null) {
        for (final ServletExtension servletExtension : servletExtensions) {
            logger.debug("Found servlet extension: {}", servletExtension);
            into.addServletExtension(servletExtension);
        }
    }
    final Map<String, ServletInfo> servletInfos = from.getServlets();
    if (servletInfos != null) {
        logger.debug("Found servlets: {}", servletInfos.values().stream().map(si -> si.getName() + " => " + si.getMappings()).collect(Collectors.toList()));
        into.addServlets(servletInfos.values());
    }
    final List<SessionListener> sessionListeners = from.getSessionListeners();
    if (sessionListeners != null) {
        for (final SessionListener sessionListener : sessionListeners) {
            logger.debug("Found session listener: {}", sessionListener);
            into.addSessionListener(sessionListener);
        }
    }
    if (from.getSessionManagerFactory() != null) {
        logger.debug("Found session manager factory: {}", from.getSessionManagerFactory());
        into.setSessionManagerFactory(from.getSessionManagerFactory());
    }
    if (from.getSessionPersistenceManager() != null) {
        logger.debug("Found session persistence manager: {}", from.getSessionPersistenceManager());
        into.setSessionPersistenceManager(from.getSessionPersistenceManager());
    }
    if (from.getTempDir() != null) {
        logger.debug("Found temp dir: {}", from.getTempDir());
        into.setTempDir(from.getTempDir());
    }
    final List<String> welcomePages = from.getWelcomePages();
    if (welcomePages != null) {
        logger.debug("Found welcome pages: {}", welcomePages);
        into.addWelcomePages(welcomePages);
    }
    final List<HandlerWrapper> initWrappers = from.getInitialHandlerChainWrappers();
    if (initWrappers != null) {
        for (final HandlerWrapper wrapper : initWrappers) {
            logger.debug("Found initial handler chain wrapper: {}", wrapper);
            into.addInitialHandlerChainWrapper(wrapper);
        }
    }
    final List<HandlerWrapper> outerWrappers = from.getOuterHandlerChainWrappers();
    if (outerWrappers != null) {
        for (final HandlerWrapper wrapper : outerWrappers) {
            logger.debug("Found outer handler chain wrapper: {}", wrapper);
            into.addOuterHandlerChainWrapper(wrapper);
        }
    }
    final List<HandlerWrapper> innerWrappers = from.getInnerHandlerChainWrappers();
    if (innerWrappers != null) {
        for (final HandlerWrapper wrapper : innerWrappers) {
            logger.debug("Found inner handler chain wrapper: {}", wrapper);
            into.addInnerHandlerChainWrapper(wrapper);
        }
    }
}
Also used : ErrorPage(io.undertow.servlet.api.ErrorPage) FilterMappingInfo(io.undertow.servlet.api.FilterMappingInfo) Set(java.util.Set) HandlerWrapper(io.undertow.server.HandlerWrapper) SecurityConstraint(io.undertow.servlet.api.SecurityConstraint) LifecycleInterceptor(io.undertow.servlet.api.LifecycleInterceptor) ServletInfo(io.undertow.servlet.api.ServletInfo) LoginConfig(io.undertow.servlet.api.LoginConfig) FilterInfo(io.undertow.servlet.api.FilterInfo) MimeMapping(io.undertow.servlet.api.MimeMapping) ServletContainerInitializerInfo(io.undertow.servlet.api.ServletContainerInitializerInfo) ListenerInfo(io.undertow.servlet.api.ListenerInfo) NotificationReceiver(io.undertow.security.api.NotificationReceiver) SessionListener(io.undertow.server.session.SessionListener) AuthenticationMechanismFactory(io.undertow.security.api.AuthenticationMechanismFactory) Map(java.util.Map) ServletExtension(io.undertow.servlet.ServletExtension)

Example 2 with ErrorPage

use of io.undertow.servlet.api.ErrorPage in project undertow by undertow-io.

the class ErrorPageTestCase method setup.

@BeforeClass
public static void setup() throws IOException, ServletException {
    final ServletContainer container = ServletContainer.Factory.newInstance();
    final PathHandler root = new PathHandler();
    DefaultServer.setRootHandler(root);
    DeploymentInfo builder1 = new DeploymentInfo();
    builder1.addServlet(new ServletInfo("error", ErrorServlet.class).addMapping("/error"));
    builder1.addServlet(new ServletInfo("path", PathServlet.class).addMapping("/*"));
    builder1.addErrorPage(new ErrorPage("/defaultErrorPage"));
    builder1.addErrorPage(new ErrorPage("/404", StatusCodes.NOT_FOUND));
    builder1.addErrorPage(new ErrorPage("/parentException", ParentException.class));
    builder1.addErrorPage(new ErrorPage("/childException", ChildException.class));
    builder1.addErrorPage(new ErrorPage("/runtimeException", RuntimeException.class));
    builder1.setExceptionHandler(LoggingExceptionHandler.builder().add(ParentException.class, "io.undertow", Logger.Level.DEBUG).add(ChildException.class, "io.undertow", Logger.Level.DEBUG).add(RuntimeException.class, "io.undertow", Logger.Level.DEBUG).add(ServletException.class, "io.undertow", Logger.Level.DEBUG).build());
    builder1.setClassIntrospecter(TestClassIntrospector.INSTANCE).setClassLoader(ErrorPageTestCase.class.getClassLoader()).setContextPath("/servletContext1").setServletStackTraces(ServletStackTraces.NONE).setDeploymentName("servletContext1.war");
    final DeploymentManager manager1 = container.addDeployment(builder1);
    manager1.deploy();
    root.addPrefixPath(builder1.getContextPath(), manager1.start());
    DeploymentInfo builder2 = new DeploymentInfo();
    builder2.addServlet(new ServletInfo("error", ErrorServlet.class).addMapping("/error"));
    builder2.addServlet(new ServletInfo("path", PathServlet.class).addMapping("/*"));
    builder2.addErrorPage(new ErrorPage("/404", StatusCodes.NOT_FOUND));
    builder2.addErrorPage(new ErrorPage("/501", StatusCodes.NOT_IMPLEMENTED));
    builder2.addErrorPage(new ErrorPage("/parentException", ParentException.class));
    builder2.addErrorPage(new ErrorPage("/childException", ChildException.class));
    builder2.addErrorPage(new ErrorPage("/runtimeException", RuntimeException.class));
    builder2.setExceptionHandler(LoggingExceptionHandler.builder().add(ParentException.class, "io.undertow", Logger.Level.DEBUG).add(ChildException.class, "io.undertow", Logger.Level.DEBUG).add(RuntimeException.class, "io.undertow", Logger.Level.DEBUG).add(ServletException.class, "io.undertow", Logger.Level.DEBUG).build());
    builder2.setClassIntrospecter(TestClassIntrospector.INSTANCE).setClassLoader(ErrorPageTestCase.class.getClassLoader()).setContextPath("/servletContext2").setServletStackTraces(ServletStackTraces.NONE).setDeploymentName("servletContext2.war");
    final DeploymentManager manager2 = container.addDeployment(builder2);
    manager2.deploy();
    root.addPrefixPath(builder2.getContextPath(), manager2.start());
    DeploymentInfo builder3 = new DeploymentInfo();
    builder3.addServlet(new ServletInfo("error", ErrorServlet.class).addMapping("/error"));
    builder3.addServlet(new ServletInfo("path", PathServlet.class).addMapping("/*"));
    builder3.addErrorPage(new ErrorPage("/defaultErrorPage"));
    builder3.addErrorPage(new ErrorPage("/404", StatusCodes.NOT_FOUND));
    builder3.addErrorPage(new ErrorPage("/500", StatusCodes.INTERNAL_SERVER_ERROR));
    builder3.addErrorPage(new ErrorPage("/parentException", ParentException.class));
    builder3.addErrorPage(new ErrorPage("/childException", ChildException.class));
    builder3.addErrorPage(new ErrorPage("/runtimeException", RuntimeException.class));
    builder3.setClassIntrospecter(TestClassIntrospector.INSTANCE).setClassLoader(ErrorPageTestCase.class.getClassLoader()).setContextPath("/servletContext3").setServletStackTraces(ServletStackTraces.NONE).setDeploymentName("servletContext3.war");
    builder3.setExceptionHandler(LoggingExceptionHandler.builder().add(ParentException.class, "io.undertow", Logger.Level.DEBUG).add(ChildException.class, "io.undertow", Logger.Level.DEBUG).add(RuntimeException.class, "io.undertow", Logger.Level.DEBUG).add(ServletException.class, "io.undertow", Logger.Level.DEBUG).build());
    final DeploymentManager manager3 = container.addDeployment(builder3);
    manager3.deploy();
    root.addPrefixPath(builder3.getContextPath(), manager3.start());
}
Also used : ServletInfo(io.undertow.servlet.api.ServletInfo) ErrorPage(io.undertow.servlet.api.ErrorPage) DeploymentManager(io.undertow.servlet.api.DeploymentManager) ServletContainer(io.undertow.servlet.api.ServletContainer) PathHandler(io.undertow.server.handlers.PathHandler) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) BeforeClass(org.junit.BeforeClass)

Example 3 with ErrorPage

use of io.undertow.servlet.api.ErrorPage in project undertow by undertow-io.

the class SecurityErrorPageTestCase method setup.

@BeforeClass
public static void setup() throws IOException, ServletException {
    final ServletContainer container = ServletContainer.Factory.newInstance();
    final PathHandler root = new PathHandler();
    DefaultServer.setRootHandler(root);
    DeploymentInfo builder = new DeploymentInfo();
    builder.addServlet(new ServletInfo("secure", SecureServlet.class).addMapping("/secure")).addSecurityConstraint(Servlets.securityConstraint().addRoleAllowed("user").addWebResourceCollection(Servlets.webResourceCollection().addUrlPattern("/*")));
    builder.addServlet(new ServletInfo("path", PathServlet.class).addMapping("/*"));
    builder.addErrorPage(new ErrorPage("/401", StatusCodes.UNAUTHORIZED));
    ServletIdentityManager identityManager = new ServletIdentityManager();
    // Just one role less user.
    identityManager.addUser("user1", "password1");
    builder.setClassIntrospecter(TestClassIntrospector.INSTANCE).setClassLoader(ErrorPageTestCase.class.getClassLoader()).setContextPath("/servletContext").setServletStackTraces(ServletStackTraces.NONE).setIdentityManager(identityManager).setLoginConfig(Servlets.loginConfig("BASIC", "Test Realm")).setDeploymentName("servletContext.war");
    final DeploymentManager manager1 = container.addDeployment(builder);
    manager1.deploy();
    root.addPrefixPath(builder.getContextPath(), manager1.start());
}
Also used : ServletInfo(io.undertow.servlet.api.ServletInfo) ErrorPage(io.undertow.servlet.api.ErrorPage) DeploymentManager(io.undertow.servlet.api.DeploymentManager) ServletContainer(io.undertow.servlet.api.ServletContainer) PathHandler(io.undertow.server.handlers.PathHandler) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) ServletIdentityManager(io.undertow.servlet.test.security.constraint.ServletIdentityManager) BeforeClass(org.junit.BeforeClass)

Example 4 with ErrorPage

use of io.undertow.servlet.api.ErrorPage 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 5 with ErrorPage

use of io.undertow.servlet.api.ErrorPage in project runwar by cfmlprojects.

the class WebXMLParser method parseWebXml.

/**
 * Parses the web.xml and configures the context.
 *
 * @param webxml
 * @param info
 */
@SuppressWarnings("unchecked")
public static void parseWebXml(File webxml, File webinf, DeploymentInfo info, SessionCookieConfig sessionConfig, boolean ignoreWelcomePages, boolean ignoreRestMappings) {
    if (!webxml.exists() || !webxml.canRead()) {
        LOG.error("Error reading web.xml! exists:" + webxml.exists() + "readable:" + webxml.canRead());
    }
    Map<String, ServletInfo> servletMap = new HashMap<String, ServletInfo>();
    Map<String, FilterInfo> filterMap = new HashMap<String, FilterInfo>();
    try {
        final String webinfPath;
        if (File.separatorChar == '\\') {
            webinfPath = webinf.getCanonicalPath().replace("\\", "\\\\");
        } else {
            webinfPath = webinf.getCanonicalPath();
        }
        trace("parsing %s", webxml.getCanonicalPath());
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        // disable validation, so we don't incur network calls
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        // parse and normalize text representation
        Document doc = docBuilder.parse(webxml);
        doc.getDocumentElement().normalize();
        trace("Root element of the doc is %s", doc.getDocumentElement().getNodeName());
        String displayName = $(doc).find("context-param").text();
        if (displayName != null) {
            info.setDisplayName(displayName);
        }
        $(doc).find("context-param").each(ctx -> {
            String pName = $(ctx).find("param-name").text();
            String pValue = $(ctx).find("param-value").text();
            info.addServletContextAttribute(pName, pValue);
            info.addInitParameter(pName, pValue);
            LOG.tracef("context param: %s = %s", pName, pValue);
        });
        trace("Total no of context-params: %s", info.getServletContextAttributes().size());
        Match listeners = $(doc).find("listener");
        trace("Total no of listeners: %s", listeners.size());
        listeners.each(ctx -> {
            String pName = $(ctx).find("listener-class").text();
            LOG.tracef("Listener: %s", pName);
            ListenerInfo listener;
            try {
                listener = new ListenerInfo((Class<? extends EventListener>) info.getClassLoader().loadClass(pName));
                info.addListener(listener);
            } catch (ClassNotFoundException e) {
                LOG.error(e);
            }
        });
        // do filters
        Match filters = $(doc).find("filter");
        trace("Total no of filters: %s", filters.size());
        filters.each(ctx -> {
            String filterName = $(ctx).find("filter-name").text();
            String className = $(ctx).find("filter-class").text();
            LOG.tracef("filter-name: %s, filter-class: %s", filterName, className);
            try {
                FilterInfo filter = new FilterInfo(filterName, (Class<? extends Filter>) info.getClassLoader().loadClass(className));
                Match initParams = $(ctx).find("init-param");
                LOG.debugf("Total no of %s init-params: %s", filterName, initParams.size());
                initParams.each(cctx -> {
                    String pName = $(cctx).find("param-name").text();
                    String pValue = $(cctx).find("param-value").text();
                    filter.addInitParam(pName, pValue);
                    LOG.tracef("%s init-param: param-name: %s  param-value: %s", filterName, pName, pValue);
                });
                if ($(ctx).find("async-supported").size() > 0) {
                    trace("Async supported: %s", $(ctx).find("async-supported").text());
                    filter.setAsyncSupported(Boolean.valueOf($(ctx).find("async-supported").text()));
                }
                filterMap.put(filterName, filter);
            } catch (ClassNotFoundException e) {
                LOG.error(e);
            }
        });
        info.addFilters(filterMap.values());
        Match filterMappings = $(doc).find("filter-mapping");
        trace("Total no of filters-mappings: %s", filterMappings.size());
        filterMappings.each(ctx -> {
            String filterName = $(ctx).find("filter-name").text();
            String className = $(ctx).find("filter-class").text();
            LOG.tracef("filter-name: %s, filter-class: %s", filterName, className);
            FilterInfo filter = filterMap.get(filterName);
            if (filter == null) {
                LOG.errorf("No filter found for filter-mapping: %s", filterName);
            } else {
                String urlPattern = $(ctx).find("url-pattern").text();
                Match dispatchers = $(ctx).find("dispatcher");
                if (dispatchers == null) {
                    LOG.debugf("filter-name: %s url-pattern: %s dispatcher: REQUEST", filterName, urlPattern);
                    info.addFilterUrlMapping(filterName, urlPattern, DispatcherType.valueOf("REQUEST"));
                } else {
                    dispatchers.each(dCtx -> {
                        String dispatcher = $(dCtx).text();
                        LOG.debugf("filter-name: %s url-pattern: %s dispatcher: %s", filterName, urlPattern, dispatcher);
                        info.addFilterUrlMapping(filterName, $(dCtx).text(), DispatcherType.valueOf(dispatcher));
                    });
                }
                String servletName = $(ctx).find("servlet-name").text();
                if (servletName != null) {
                    LOG.debugf("Adding servlet mapping: %s", servletName);
                    info.addFilterServletNameMapping(filterName, servletName, DispatcherType.valueOf("REQUEST"));
                }
            }
        });
        Match servlets = $(doc).find("servlet");
        trace("Total no of servlets: %s", servlets.size());
        servlets.each(ctx -> {
            String servletName = $(ctx).find("servlet-name").text();
            String servletClassName = $(ctx).find("servlet-class").text();
            String loadOnStartup = $(ctx).find("load-on-startup").text();
            LOG.tracef("servlet-name: %s, servlet-class: %s", servletName, servletClassName);
            LOG.tracef("Adding servlet to undertow: ************* %s: %s *************", servletName, servletClassName);
            Class<?> servletClass;
            try {
                servletClass = info.getClassLoader().loadClass(servletClassName);
            } catch (Exception e) {
                String msg = "Could not load servlet class: " + servletClassName;
                LOG.error(msg);
                throw new RuntimeException(msg);
            }
            ServletInfo servlet = new ServletInfo(servletName, (Class<? extends Servlet>) servletClass);
            servlet.setRequireWelcomeFileMapping(true);
            if (loadOnStartup != null) {
                trace("Load on startup: %s", loadOnStartup);
                servlet.setLoadOnStartup(Integer.valueOf(loadOnStartup));
            }
            Match initParams = $(ctx).find("init-param");
            LOG.debugf("Total no of %s init-params: %s", servletName, initParams.size());
            initParams.each(cctx -> {
                String pName = $(cctx).find("param-name").text();
                String pValue = $(cctx).find("param-value").text();
                pValue = pValue.replaceAll(".?/WEB-INF", SPECIAL_REGEX_CHARS.matcher(webinfPath).replaceAll("\\\\$0"));
                LOG.tracef("%s init-param: param-name: %s  param-value: %s", servletName, pName, pValue);
                servlet.addInitParam(pName, pValue);
            });
            servletMap.put(servlet.getName(), servlet);
        });
        Match servletMappings = $(doc).find("servlet-mapping");
        trace("Total no of servlet-mappings: %s", servletMappings.size());
        servletMappings.each(ctx -> {
            String servletName = $(ctx).find("servlet-name").text();
            ServletInfo servlet = servletMap.get(servletName);
            if (servlet == null) {
                LOG.errorf("No servlet found for servlet-mapping: %s", servletName);
            } else {
                Match urlPatterns = $(ctx).find("url-pattern");
                urlPatterns.each(urlPatternElement -> {
                    String urlPattern = $(urlPatternElement).text();
                    if (ignoreRestMappings && (servletName.toLowerCase().equals("restservlet") || servletName.toLowerCase().equals("cfrestservlet"))) {
                        LOG.tracef("Skipping mapping servlet-name:%s, url-partern: %s", servletName, urlPattern);
                    } else {
                        LOG.tracef("mapping servlet-name:%s, url-pattern: %s", servletName, urlPattern);
                        servlet.addMapping(urlPattern);
                    }
                });
            }
        });
        // add servlets to deploy info
        info.addServlets(servletMap.values());
        // do welcome files
        if (ignoreWelcomePages) {
            LOG.info("Ignoring any welcome pages in web.xml");
        } else {
            Match welcomeFileList = $(doc).find("welcome-file-list");
            trace("Total no of welcome files: %s", welcomeFileList.find("welcome-file").size());
            welcomeFileList.find("welcome-file").each(welcomeFileElement -> {
                String welcomeFile = $(welcomeFileElement).text();
                LOG.debugf("welcome-file: %s", welcomeFile);
                info.addWelcomePage(welcomeFile);
            });
        }
        Match mimeMappings = $(doc).find("mime-mapping");
        trace("Total no of mime-mappings: %s", mimeMappings.size());
        mimeMappings.each(ctx -> {
            String extension = $(ctx).find("extension").text();
            String mimeType = $(ctx).find("mime-type").text();
            LOG.tracef("filter-name: %s, filter-class: %s", extension, mimeType);
            info.addMimeMapping(new MimeMapping(extension, mimeType));
        });
        Match errorPages = $(doc).find("error-page");
        trace("Total no of error-pages: %s", errorPages.size());
        errorPages.each(ctx -> {
            String location = $(ctx).find("location").text();
            String errorCode = $(ctx).find("error-code").text();
            String exceptionType = $(ctx).find("exception-type").text();
            if (errorCode != null && exceptionType != null) {
                LOG.errorf("Cannot specify both error-code and exception-type, using exception-type: %s", exceptionType);
                errorCode = null;
            }
            if (errorCode == null && exceptionType == null) {
                LOG.tracef("default error-page location: %s", location);
                info.addErrorPage(new ErrorPage(location));
            } else if (errorCode != null) {
                LOG.tracef("error-code: %s - location: %s", location, errorCode);
                info.addErrorPage(new ErrorPage(location, Integer.parseInt(errorCode)));
            } else {
                LOG.tracef("exception-type: %s - location: %s", location, errorCode);
                try {
                    info.addErrorPage(new ErrorPage(location, (Class<? extends Throwable>) info.getClassLoader().loadClass(exceptionType)));
                } catch (ClassNotFoundException e) {
                    LOG.error(e);
                }
            }
        });
        Match sessionConfigElement = $(doc).find("session-config");
        trace("Total no of cookie config elements: %s", sessionConfigElement.find("cookie-config").size());
        sessionConfigElement.find("cookie-config").each(welcomeFileElement -> {
            String httpOnly = $(welcomeFileElement).find("http-only").text();
            String secure = $(welcomeFileElement).find("secure").text();
            sessionConfig.setHttpOnly(Boolean.valueOf(httpOnly));
            sessionConfig.setSecure(Boolean.valueOf(secure));
            LOG.debugf("http-only: %s", Boolean.valueOf(httpOnly).toString());
            LOG.debugf("secure: %s", Boolean.valueOf(secure).toString());
        });
    } catch (Exception e) {
        LOG.error("Error reading web.xml", e);
        throw new RuntimeException(e);
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ErrorPage(io.undertow.servlet.api.ErrorPage) HashMap(java.util.HashMap) Document(org.w3c.dom.Document) Match(org.joox.Match) ServletInfo(io.undertow.servlet.api.ServletInfo) ListenerInfo(io.undertow.servlet.api.ListenerInfo) DocumentBuilder(javax.xml.parsers.DocumentBuilder) EventListener(java.util.EventListener) FilterInfo(io.undertow.servlet.api.FilterInfo) MimeMapping(io.undertow.servlet.api.MimeMapping)

Aggregations

ErrorPage (io.undertow.servlet.api.ErrorPage)8 ServletInfo (io.undertow.servlet.api.ServletInfo)7 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)4 FilterInfo (io.undertow.servlet.api.FilterInfo)4 HashMap (java.util.HashMap)4 PathHandler (io.undertow.server.handlers.PathHandler)3 ListenerInfo (io.undertow.servlet.api.ListenerInfo)3 LoginConfig (io.undertow.servlet.api.LoginConfig)3 MimeMapping (io.undertow.servlet.api.MimeMapping)3 SecurityConstraint (io.undertow.servlet.api.SecurityConstraint)3 HandlerWrapper (io.undertow.server.HandlerWrapper)2 HttpHandler (io.undertow.server.HttpHandler)2 ServletExtension (io.undertow.servlet.ServletExtension)2 DeploymentManager (io.undertow.servlet.api.DeploymentManager)2 ServletContainer (io.undertow.servlet.api.ServletContainer)2 ServletContainerInitializerInfo (io.undertow.servlet.api.ServletContainerInitializerInfo)2 WebResourceCollection (io.undertow.servlet.api.WebResourceCollection)2 WebSocketDeploymentInfo (io.undertow.websockets.jsr.WebSocketDeploymentInfo)2 File (java.io.File)2 IOException (java.io.IOException)2