Search in sources :

Example 1 with SessionTrackingMode

use of javax.servlet.SessionTrackingMode in project gocd by gocd.

the class WebappSessionConfigIntegrationTest method shouldSetSessionTrackingModeToCookieOnly.

@Test
public void shouldSetSessionTrackingModeToCookieOnly() throws Exception {
    Server server = new Server(1234);
    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setWar(webapp.getAbsolutePath());
    webAppContext.setContextPath("/");
    server.setHandler(webAppContext);
    try {
        server.start();
        Set<SessionTrackingMode> effectiveSessionTrackingModes = ((WebAppContext) server.getHandlers()[0]).getServletContext().getEffectiveSessionTrackingModes();
        assertThat(effectiveSessionTrackingModes.size(), is(1));
        assertThat(effectiveSessionTrackingModes.contains(SessionTrackingMode.COOKIE), is(true));
    } finally {
        server.stop();
    }
}
Also used : WebAppContext(org.eclipse.jetty.webapp.WebAppContext) Server(org.eclipse.jetty.server.Server) SessionTrackingMode(javax.servlet.SessionTrackingMode) Test(org.junit.Test)

Example 2 with SessionTrackingMode

use of javax.servlet.SessionTrackingMode in project wildfly by wildfly.

the class UndertowDeploymentInfoService method start.

@Override
public synchronized void start(final StartContext startContext) throws StartException {
    ClassLoader oldTccl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(module.getClassLoader());
        DeploymentInfo deploymentInfo = createServletConfig();
        deploymentInfo.setConfidentialPortManager(getConfidentialPortManager());
        handleDistributable(deploymentInfo);
        if (securityFunction.getOptionalValue() == null) {
            handleIdentityManager(deploymentInfo);
            handleJASPIMechanism(deploymentInfo);
            handleJACCAuthorization(deploymentInfo);
            handleAuthManagerLogout(deploymentInfo, mergedMetaData);
            if (mergedMetaData.isUseJBossAuthorization()) {
                deploymentInfo.setAuthorizationManager(new JbossAuthorizationManager(deploymentInfo.getAuthorizationManager()));
            }
        }
        handleAdditionalAuthenticationMechanisms(deploymentInfo);
        SessionConfigMetaData sessionConfig = mergedMetaData.getSessionConfig();
        if (sharedSessionManagerConfig != null && sharedSessionManagerConfig.getSessionConfig() != null) {
            sessionConfig = sharedSessionManagerConfig.getSessionConfig();
        }
        ServletSessionConfig config = null;
        //default session config
        SessionCookieConfig defaultSessionConfig = container.getValue().getSessionCookieConfig();
        if (defaultSessionConfig != null) {
            config = new ServletSessionConfig();
            if (defaultSessionConfig.getName() != null) {
                config.setName(defaultSessionConfig.getName());
            }
            if (defaultSessionConfig.getDomain() != null) {
                config.setDomain(defaultSessionConfig.getDomain());
            }
            if (defaultSessionConfig.getHttpOnly() != null) {
                config.setHttpOnly(defaultSessionConfig.getHttpOnly());
            }
            if (defaultSessionConfig.getSecure() != null) {
                config.setSecure(defaultSessionConfig.getSecure());
            }
            if (defaultSessionConfig.getMaxAge() != null) {
                config.setMaxAge(defaultSessionConfig.getMaxAge());
            }
            if (defaultSessionConfig.getComment() != null) {
                config.setComment(defaultSessionConfig.getComment());
            }
        }
        SecureRandomSessionIdGenerator sessionIdGenerator = new SecureRandomSessionIdGenerator();
        sessionIdGenerator.setLength(container.getValue().getSessionIdLength());
        deploymentInfo.setSessionIdGenerator(sessionIdGenerator);
        boolean sessionTimeoutSet = false;
        if (sessionConfig != null) {
            if (sessionConfig.getSessionTimeoutSet()) {
                deploymentInfo.setDefaultSessionTimeout(sessionConfig.getSessionTimeout() * 60);
                sessionTimeoutSet = true;
            }
            CookieConfigMetaData cookieConfig = sessionConfig.getCookieConfig();
            if (config == null) {
                config = new ServletSessionConfig();
            }
            if (cookieConfig != null) {
                if (cookieConfig.getName() != null) {
                    config.setName(cookieConfig.getName());
                }
                if (cookieConfig.getDomain() != null) {
                    config.setDomain(cookieConfig.getDomain());
                }
                if (cookieConfig.getComment() != null) {
                    config.setComment(cookieConfig.getComment());
                }
                config.setSecure(cookieConfig.getSecure());
                config.setPath(cookieConfig.getPath());
                config.setMaxAge(cookieConfig.getMaxAge());
                config.setHttpOnly(cookieConfig.getHttpOnly());
            }
            List<SessionTrackingModeType> modes = sessionConfig.getSessionTrackingModes();
            if (modes != null && !modes.isEmpty()) {
                final Set<SessionTrackingMode> trackingModes = new HashSet<>();
                for (SessionTrackingModeType mode : modes) {
                    switch(mode) {
                        case COOKIE:
                            trackingModes.add(SessionTrackingMode.COOKIE);
                            break;
                        case SSL:
                            trackingModes.add(SessionTrackingMode.SSL);
                            break;
                        case URL:
                            trackingModes.add(SessionTrackingMode.URL);
                            break;
                    }
                }
                config.setSessionTrackingModes(trackingModes);
            }
        }
        if (!sessionTimeoutSet) {
            deploymentInfo.setDefaultSessionTimeout(container.getValue().getDefaultSessionTimeout() * 60);
        }
        if (config != null) {
            deploymentInfo.setServletSessionConfig(config);
        }
        for (final SetupAction action : setupActions) {
            deploymentInfo.addThreadSetupAction(new UndertowThreadSetupAction(action));
        }
        if (initialHandlerChainWrappers != null) {
            for (HandlerWrapper handlerWrapper : initialHandlerChainWrappers) {
                deploymentInfo.addInitialHandlerChainWrapper(handlerWrapper);
            }
        }
        if (innerHandlerChainWrappers != null) {
            for (HandlerWrapper handlerWrapper : innerHandlerChainWrappers) {
                deploymentInfo.addInnerHandlerChainWrapper(handlerWrapper);
            }
        }
        if (outerHandlerChainWrappers != null) {
            for (HandlerWrapper handlerWrapper : outerHandlerChainWrappers) {
                deploymentInfo.addOuterHandlerChainWrapper(handlerWrapper);
            }
        }
        if (threadSetupActions != null) {
            for (ThreadSetupHandler threadSetupAction : threadSetupActions) {
                deploymentInfo.addThreadSetupAction(threadSetupAction);
            }
        }
        deploymentInfo.setServerName(serverEnvironmentInjectedValue.getValue().getProductConfig().getPrettyVersionString());
        if (undertowService.getValue().isStatisticsEnabled()) {
            deploymentInfo.setMetricsCollector(new UndertowMetricsCollector());
        }
        ControlPoint controlPoint = controlPointInjectedValue.getOptionalValue();
        if (controlPoint != null) {
            deploymentInfo.addOuterHandlerChainWrapper(GlobalRequestControllerHandler.wrapper(controlPoint, allowSuspendedRequests));
        }
        container.getValue().getAuthenticationMechanisms().entrySet().forEach(e -> deploymentInfo.addAuthenticationMechanism(e.getKey(), e.getValue()));
        deploymentInfo.setUseCachedAuthenticationMechanism(!deploymentInfo.getAuthenticationMechanisms().containsKey(SingleSignOnService.AUTHENTICATION_MECHANISM_NAME));
        this.deploymentInfo = deploymentInfo;
    } finally {
        Thread.currentThread().setContextClassLoader(oldTccl);
    }
}
Also used : SessionConfigMetaData(org.jboss.metadata.web.spec.SessionConfigMetaData) JbossAuthorizationManager(org.wildfly.extension.undertow.security.JbossAuthorizationManager) SessionTrackingMode(javax.servlet.SessionTrackingMode) CookieConfigMetaData(org.jboss.metadata.web.spec.CookieConfigMetaData) SetupAction(org.jboss.as.server.deployment.SetupAction) SecurityContextThreadSetupAction(org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction) ControlPoint(org.wildfly.extension.requestcontroller.ControlPoint) ServletSessionConfig(io.undertow.servlet.api.ServletSessionConfig) HandlerWrapper(io.undertow.server.HandlerWrapper) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) SecureRandomSessionIdGenerator(io.undertow.server.session.SecureRandomSessionIdGenerator) SessionCookieConfig(org.wildfly.extension.undertow.SessionCookieConfig) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) SessionTrackingModeType(org.jboss.metadata.web.spec.SessionTrackingModeType) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 3 with SessionTrackingMode

use of javax.servlet.SessionTrackingMode in project tomcat by apache.

the class WebXml method toXml.

/**
     * Generate a web.xml in String form that matches the representation stored
     * in this object.
     *
     * @return The complete contents of web.xml as a String
     */
public String toXml() {
    StringBuilder sb = new StringBuilder(2048);
    // TODO - Various, icon, description etc elements are skipped - mainly
    //        because they are ignored when web.xml is parsed - see above
    // NOTE - Elements need to be written in the order defined in the 2.3
    //        DTD else validation of the merged web.xml will fail
    // NOTE - Some elements need to be skipped based on the version of the
    //        specification being used. Version is validated and starts at
    //        2.2. The version tests used in this method take advantage of
    //        this.
    // Declaration
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    // Root element
    if (publicId != null) {
        sb.append("<!DOCTYPE web-app PUBLIC\n");
        sb.append("  \"");
        sb.append(publicId);
        sb.append("\"\n");
        sb.append("  \"");
        if (XmlIdentifiers.WEB_22_PUBLIC.equals(publicId)) {
            sb.append(XmlIdentifiers.WEB_22_SYSTEM);
        } else {
            sb.append(XmlIdentifiers.WEB_23_SYSTEM);
        }
        sb.append("\">\n");
        sb.append("<web-app>");
    } else {
        String javaeeNamespace = null;
        String webXmlSchemaLocation = null;
        String version = getVersion();
        if ("2.4".equals(version)) {
            javaeeNamespace = XmlIdentifiers.JAVAEE_1_4_NS;
            webXmlSchemaLocation = XmlIdentifiers.WEB_24_XSD;
        } else if ("2.5".equals(version)) {
            javaeeNamespace = XmlIdentifiers.JAVAEE_5_NS;
            webXmlSchemaLocation = XmlIdentifiers.WEB_25_XSD;
        } else if ("3.0".equals(version)) {
            javaeeNamespace = XmlIdentifiers.JAVAEE_6_NS;
            webXmlSchemaLocation = XmlIdentifiers.WEB_30_XSD;
        } else if ("3.1".equals(version)) {
            javaeeNamespace = XmlIdentifiers.JAVAEE_7_NS;
            webXmlSchemaLocation = XmlIdentifiers.WEB_31_XSD;
        } else if ("4.0".equals(version)) {
            javaeeNamespace = XmlIdentifiers.JAVAEE_8_NS;
            webXmlSchemaLocation = XmlIdentifiers.WEB_40_XSD;
        }
        sb.append("<web-app xmlns=\"");
        sb.append(javaeeNamespace);
        sb.append("\"\n");
        sb.append("         xmlns:xsi=");
        sb.append("\"http://www.w3.org/2001/XMLSchema-instance\"\n");
        sb.append("         xsi:schemaLocation=\"");
        sb.append(javaeeNamespace);
        sb.append(" ");
        sb.append(webXmlSchemaLocation);
        sb.append("\"\n");
        sb.append("         version=\"");
        sb.append(getVersion());
        sb.append("\"");
        if ("2.4".equals(version)) {
            sb.append(">\n\n");
        } else {
            sb.append("\n         metadata-complete=\"true\">\n\n");
        }
    }
    appendElement(sb, INDENT2, "display-name", displayName);
    if (isDistributable()) {
        sb.append("  <distributable/>\n\n");
    }
    for (Map.Entry<String, String> entry : contextParams.entrySet()) {
        sb.append("  <context-param>\n");
        appendElement(sb, INDENT4, "param-name", entry.getKey());
        appendElement(sb, INDENT4, "param-value", entry.getValue());
        sb.append("  </context-param>\n");
    }
    sb.append('\n');
    // Filters were introduced in Servlet 2.3
    if (getMajorVersion() > 2 || getMinorVersion() > 2) {
        for (Map.Entry<String, FilterDef> entry : filters.entrySet()) {
            FilterDef filterDef = entry.getValue();
            sb.append("  <filter>\n");
            appendElement(sb, INDENT4, "description", filterDef.getDescription());
            appendElement(sb, INDENT4, "display-name", filterDef.getDisplayName());
            appendElement(sb, INDENT4, "filter-name", filterDef.getFilterName());
            appendElement(sb, INDENT4, "filter-class", filterDef.getFilterClass());
            // Async support was introduced for Servlet 3.0 onwards
            if (getMajorVersion() != 2) {
                appendElement(sb, INDENT4, "async-supported", filterDef.getAsyncSupported());
            }
            for (Map.Entry<String, String> param : filterDef.getParameterMap().entrySet()) {
                sb.append("    <init-param>\n");
                appendElement(sb, INDENT6, "param-name", param.getKey());
                appendElement(sb, INDENT6, "param-value", param.getValue());
                sb.append("    </init-param>\n");
            }
            sb.append("  </filter>\n");
        }
        sb.append('\n');
        for (FilterMap filterMap : filterMaps) {
            sb.append("  <filter-mapping>\n");
            appendElement(sb, INDENT4, "filter-name", filterMap.getFilterName());
            if (filterMap.getMatchAllServletNames()) {
                sb.append("    <servlet-name>*</servlet-name>\n");
            } else {
                for (String servletName : filterMap.getServletNames()) {
                    appendElement(sb, INDENT4, "servlet-name", servletName);
                }
            }
            if (filterMap.getMatchAllUrlPatterns()) {
                sb.append("    <url-pattern>*</url-pattern>\n");
            } else {
                for (String urlPattern : filterMap.getURLPatterns()) {
                    appendElement(sb, INDENT4, "url-pattern", encodeUrl(urlPattern));
                }
            }
            // dispatcher was added in Servlet 2.4
            if (getMajorVersion() > 2 || getMinorVersion() > 3) {
                for (String dispatcher : filterMap.getDispatcherNames()) {
                    if (getMajorVersion() == 2 && DispatcherType.ASYNC.name().equals(dispatcher)) {
                        continue;
                    }
                    appendElement(sb, INDENT4, "dispatcher", dispatcher);
                }
            }
            sb.append("  </filter-mapping>\n");
        }
        sb.append('\n');
    }
    // Listeners were introduced in Servlet 2.3
    if (getMajorVersion() > 2 || getMinorVersion() > 2) {
        for (String listener : listeners) {
            sb.append("  <listener>\n");
            appendElement(sb, INDENT4, "listener-class", listener);
            sb.append("  </listener>\n");
        }
        sb.append('\n');
    }
    for (Map.Entry<String, ServletDef> entry : servlets.entrySet()) {
        ServletDef servletDef = entry.getValue();
        sb.append("  <servlet>\n");
        appendElement(sb, INDENT4, "description", servletDef.getDescription());
        appendElement(sb, INDENT4, "display-name", servletDef.getDisplayName());
        appendElement(sb, INDENT4, "servlet-name", entry.getKey());
        appendElement(sb, INDENT4, "servlet-class", servletDef.getServletClass());
        appendElement(sb, INDENT4, "jsp-file", servletDef.getJspFile());
        for (Map.Entry<String, String> param : servletDef.getParameterMap().entrySet()) {
            sb.append("    <init-param>\n");
            appendElement(sb, INDENT6, "param-name", param.getKey());
            appendElement(sb, INDENT6, "param-value", param.getValue());
            sb.append("    </init-param>\n");
        }
        appendElement(sb, INDENT4, "load-on-startup", servletDef.getLoadOnStartup());
        appendElement(sb, INDENT4, "enabled", servletDef.getEnabled());
        // Async support was introduced for Servlet 3.0 onwards
        if (getMajorVersion() != 2) {
            appendElement(sb, INDENT4, "async-supported", servletDef.getAsyncSupported());
        }
        // servlet/run-as was introduced in Servlet 2.3
        if (getMajorVersion() > 2 || getMinorVersion() > 2) {
            if (servletDef.getRunAs() != null) {
                sb.append("    <run-as>\n");
                appendElement(sb, INDENT6, "role-name", servletDef.getRunAs());
                sb.append("    </run-as>\n");
            }
        }
        for (SecurityRoleRef roleRef : servletDef.getSecurityRoleRefs()) {
            sb.append("    <security-role-ref>\n");
            appendElement(sb, INDENT6, "role-name", roleRef.getName());
            appendElement(sb, INDENT6, "role-link", roleRef.getLink());
            sb.append("    </security-role-ref>\n");
        }
        // multipart-config was added in Servlet 3.0
        if (getMajorVersion() != 2) {
            MultipartDef multipartDef = servletDef.getMultipartDef();
            if (multipartDef != null) {
                sb.append("    <multipart-config>\n");
                appendElement(sb, INDENT6, "location", multipartDef.getLocation());
                appendElement(sb, INDENT6, "max-file-size", multipartDef.getMaxFileSize());
                appendElement(sb, INDENT6, "max-request-size", multipartDef.getMaxRequestSize());
                appendElement(sb, INDENT6, "file-size-threshold", multipartDef.getFileSizeThreshold());
                sb.append("    </multipart-config>\n");
            }
        }
        sb.append("  </servlet>\n");
    }
    sb.append('\n');
    for (Map.Entry<String, String> entry : servletMappings.entrySet()) {
        sb.append("  <servlet-mapping>\n");
        appendElement(sb, INDENT4, "servlet-name", entry.getValue());
        appendElement(sb, INDENT4, "url-pattern", encodeUrl(entry.getKey()));
        sb.append("  </servlet-mapping>\n");
    }
    sb.append('\n');
    if (sessionConfig != null) {
        sb.append("  <session-config>\n");
        appendElement(sb, INDENT4, "session-timeout", sessionConfig.getSessionTimeout());
        if (majorVersion >= 3) {
            sb.append("    <cookie-config>\n");
            appendElement(sb, INDENT6, "name", sessionConfig.getCookieName());
            appendElement(sb, INDENT6, "domain", sessionConfig.getCookieDomain());
            appendElement(sb, INDENT6, "path", sessionConfig.getCookiePath());
            appendElement(sb, INDENT6, "comment", sessionConfig.getCookieComment());
            appendElement(sb, INDENT6, "http-only", sessionConfig.getCookieHttpOnly());
            appendElement(sb, INDENT6, "secure", sessionConfig.getCookieSecure());
            appendElement(sb, INDENT6, "max-age", sessionConfig.getCookieMaxAge());
            sb.append("    </cookie-config>\n");
            for (SessionTrackingMode stm : sessionConfig.getSessionTrackingModes()) {
                appendElement(sb, INDENT4, "tracking-mode", stm.name());
            }
        }
        sb.append("  </session-config>\n\n");
    }
    for (Map.Entry<String, String> entry : mimeMappings.entrySet()) {
        sb.append("  <mime-mapping>\n");
        appendElement(sb, INDENT4, "extension", entry.getKey());
        appendElement(sb, INDENT4, "mime-type", entry.getValue());
        sb.append("  </mime-mapping>\n");
    }
    sb.append('\n');
    if (welcomeFiles.size() > 0) {
        sb.append("  <welcome-file-list>\n");
        for (String welcomeFile : welcomeFiles) {
            appendElement(sb, INDENT4, "welcome-file", welcomeFile);
        }
        sb.append("  </welcome-file-list>\n\n");
    }
    for (ErrorPage errorPage : errorPages.values()) {
        String exceptionType = errorPage.getExceptionType();
        int errorCode = errorPage.getErrorCode();
        if (exceptionType == null && errorCode == 0 && getMajorVersion() == 2) {
            // Default error pages are only supported from 3.0 onwards
            continue;
        }
        sb.append("  <error-page>\n");
        if (errorPage.getExceptionType() != null) {
            appendElement(sb, INDENT4, "exception-type", exceptionType);
        } else if (errorPage.getErrorCode() > 0) {
            appendElement(sb, INDENT4, "error-code", Integer.toString(errorCode));
        }
        appendElement(sb, INDENT4, "location", errorPage.getLocation());
        sb.append("  </error-page>\n");
    }
    sb.append('\n');
    // directly and jsp-property-group did not exist
    if (taglibs.size() > 0 || jspPropertyGroups.size() > 0) {
        if (getMajorVersion() > 2 || getMinorVersion() > 3) {
            sb.append("  <jsp-config>\n");
        }
        for (Map.Entry<String, String> entry : taglibs.entrySet()) {
            sb.append("    <taglib>\n");
            appendElement(sb, INDENT6, "taglib-uri", entry.getKey());
            appendElement(sb, INDENT6, "taglib-location", entry.getValue());
            sb.append("    </taglib>\n");
        }
        if (getMajorVersion() > 2 || getMinorVersion() > 3) {
            for (JspPropertyGroup jpg : jspPropertyGroups) {
                sb.append("    <jsp-property-group>\n");
                for (String urlPattern : jpg.getUrlPatterns()) {
                    appendElement(sb, INDENT6, "url-pattern", encodeUrl(urlPattern));
                }
                appendElement(sb, INDENT6, "el-ignored", jpg.getElIgnored());
                appendElement(sb, INDENT6, "page-encoding", jpg.getPageEncoding());
                appendElement(sb, INDENT6, "scripting-invalid", jpg.getScriptingInvalid());
                appendElement(sb, INDENT6, "is-xml", jpg.getIsXml());
                for (String prelude : jpg.getIncludePreludes()) {
                    appendElement(sb, INDENT6, "include-prelude", prelude);
                }
                for (String coda : jpg.getIncludeCodas()) {
                    appendElement(sb, INDENT6, "include-coda", coda);
                }
                appendElement(sb, INDENT6, "deferred-syntax-allowed-as-literal", jpg.getDeferredSyntax());
                appendElement(sb, INDENT6, "trim-directive-whitespaces", jpg.getTrimWhitespace());
                appendElement(sb, INDENT6, "default-content-type", jpg.getDefaultContentType());
                appendElement(sb, INDENT6, "buffer", jpg.getBuffer());
                appendElement(sb, INDENT6, "error-on-undeclared-namespace", jpg.getErrorOnUndeclaredNamespace());
                sb.append("    </jsp-property-group>\n");
            }
            sb.append("  </jsp-config>\n\n");
        }
    }
    // resource-env-ref was introduced in Servlet 2.3
    if (getMajorVersion() > 2 || getMinorVersion() > 2) {
        for (ContextResourceEnvRef resourceEnvRef : resourceEnvRefs.values()) {
            sb.append("  <resource-env-ref>\n");
            appendElement(sb, INDENT4, "description", resourceEnvRef.getDescription());
            appendElement(sb, INDENT4, "resource-env-ref-name", resourceEnvRef.getName());
            appendElement(sb, INDENT4, "resource-env-ref-type", resourceEnvRef.getType());
            // TODO mapped-name
            for (InjectionTarget target : resourceEnvRef.getInjectionTargets()) {
                sb.append("    <injection-target>\n");
                appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
                appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
                sb.append("    </injection-target>\n");
            }
            // TODO lookup-name
            sb.append("  </resource-env-ref>\n");
        }
        sb.append('\n');
    }
    for (ContextResource resourceRef : resourceRefs.values()) {
        sb.append("  <resource-ref>\n");
        appendElement(sb, INDENT4, "description", resourceRef.getDescription());
        appendElement(sb, INDENT4, "res-ref-name", resourceRef.getName());
        appendElement(sb, INDENT4, "res-type", resourceRef.getType());
        appendElement(sb, INDENT4, "res-auth", resourceRef.getAuth());
        // resource-ref/res-sharing-scope was introduced in Servlet 2.3
        if (getMajorVersion() > 2 || getMinorVersion() > 2) {
            appendElement(sb, INDENT4, "res-sharing-scope", resourceRef.getScope());
        }
        // TODO mapped-name
        for (InjectionTarget target : resourceRef.getInjectionTargets()) {
            sb.append("    <injection-target>\n");
            appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
            appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
            sb.append("    </injection-target>\n");
        }
        // TODO lookup-name
        sb.append("  </resource-ref>\n");
    }
    sb.append('\n');
    for (SecurityConstraint constraint : securityConstraints) {
        sb.append("  <security-constraint>\n");
        // security-constraint/display-name was introduced in Servlet 2.3
        if (getMajorVersion() > 2 || getMinorVersion() > 2) {
            appendElement(sb, INDENT4, "display-name", constraint.getDisplayName());
        }
        for (SecurityCollection collection : constraint.findCollections()) {
            sb.append("    <web-resource-collection>\n");
            appendElement(sb, INDENT6, "web-resource-name", collection.getName());
            appendElement(sb, INDENT6, "description", collection.getDescription());
            for (String urlPattern : collection.findPatterns()) {
                appendElement(sb, INDENT6, "url-pattern", encodeUrl(urlPattern));
            }
            for (String method : collection.findMethods()) {
                appendElement(sb, INDENT6, "http-method", method);
            }
            for (String method : collection.findOmittedMethods()) {
                appendElement(sb, INDENT6, "http-method-omission", method);
            }
            sb.append("    </web-resource-collection>\n");
        }
        if (constraint.findAuthRoles().length > 0) {
            sb.append("    <auth-constraint>\n");
            for (String role : constraint.findAuthRoles()) {
                appendElement(sb, INDENT6, "role-name", role);
            }
            sb.append("    </auth-constraint>\n");
        }
        if (constraint.getUserConstraint() != null) {
            sb.append("    <user-data-constraint>\n");
            appendElement(sb, INDENT6, "transport-guarantee", constraint.getUserConstraint());
            sb.append("    </user-data-constraint>\n");
        }
        sb.append("  </security-constraint>\n");
    }
    sb.append('\n');
    if (loginConfig != null) {
        sb.append("  <login-config>\n");
        appendElement(sb, INDENT4, "auth-method", loginConfig.getAuthMethod());
        appendElement(sb, INDENT4, "realm-name", loginConfig.getRealmName());
        if (loginConfig.getErrorPage() != null || loginConfig.getLoginPage() != null) {
            sb.append("    <form-login-config>\n");
            appendElement(sb, INDENT6, "form-login-page", loginConfig.getLoginPage());
            appendElement(sb, INDENT6, "form-error-page", loginConfig.getErrorPage());
            sb.append("    </form-login-config>\n");
        }
        sb.append("  </login-config>\n\n");
    }
    for (String roleName : securityRoles) {
        sb.append("  <security-role>\n");
        appendElement(sb, INDENT4, "role-name", roleName);
        sb.append("  </security-role>\n");
    }
    for (ContextEnvironment envEntry : envEntries.values()) {
        sb.append("  <env-entry>\n");
        appendElement(sb, INDENT4, "description", envEntry.getDescription());
        appendElement(sb, INDENT4, "env-entry-name", envEntry.getName());
        appendElement(sb, INDENT4, "env-entry-type", envEntry.getType());
        appendElement(sb, INDENT4, "env-entry-value", envEntry.getValue());
        // TODO mapped-name
        for (InjectionTarget target : envEntry.getInjectionTargets()) {
            sb.append("    <injection-target>\n");
            appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
            appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
            sb.append("    </injection-target>\n");
        }
        // TODO lookup-name
        sb.append("  </env-entry>\n");
    }
    sb.append('\n');
    for (ContextEjb ejbRef : ejbRefs.values()) {
        sb.append("  <ejb-ref>\n");
        appendElement(sb, INDENT4, "description", ejbRef.getDescription());
        appendElement(sb, INDENT4, "ejb-ref-name", ejbRef.getName());
        appendElement(sb, INDENT4, "ejb-ref-type", ejbRef.getType());
        appendElement(sb, INDENT4, "home", ejbRef.getHome());
        appendElement(sb, INDENT4, "remote", ejbRef.getRemote());
        appendElement(sb, INDENT4, "ejb-link", ejbRef.getLink());
        // TODO mapped-name
        for (InjectionTarget target : ejbRef.getInjectionTargets()) {
            sb.append("    <injection-target>\n");
            appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
            appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
            sb.append("    </injection-target>\n");
        }
        // TODO lookup-name
        sb.append("  </ejb-ref>\n");
    }
    sb.append('\n');
    // ejb-local-ref was introduced in Servlet 2.3
    if (getMajorVersion() > 2 || getMinorVersion() > 2) {
        for (ContextLocalEjb ejbLocalRef : ejbLocalRefs.values()) {
            sb.append("  <ejb-local-ref>\n");
            appendElement(sb, INDENT4, "description", ejbLocalRef.getDescription());
            appendElement(sb, INDENT4, "ejb-ref-name", ejbLocalRef.getName());
            appendElement(sb, INDENT4, "ejb-ref-type", ejbLocalRef.getType());
            appendElement(sb, INDENT4, "local-home", ejbLocalRef.getHome());
            appendElement(sb, INDENT4, "local", ejbLocalRef.getLocal());
            appendElement(sb, INDENT4, "ejb-link", ejbLocalRef.getLink());
            // TODO mapped-name
            for (InjectionTarget target : ejbLocalRef.getInjectionTargets()) {
                sb.append("    <injection-target>\n");
                appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
                appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
                sb.append("    </injection-target>\n");
            }
            // TODO lookup-name
            sb.append("  </ejb-local-ref>\n");
        }
        sb.append('\n');
    }
    // service-ref was introduced in Servlet 2.4
    if (getMajorVersion() > 2 || getMinorVersion() > 3) {
        for (ContextService serviceRef : serviceRefs.values()) {
            sb.append("  <service-ref>\n");
            appendElement(sb, INDENT4, "description", serviceRef.getDescription());
            appendElement(sb, INDENT4, "display-name", serviceRef.getDisplayname());
            appendElement(sb, INDENT4, "service-ref-name", serviceRef.getName());
            appendElement(sb, INDENT4, "service-interface", serviceRef.getInterface());
            appendElement(sb, INDENT4, "service-ref-type", serviceRef.getType());
            appendElement(sb, INDENT4, "wsdl-file", serviceRef.getWsdlfile());
            appendElement(sb, INDENT4, "jaxrpc-mapping-file", serviceRef.getJaxrpcmappingfile());
            String qname = serviceRef.getServiceqnameNamespaceURI();
            if (qname != null) {
                qname = qname + ":";
            }
            qname = qname + serviceRef.getServiceqnameLocalpart();
            appendElement(sb, INDENT4, "service-qname", qname);
            Iterator<String> endpointIter = serviceRef.getServiceendpoints();
            while (endpointIter.hasNext()) {
                String endpoint = endpointIter.next();
                sb.append("    <port-component-ref>\n");
                appendElement(sb, INDENT6, "service-endpoint-interface", endpoint);
                appendElement(sb, INDENT6, "port-component-link", serviceRef.getProperty(endpoint));
                sb.append("    </port-component-ref>\n");
            }
            Iterator<String> handlerIter = serviceRef.getHandlers();
            while (handlerIter.hasNext()) {
                String handler = handlerIter.next();
                sb.append("    <handler>\n");
                ContextHandler ch = serviceRef.getHandler(handler);
                appendElement(sb, INDENT6, "handler-name", ch.getName());
                appendElement(sb, INDENT6, "handler-class", ch.getHandlerclass());
                sb.append("    </handler>\n");
            }
            // TODO mapped-name
            for (InjectionTarget target : serviceRef.getInjectionTargets()) {
                sb.append("    <injection-target>\n");
                appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
                appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
                sb.append("    </injection-target>\n");
            }
            // TODO lookup-name
            sb.append("  </service-ref>\n");
        }
        sb.append('\n');
    }
    if (!postConstructMethods.isEmpty()) {
        for (Entry<String, String> entry : postConstructMethods.entrySet()) {
            sb.append("  <post-construct>\n");
            appendElement(sb, INDENT4, "lifecycle-callback-class", entry.getKey());
            appendElement(sb, INDENT4, "lifecycle-callback-method", entry.getValue());
            sb.append("  </post-construct>\n");
        }
        sb.append('\n');
    }
    if (!preDestroyMethods.isEmpty()) {
        for (Entry<String, String> entry : preDestroyMethods.entrySet()) {
            sb.append("  <pre-destroy>\n");
            appendElement(sb, INDENT4, "lifecycle-callback-class", entry.getKey());
            appendElement(sb, INDENT4, "lifecycle-callback-method", entry.getValue());
            sb.append("  </pre-destroy>\n");
        }
        sb.append('\n');
    }
    // Servlet 2.4
    if (getMajorVersion() > 2 || getMinorVersion() > 3) {
        for (MessageDestinationRef mdr : messageDestinationRefs.values()) {
            sb.append("  <message-destination-ref>\n");
            appendElement(sb, INDENT4, "description", mdr.getDescription());
            appendElement(sb, INDENT4, "message-destination-ref-name", mdr.getName());
            appendElement(sb, INDENT4, "message-destination-type", mdr.getType());
            appendElement(sb, INDENT4, "message-destination-usage", mdr.getUsage());
            appendElement(sb, INDENT4, "message-destination-link", mdr.getLink());
            // TODO mapped-name
            for (InjectionTarget target : mdr.getInjectionTargets()) {
                sb.append("    <injection-target>\n");
                appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass());
                appendElement(sb, INDENT6, "injection-target-name", target.getTargetName());
                sb.append("    </injection-target>\n");
            }
            // TODO lookup-name
            sb.append("  </message-destination-ref>\n");
        }
        sb.append('\n');
        for (MessageDestination md : messageDestinations.values()) {
            sb.append("  <message-destination>\n");
            appendElement(sb, INDENT4, "description", md.getDescription());
            appendElement(sb, INDENT4, "display-name", md.getDisplayName());
            appendElement(sb, INDENT4, "message-destination-name", md.getName());
            // TODO mapped-name
            sb.append("  </message-destination>\n");
        }
        sb.append('\n');
    }
    // locale-encoding-mapping-list was introduced in Servlet 2.4
    if (getMajorVersion() > 2 || getMinorVersion() > 3) {
        if (localeEncodingMappings.size() > 0) {
            sb.append("  <locale-encoding-mapping-list>\n");
            for (Map.Entry<String, String> entry : localeEncodingMappings.entrySet()) {
                sb.append("    <locale-encoding-mapping>\n");
                appendElement(sb, INDENT6, "locale", entry.getKey());
                appendElement(sb, INDENT6, "encoding", entry.getValue());
                sb.append("    </locale-encoding-mapping>\n");
            }
            sb.append("  </locale-encoding-mapping-list>\n");
            sb.append("\n");
        }
    }
    // deny-uncovered-http-methods was introduced in Servlet 3.1
    if (getMajorVersion() > 3 || (getMajorVersion() == 3 && getMinorVersion() > 0)) {
        if (denyUncoveredHttpMethods) {
            sb.append("  <deny-uncovered-http-methods/>");
            sb.append("\n");
        }
    }
    // request-encoding and response-encoding was introduced in Servlet 4.0
    if (getMajorVersion() >= 4) {
        appendElement(sb, INDENT2, "request-encoding", requestEncoding);
        appendElement(sb, INDENT2, "response-encoding", responseEncoding);
    }
    sb.append("</web-app>");
    return sb.toString();
}
Also used : SessionTrackingMode(javax.servlet.SessionTrackingMode) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 4 with SessionTrackingMode

use of javax.servlet.SessionTrackingMode in project jetty.project by eclipse.

the class StandardDescriptorProcessor method visitSessionConfig.

public void visitSessionConfig(WebAppContext context, Descriptor descriptor, XmlParser.Node node) {
    XmlParser.Node tNode = node.get("session-timeout");
    if (tNode != null) {
        java.math.BigDecimal asDecimal = new java.math.BigDecimal(tNode.toString(false, true));
        if (asDecimal.compareTo(org.eclipse.jetty.server.session.SessionHandler.MAX_INACTIVE_MINUTES) > 0)
            throw new IllegalStateException("Max session-timeout in minutes is " + org.eclipse.jetty.server.session.SessionHandler.MAX_INACTIVE_MINUTES);
        context.getSessionHandler().setMaxInactiveInterval(asDecimal.intValueExact() * 60);
    }
    //Servlet Spec 3.0
    // <tracking-mode>
    // this is additive across web-fragments
    Iterator<Node> iter = node.iterator("tracking-mode");
    if (iter.hasNext()) {
        Set<SessionTrackingMode> modes = null;
        Origin o = context.getMetaData().getOrigin("session.tracking-mode");
        switch(o) {
            //not previously set, starting fresh
            case NotSet:
            case //previously set in web defaults, allow this descriptor to start fresh
            WebDefaults:
                {
                    modes = new HashSet<SessionTrackingMode>();
                    context.getMetaData().setOrigin("session.tracking-mode", descriptor);
                    break;
                }
            case WebXml:
            case WebFragment:
            case WebOverride:
                {
                    //if setting from an override descriptor, start afresh, otherwise add-in tracking-modes
                    if (descriptor instanceof OverrideDescriptor)
                        modes = new HashSet<SessionTrackingMode>();
                    else
                        modes = new HashSet<SessionTrackingMode>(context.getSessionHandler().getEffectiveSessionTrackingModes());
                    context.getMetaData().setOrigin("session.tracking-mode", descriptor);
                    break;
                }
            default:
                // TODO throw ISE?   
                LOG.warn(new Throwable());
        }
        while (iter.hasNext()) {
            XmlParser.Node mNode = (XmlParser.Node) iter.next();
            String trackMode = mNode.toString(false, true);
            modes.add(SessionTrackingMode.valueOf(trackMode));
        }
        context.getSessionHandler().setSessionTrackingModes(modes);
    }
    //Servlet Spec 3.0
    //<cookie-config>
    XmlParser.Node cookieConfig = node.get("cookie-config");
    if (cookieConfig != null) {
        //  <name>
        String name = cookieConfig.getString("name", false, true);
        if (name != null) {
            switch(context.getMetaData().getOrigin("cookie-config.name")) {
                case NotSet:
                    {
                        //no <cookie-config><name> set yet, accept it
                        context.getSessionHandler().getSessionCookieConfig().setName(name);
                        context.getMetaData().setOrigin("cookie-config.name", descriptor);
                        break;
                    }
                case WebXml:
                case WebDefaults:
                case WebOverride:
                    {
                        //<cookie-config><name> set in a web xml, only allow web-default/web-override to change
                        if (!(descriptor instanceof FragmentDescriptor)) {
                            context.getSessionHandler().getSessionCookieConfig().setName(name);
                            context.getMetaData().setOrigin("cookie-config.name", descriptor);
                        }
                        break;
                    }
                case WebFragment:
                    {
                        //a web-fragment set the value, all web-fragments must have the same value
                        if (!context.getSessionHandler().getSessionCookieConfig().getName().equals(name))
                            throw new IllegalStateException("Conflicting cookie-config name " + name + " in " + descriptor.getResource());
                        break;
                    }
                default:
                    // TODO throw ISE?
                    LOG.warn(new Throwable());
            }
        }
        //  <domain>
        String domain = cookieConfig.getString("domain", false, true);
        if (domain != null) {
            switch(context.getMetaData().getOrigin("cookie-config.domain")) {
                case NotSet:
                    {
                        //no <cookie-config><domain> set yet, accept it
                        context.getSessionHandler().getSessionCookieConfig().setDomain(domain);
                        context.getMetaData().setOrigin("cookie-config.domain", descriptor);
                        break;
                    }
                case WebXml:
                case WebDefaults:
                case WebOverride:
                    {
                        //<cookie-config><domain> set in a web xml, only allow web-default/web-override to change
                        if (!(descriptor instanceof FragmentDescriptor)) {
                            context.getSessionHandler().getSessionCookieConfig().setDomain(domain);
                            context.getMetaData().setOrigin("cookie-config.domain", descriptor);
                        }
                        break;
                    }
                case WebFragment:
                    {
                        //a web-fragment set the value, all web-fragments must have the same value
                        if (!context.getSessionHandler().getSessionCookieConfig().getDomain().equals(domain))
                            throw new IllegalStateException("Conflicting cookie-config domain " + domain + " in " + descriptor.getResource());
                        break;
                    }
                default:
                    // TODO throw ISE?
                    LOG.warn(new Throwable());
            }
        }
        //  <path>
        String path = cookieConfig.getString("path", false, true);
        if (path != null) {
            switch(context.getMetaData().getOrigin("cookie-config.path")) {
                case NotSet:
                    {
                        //no <cookie-config><domain> set yet, accept it
                        context.getSessionHandler().getSessionCookieConfig().setPath(path);
                        context.getMetaData().setOrigin("cookie-config.path", descriptor);
                        break;
                    }
                case WebXml:
                case WebDefaults:
                case WebOverride:
                    {
                        //<cookie-config><domain> set in a web xml, only allow web-default/web-override to change
                        if (!(descriptor instanceof FragmentDescriptor)) {
                            context.getSessionHandler().getSessionCookieConfig().setPath(path);
                            context.getMetaData().setOrigin("cookie-config.path", descriptor);
                        }
                        break;
                    }
                case WebFragment:
                    {
                        //a web-fragment set the value, all web-fragments must have the same value
                        if (!context.getSessionHandler().getSessionCookieConfig().getPath().equals(path))
                            throw new IllegalStateException("Conflicting cookie-config path " + path + " in " + descriptor.getResource());
                        break;
                    }
                default:
                    // TODO throw ISE?
                    LOG.warn(new Throwable());
            }
        }
        //  <comment>
        String comment = cookieConfig.getString("comment", false, true);
        if (comment != null) {
            switch(context.getMetaData().getOrigin("cookie-config.comment")) {
                case NotSet:
                    {
                        //no <cookie-config><comment> set yet, accept it
                        context.getSessionHandler().getSessionCookieConfig().setComment(comment);
                        context.getMetaData().setOrigin("cookie-config.comment", descriptor);
                        break;
                    }
                case WebXml:
                case WebDefaults:
                case WebOverride:
                    {
                        //<cookie-config><comment> set in a web xml, only allow web-default/web-override to change
                        if (!(descriptor instanceof FragmentDescriptor)) {
                            context.getSessionHandler().getSessionCookieConfig().setComment(comment);
                            context.getMetaData().setOrigin("cookie-config.comment", descriptor);
                        }
                        break;
                    }
                case WebFragment:
                    {
                        //a web-fragment set the value, all web-fragments must have the same value
                        if (!context.getSessionHandler().getSessionCookieConfig().getComment().equals(comment))
                            throw new IllegalStateException("Conflicting cookie-config comment " + comment + " in " + descriptor.getResource());
                        break;
                    }
                default:
                    // TODO throw ISE?
                    LOG.warn(new Throwable());
            }
        }
        //  <http-only>true/false
        tNode = cookieConfig.get("http-only");
        if (tNode != null) {
            boolean httpOnly = Boolean.parseBoolean(tNode.toString(false, true));
            switch(context.getMetaData().getOrigin("cookie-config.http-only")) {
                case NotSet:
                    {
                        //no <cookie-config><http-only> set yet, accept it
                        context.getSessionHandler().getSessionCookieConfig().setHttpOnly(httpOnly);
                        context.getMetaData().setOrigin("cookie-config.http-only", descriptor);
                        break;
                    }
                case WebXml:
                case WebDefaults:
                case WebOverride:
                    {
                        //<cookie-config><http-only> set in a web xml, only allow web-default/web-override to change
                        if (!(descriptor instanceof FragmentDescriptor)) {
                            context.getSessionHandler().getSessionCookieConfig().setHttpOnly(httpOnly);
                            context.getMetaData().setOrigin("cookie-config.http-only", descriptor);
                        }
                        break;
                    }
                case WebFragment:
                    {
                        //a web-fragment set the value, all web-fragments must have the same value
                        if (context.getSessionHandler().getSessionCookieConfig().isHttpOnly() != httpOnly)
                            throw new IllegalStateException("Conflicting cookie-config http-only " + httpOnly + " in " + descriptor.getResource());
                        break;
                    }
                default:
                    // TODO throw ISE?
                    LOG.warn(new Throwable());
            }
        }
        //  <secure>true/false
        tNode = cookieConfig.get("secure");
        if (tNode != null) {
            boolean secure = Boolean.parseBoolean(tNode.toString(false, true));
            switch(context.getMetaData().getOrigin("cookie-config.secure")) {
                case NotSet:
                    {
                        //no <cookie-config><secure> set yet, accept it
                        context.getSessionHandler().getSessionCookieConfig().setSecure(secure);
                        context.getMetaData().setOrigin("cookie-config.secure", descriptor);
                        break;
                    }
                case WebXml:
                case WebDefaults:
                case WebOverride:
                    {
                        //<cookie-config><secure> set in a web xml, only allow web-default/web-override to change
                        if (!(descriptor instanceof FragmentDescriptor)) {
                            context.getSessionHandler().getSessionCookieConfig().setSecure(secure);
                            context.getMetaData().setOrigin("cookie-config.secure", descriptor);
                        }
                        break;
                    }
                case WebFragment:
                    {
                        //a web-fragment set the value, all web-fragments must have the same value
                        if (context.getSessionHandler().getSessionCookieConfig().isSecure() != secure)
                            throw new IllegalStateException("Conflicting cookie-config secure " + secure + " in " + descriptor.getResource());
                        break;
                    }
                default:
                    // TODO throw ISE?
                    LOG.warn(new Throwable());
            }
        }
        //  <max-age>
        tNode = cookieConfig.get("max-age");
        if (tNode != null) {
            int maxAge = Integer.parseInt(tNode.toString(false, true));
            switch(context.getMetaData().getOrigin("cookie-config.max-age")) {
                case NotSet:
                    {
                        //no <cookie-config><max-age> set yet, accept it
                        context.getSessionHandler().getSessionCookieConfig().setMaxAge(maxAge);
                        context.getMetaData().setOrigin("cookie-config.max-age", descriptor);
                        break;
                    }
                case WebXml:
                case WebDefaults:
                case WebOverride:
                    {
                        //<cookie-config><max-age> set in a web xml, only allow web-default/web-override to change
                        if (!(descriptor instanceof FragmentDescriptor)) {
                            context.getSessionHandler().getSessionCookieConfig().setMaxAge(maxAge);
                            context.getMetaData().setOrigin("cookie-config.max-age", descriptor);
                        }
                        break;
                    }
                case WebFragment:
                    {
                        //a web-fragment set the value, all web-fragments must have the same value
                        if (context.getSessionHandler().getSessionCookieConfig().getMaxAge() != maxAge)
                            throw new IllegalStateException("Conflicting cookie-config max-age " + maxAge + " in " + descriptor.getResource());
                        break;
                    }
                default:
                    // TODO throw ISE?
                    LOG.warn(new Throwable());
            }
        }
    }
}
Also used : XmlParser(org.eclipse.jetty.xml.XmlParser) SessionTrackingMode(javax.servlet.SessionTrackingMode) Node(org.eclipse.jetty.xml.XmlParser.Node) Node(org.eclipse.jetty.xml.XmlParser.Node) Constraint(org.eclipse.jetty.util.security.Constraint) HashSet(java.util.HashSet)

Example 5 with SessionTrackingMode

use of javax.servlet.SessionTrackingMode in project jetty.project by eclipse.

the class QuickStartDescriptorGenerator method generateQuickStartWebXml.

/**
     * Perform the generation of the xml file
     * @param stream the stream to generate the quickstart-web.xml to
     * @throws IOException if unable to generate the quickstart-web.xml
     * @throws FileNotFoundException if unable to find the file 
     */
public void generateQuickStartWebXml(OutputStream stream) throws FileNotFoundException, IOException {
    if (_webApp == null)
        throw new IllegalStateException("No webapp for quickstart generation");
    if (stream == null)
        throw new IllegalStateException("No output for quickstart generation");
    _webApp.getMetaData().getOrigins();
    if (_webApp.getBaseResource() == null)
        throw new IllegalArgumentException("No base resource for " + this);
    LOG.info("Quickstart generating");
    XmlAppendable out = new XmlAppendable(stream, "UTF-8");
    MetaData md = _webApp.getMetaData();
    Map<String, String> webappAttr = new HashMap<>();
    webappAttr.put("xmlns", "http://xmlns.jcp.org/xml/ns/javaee");
    webappAttr.put("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    webappAttr.put("xsi:schemaLocation", "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd");
    webappAttr.put("metadata-complete", "true");
    webappAttr.put("version", "3.1");
    out.openTag("web-app", webappAttr);
    if (_webApp.getDisplayName() != null)
        out.tag("display-name", _webApp.getDisplayName());
    // Set some special context parameters
    // The location of the war file on disk
    AttributeNormalizer normalizer = new AttributeNormalizer(_webApp.getBaseResource());
    // The library order
    addContextParamFromAttribute(out, ServletContext.ORDERED_LIBS);
    //the servlet container initializers
    addContextParamFromAttribute(out, AnnotationConfiguration.CONTAINER_INITIALIZERS);
    //the tlds discovered
    addContextParamFromAttribute(out, MetaInfConfiguration.METAINF_TLDS, normalizer);
    //the META-INF/resources discovered
    addContextParamFromAttribute(out, MetaInfConfiguration.METAINF_RESOURCES, normalizer);
    //add the name of the origin attribute, if it is being used
    if (_generateOrigin) {
        out.openTag("context-param").tag("param-name", ORIGIN).tag("param-value", _originAttribute).closeTag();
    }
    // init params
    for (String p : _webApp.getInitParams().keySet()) out.openTag("context-param", origin(md, "context-param." + p)).tag("param-name", p).tag("param-value", _webApp.getInitParameter(p)).closeTag();
    if (_webApp.getEventListeners() != null)
        for (EventListener e : _webApp.getEventListeners()) out.openTag("listener", origin(md, e.getClass().getCanonicalName() + ".listener")).tag("listener-class", e.getClass().getCanonicalName()).closeTag();
    ServletHandler servlets = _webApp.getServletHandler();
    if (servlets.getFilters() != null) {
        for (FilterHolder holder : servlets.getFilters()) outholder(out, md, holder);
    }
    if (servlets.getFilterMappings() != null) {
        for (FilterMapping mapping : servlets.getFilterMappings()) {
            out.openTag("filter-mapping");
            out.tag("filter-name", mapping.getFilterName());
            if (mapping.getPathSpecs() != null)
                for (String s : mapping.getPathSpecs()) out.tag("url-pattern", s);
            if (mapping.getServletNames() != null)
                for (String n : mapping.getServletNames()) out.tag("servlet-name", n);
            if (!mapping.isDefaultDispatches()) {
                if (mapping.appliesTo(DispatcherType.REQUEST))
                    out.tag("dispatcher", "REQUEST");
                if (mapping.appliesTo(DispatcherType.ASYNC))
                    out.tag("dispatcher", "ASYNC");
                if (mapping.appliesTo(DispatcherType.ERROR))
                    out.tag("dispatcher", "ERROR");
                if (mapping.appliesTo(DispatcherType.FORWARD))
                    out.tag("dispatcher", "FORWARD");
                if (mapping.appliesTo(DispatcherType.INCLUDE))
                    out.tag("dispatcher", "INCLUDE");
            }
            out.closeTag();
        }
    }
    if (servlets.getServlets() != null) {
        for (ServletHolder holder : servlets.getServlets()) outholder(out, md, holder);
    }
    if (servlets.getServletMappings() != null) {
        for (ServletMapping mapping : servlets.getServletMappings()) {
            out.openTag("servlet-mapping", origin(md, mapping.getServletName() + ".servlet.mappings"));
            out.tag("servlet-name", mapping.getServletName());
            if (mapping.getPathSpecs() != null)
                for (String s : mapping.getPathSpecs()) out.tag("url-pattern", s);
            out.closeTag();
        }
    }
    // Security elements
    SecurityHandler security = _webApp.getSecurityHandler();
    if (security != null && (security.getRealmName() != null || security.getAuthMethod() != null)) {
        out.openTag("login-config");
        if (security.getAuthMethod() != null)
            out.tag("auth-method", origin(md, "auth-method"), security.getAuthMethod());
        if (security.getRealmName() != null)
            out.tag("realm-name", origin(md, "realm-name"), security.getRealmName());
        if (Constraint.__FORM_AUTH.equalsIgnoreCase(security.getAuthMethod())) {
            out.openTag("form-login-config");
            out.tag("form-login-page", origin(md, "form-login-page"), security.getInitParameter(FormAuthenticator.__FORM_LOGIN_PAGE));
            out.tag("form-error-page", origin(md, "form-error-page"), security.getInitParameter(FormAuthenticator.__FORM_ERROR_PAGE));
            out.closeTag();
        }
        out.closeTag();
    }
    if (security instanceof ConstraintAware) {
        ConstraintAware ca = (ConstraintAware) security;
        for (String r : ca.getRoles()) out.openTag("security-role").tag("role-name", r).closeTag();
        for (ConstraintMapping m : ca.getConstraintMappings()) {
            out.openTag("security-constraint");
            out.openTag("web-resource-collection");
            {
                if (m.getConstraint().getName() != null)
                    out.tag("web-resource-name", m.getConstraint().getName());
                if (m.getPathSpec() != null)
                    out.tag("url-pattern", origin(md, "constraint.url." + m.getPathSpec()), m.getPathSpec());
                if (m.getMethod() != null)
                    out.tag("http-method", m.getMethod());
                if (m.getMethodOmissions() != null)
                    for (String o : m.getMethodOmissions()) out.tag("http-method-omission", o);
                out.closeTag();
            }
            if (m.getConstraint().getAuthenticate()) {
                String[] roles = m.getConstraint().getRoles();
                if (roles != null && roles.length > 0) {
                    out.openTag("auth-constraint");
                    if (m.getConstraint().getRoles() != null)
                        for (String r : m.getConstraint().getRoles()) out.tag("role-name", r);
                    out.closeTag();
                } else
                    out.tag("auth-constraint");
            }
            switch(m.getConstraint().getDataConstraint()) {
                case Constraint.DC_NONE:
                    out.openTag("user-data-constraint").tag("transport-guarantee", "NONE").closeTag();
                    break;
                case Constraint.DC_INTEGRAL:
                    out.openTag("user-data-constraint").tag("transport-guarantee", "INTEGRAL").closeTag();
                    break;
                case Constraint.DC_CONFIDENTIAL:
                    out.openTag("user-data-constraint").tag("transport-guarantee", "CONFIDENTIAL").closeTag();
                    break;
                default:
                    break;
            }
            out.closeTag();
        }
    }
    if (_webApp.getWelcomeFiles() != null) {
        out.openTag("welcome-file-list");
        for (String welcomeFile : _webApp.getWelcomeFiles()) {
            out.tag("welcome-file", welcomeFile);
        }
        out.closeTag();
    }
    Map<String, String> localeEncodings = _webApp.getLocaleEncodings();
    if (localeEncodings != null && !localeEncodings.isEmpty()) {
        out.openTag("locale-encoding-mapping-list");
        for (Map.Entry<String, String> entry : localeEncodings.entrySet()) {
            out.openTag("locale-encoding-mapping", origin(md, "locale-encoding." + entry.getKey()));
            out.tag("locale", entry.getKey());
            out.tag("encoding", entry.getValue());
            out.closeTag();
        }
        out.closeTag();
    }
    //session-config
    if (_webApp.getSessionHandler() != null) {
        out.openTag("session-config");
        int maxInactiveSec = _webApp.getSessionHandler().getMaxInactiveInterval();
        out.tag("session-timeout", (maxInactiveSec == 0 ? "0" : Integer.toString(maxInactiveSec / 60)));
        //cookie-config
        SessionCookieConfig cookieConfig = _webApp.getSessionHandler().getSessionCookieConfig();
        if (cookieConfig != null) {
            out.openTag("cookie-config");
            if (cookieConfig.getName() != null)
                out.tag("name", origin(md, "cookie-config.name"), cookieConfig.getName());
            if (cookieConfig.getDomain() != null)
                out.tag("domain", origin(md, "cookie-config.domain"), cookieConfig.getDomain());
            if (cookieConfig.getPath() != null)
                out.tag("path", origin(md, "cookie-config.path"), cookieConfig.getPath());
            if (cookieConfig.getComment() != null)
                out.tag("comment", origin(md, "cookie-config.comment"), cookieConfig.getComment());
            out.tag("http-only", origin(md, "cookie-config.http-only"), Boolean.toString(cookieConfig.isHttpOnly()));
            out.tag("secure", origin(md, "cookie-config.secure"), Boolean.toString(cookieConfig.isSecure()));
            out.tag("max-age", origin(md, "cookie-config.max-age"), Integer.toString(cookieConfig.getMaxAge()));
            out.closeTag();
        }
        // tracking-modes
        Set<SessionTrackingMode> modes = _webApp.getSessionHandler().getEffectiveSessionTrackingModes();
        if (modes != null) {
            for (SessionTrackingMode mode : modes) out.tag("tracking-mode", mode.toString());
        }
        out.closeTag();
    }
    //error-pages
    Map<String, String> errorPages = ((ErrorPageErrorHandler) _webApp.getErrorHandler()).getErrorPages();
    if (errorPages != null) {
        for (Map.Entry<String, String> entry : errorPages.entrySet()) {
            out.openTag("error-page", origin(md, "error." + entry.getKey()));
            //a global or default error page has no code or exception               
            if (!ErrorPageErrorHandler.GLOBAL_ERROR_PAGE.equals(entry.getKey())) {
                if (entry.getKey().matches("\\d{3}"))
                    out.tag("error-code", entry.getKey());
                else
                    out.tag("exception-type", entry.getKey());
            }
            out.tag("location", entry.getValue());
            out.closeTag();
        }
    }
    //mime-types
    MimeTypes mimeTypes = _webApp.getMimeTypes();
    if (mimeTypes != null) {
        for (Map.Entry<String, String> entry : mimeTypes.getMimeMap().entrySet()) {
            out.openTag("mime-mapping");
            out.tag("extension", origin(md, "extension." + entry.getKey()), entry.getKey());
            out.tag("mime-type", entry.getValue());
            out.closeTag();
        }
    }
    //jsp-config
    JspConfig jspConfig = (JspConfig) _webApp.getServletContext().getJspConfigDescriptor();
    if (jspConfig != null) {
        out.openTag("jsp-config");
        Collection<TaglibDescriptor> tlds = jspConfig.getTaglibs();
        if (tlds != null && !tlds.isEmpty()) {
            for (TaglibDescriptor tld : tlds) {
                out.openTag("taglib");
                out.tag("taglib-uri", tld.getTaglibURI());
                out.tag("taglib-location", tld.getTaglibLocation());
                out.closeTag();
            }
        }
        Collection<JspPropertyGroupDescriptor> jspPropertyGroups = jspConfig.getJspPropertyGroups();
        if (jspPropertyGroups != null && !jspPropertyGroups.isEmpty()) {
            for (JspPropertyGroupDescriptor jspPropertyGroup : jspPropertyGroups) {
                out.openTag("jsp-property-group");
                Collection<String> strings = jspPropertyGroup.getUrlPatterns();
                if (strings != null && !strings.isEmpty()) {
                    for (String urlPattern : strings) out.tag("url-pattern", urlPattern);
                }
                if (jspPropertyGroup.getElIgnored() != null)
                    out.tag("el-ignored", jspPropertyGroup.getElIgnored());
                if (jspPropertyGroup.getPageEncoding() != null)
                    out.tag("page-encoding", jspPropertyGroup.getPageEncoding());
                if (jspPropertyGroup.getScriptingInvalid() != null)
                    out.tag("scripting-invalid", jspPropertyGroup.getScriptingInvalid());
                if (jspPropertyGroup.getIsXml() != null)
                    out.tag("is-xml", jspPropertyGroup.getIsXml());
                if (jspPropertyGroup.getDeferredSyntaxAllowedAsLiteral() != null)
                    out.tag("deferred-syntax-allowed-as-literal", jspPropertyGroup.getDeferredSyntaxAllowedAsLiteral());
                if (jspPropertyGroup.getTrimDirectiveWhitespaces() != null)
                    out.tag("trim-directive-whitespaces", jspPropertyGroup.getTrimDirectiveWhitespaces());
                if (jspPropertyGroup.getDefaultContentType() != null)
                    out.tag("default-content-type", jspPropertyGroup.getDefaultContentType());
                if (jspPropertyGroup.getBuffer() != null)
                    out.tag("buffer", jspPropertyGroup.getBuffer());
                if (jspPropertyGroup.getErrorOnUndeclaredNamespace() != null)
                    out.tag("error-on-undeclared-namespace", jspPropertyGroup.getErrorOnUndeclaredNamespace());
                strings = jspPropertyGroup.getIncludePreludes();
                if (strings != null && !strings.isEmpty()) {
                    for (String prelude : strings) out.tag("include-prelude", prelude);
                }
                strings = jspPropertyGroup.getIncludeCodas();
                if (strings != null && !strings.isEmpty()) {
                    for (String coda : strings) out.tag("include-coda", coda);
                }
                out.closeTag();
            }
        }
        out.closeTag();
    }
    //lifecycle: post-construct, pre-destroy
    LifeCycleCallbackCollection lifecycles = ((LifeCycleCallbackCollection) _webApp.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION));
    if (lifecycles != null) {
        Collection<LifeCycleCallback> tmp = lifecycles.getPostConstructCallbacks();
        for (LifeCycleCallback c : tmp) {
            out.openTag("post-construct");
            out.tag("lifecycle-callback-class", c.getTargetClassName());
            out.tag("lifecycle-callback-method", c.getMethodName());
            out.closeTag();
        }
        tmp = lifecycles.getPreDestroyCallbacks();
        for (LifeCycleCallback c : tmp) {
            out.openTag("pre-destroy");
            out.tag("lifecycle-callback-class", c.getTargetClassName());
            out.tag("lifecycle-callback-method", c.getMethodName());
            out.closeTag();
        }
    }
    out.literal(_extraXML);
    out.closeTag();
}
Also used : ServletHandler(org.eclipse.jetty.servlet.ServletHandler) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ErrorPageErrorHandler(org.eclipse.jetty.servlet.ErrorPageErrorHandler) JspConfig(org.eclipse.jetty.servlet.ServletContextHandler.JspConfig) HashMap(java.util.HashMap) SessionTrackingMode(javax.servlet.SessionTrackingMode) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) FilterMapping(org.eclipse.jetty.servlet.FilterMapping) JspPropertyGroupDescriptor(javax.servlet.descriptor.JspPropertyGroupDescriptor) MetaData(org.eclipse.jetty.webapp.MetaData) ConstraintAware(org.eclipse.jetty.security.ConstraintAware) SessionCookieConfig(javax.servlet.SessionCookieConfig) EventListener(java.util.EventListener) ServletMapping(org.eclipse.jetty.servlet.ServletMapping) SecurityHandler(org.eclipse.jetty.security.SecurityHandler) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) LifeCycleCallbackCollection(org.eclipse.jetty.plus.annotation.LifeCycleCallbackCollection) MimeTypes(org.eclipse.jetty.http.MimeTypes) Constraint(org.eclipse.jetty.util.security.Constraint) XmlAppendable(org.eclipse.jetty.xml.XmlAppendable) TaglibDescriptor(javax.servlet.descriptor.TaglibDescriptor) LifeCycleCallback(org.eclipse.jetty.plus.annotation.LifeCycleCallback) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

SessionTrackingMode (javax.servlet.SessionTrackingMode)7 HashSet (java.util.HashSet)3 ThreadSetupHandler (io.undertow.servlet.api.ThreadSetupHandler)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Constraint (org.eclipse.jetty.util.security.Constraint)2 HandlerWrapper (io.undertow.server.HandlerWrapper)1 HttpServerExchange (io.undertow.server.HttpServerExchange)1 PathParameterSessionConfig (io.undertow.server.session.PathParameterSessionConfig)1 SecureRandomSessionIdGenerator (io.undertow.server.session.SecureRandomSessionIdGenerator)1 SessionConfig (io.undertow.server.session.SessionConfig)1 SslSessionConfig (io.undertow.server.session.SslSessionConfig)1 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)1 ServletSessionConfig (io.undertow.servlet.api.ServletSessionConfig)1 SessionConfigWrapper (io.undertow.servlet.api.SessionConfigWrapper)1 WebSocketDeploymentInfo (io.undertow.websockets.jsr.WebSocketDeploymentInfo)1 FileNotFoundException (java.io.FileNotFoundException)1 MalformedURLException (java.net.MalformedURLException)1 PrivilegedAction (java.security.PrivilegedAction)1