Search in sources :

Example 11 with SessionCookieConfig

use of javax.servlet.SessionCookieConfig in project Payara by payara.

the class TomcatDeploymentConfig method configureStandardContext.

/**
 * Configure the <code>WebModule</code> instance by creating
 * <code>StandardWrapper</code> using the information contained
 * in the deployment descriptor (Welcome Files, JSP, Servlets etc.)
 */
protected static void configureStandardContext(WebModule webModule, WebBundleDescriptorImpl wmd) {
    for (WebComponentDescriptor webComponentDesc : wmd.getWebComponentDescriptors()) {
        addWebComponentDescriptor(webModule, webComponentDesc);
    }
    SessionConfig sessionConfig = wmd.getSessionConfig();
    // <session-config><session-timeout>
    webModule.setSessionTimeout(sessionConfig.getSessionTimeout());
    // <session-config><cookie-config>
    CookieConfig cookieConfig = sessionConfig.getCookieConfig();
    if (cookieConfig != null) {
        SessionCookieConfig sessionCookieConfig = webModule.getSessionCookieConfig();
        /* 
             * Unlike a cookie's domain, path, and comment, its name
             * will be empty (instead of null) if left unspecified
             * inside <session-config><cookie-config>
             */
        if (cookieConfig.getName() != null && !cookieConfig.getName().isEmpty()) {
            sessionCookieConfig.setName(cookieConfig.getName());
        }
        sessionCookieConfig.setDomain(cookieConfig.getDomain());
        sessionCookieConfig.setPath(cookieConfig.getPath());
        sessionCookieConfig.setComment(cookieConfig.getComment());
        sessionCookieConfig.setHttpOnly(cookieConfig.isHttpOnly());
        sessionCookieConfig.setSecure(cookieConfig.isSecure());
        sessionCookieConfig.setMaxAge(cookieConfig.getMaxAge());
    }
    // <session-config><tracking-mode>
    if (!sessionConfig.getTrackingModes().isEmpty()) {
        webModule.setSessionTrackingModes(sessionConfig.getTrackingModes());
    }
    // glassfish-web.xml override the web.xml
    com.sun.enterprise.web.session.SessionCookieConfig gfSessionCookieConfig = webModule.getSessionCookieConfigFromSunWebXml();
    if (gfSessionCookieConfig != null) {
        WebSessionCookieConfig sessionCookieConfig = (WebSessionCookieConfig) webModule.getSessionCookieConfig();
        if (gfSessionCookieConfig.getName() != null && !gfSessionCookieConfig.getName().isEmpty()) {
            sessionCookieConfig.setName(gfSessionCookieConfig.getName());
        }
        if (gfSessionCookieConfig.getPath() != null) {
            sessionCookieConfig.setPath(gfSessionCookieConfig.getPath());
        }
        if (gfSessionCookieConfig.getMaxAge() != null) {
            sessionCookieConfig.setMaxAge(gfSessionCookieConfig.getMaxAge());
        }
        if (gfSessionCookieConfig.getDomain() != null) {
            sessionCookieConfig.setDomain(gfSessionCookieConfig.getDomain());
        }
        if (gfSessionCookieConfig.getComment() != null) {
            sessionCookieConfig.setComment(gfSessionCookieConfig.getComment());
        }
        if (gfSessionCookieConfig.getSecure() != null) {
            sessionCookieConfig.setSecure(gfSessionCookieConfig.getSecure());
        }
        if (gfSessionCookieConfig.getHttpOnly() != null) {
            sessionCookieConfig.setHttpOnly(gfSessionCookieConfig.getHttpOnly());
        }
    }
    Enumeration enumeration = wmd.getWelcomeFiles();
    while (enumeration.hasMoreElements()) {
        webModule.addWelcomeFile((String) enumeration.nextElement());
    }
    LocaleEncodingMappingListDescriptor lemds = wmd.getLocaleEncodingMappingListDescriptor();
    if (lemds != null) {
        for (LocaleEncodingMappingDescriptor lemd : lemds.getLocaleEncodingMappingSet()) {
            webModule.addLocaleEncodingMappingParameter(lemd.getLocale(), lemd.getEncoding());
        }
    }
    webModule.setOrderedLibs(wmd.getOrderedLibs());
    String[] majorMinorVersions = wmd.getSpecVersion().split("\\.");
    if (majorMinorVersions.length != 2) {
        throw new IllegalArgumentException("Illegal Servlet spec version");
    }
    webModule.setEffectiveMajorVersion(Integer.parseInt(majorMinorVersions[0]));
    webModule.setEffectiveMinorVersion(Integer.parseInt(majorMinorVersions[1]));
}
Also used : Enumeration(java.util.Enumeration) WebSessionCookieConfig(com.sun.enterprise.web.session.WebSessionCookieConfig) SessionCookieConfig(javax.servlet.SessionCookieConfig) WebSessionCookieConfig(com.sun.enterprise.web.session.WebSessionCookieConfig) WebSessionCookieConfig(com.sun.enterprise.web.session.WebSessionCookieConfig) SessionCookieConfig(javax.servlet.SessionCookieConfig)

Example 12 with SessionCookieConfig

use of javax.servlet.SessionCookieConfig in project meecrowave by apache.

the class Meecrowave method deployWebapp.

public Meecrowave deployWebapp(final DeploymentMeta meta) {
    if (contexts.containsKey(meta.context)) {
        throw new IllegalArgumentException("Already deployed: '" + meta.context + "'");
    }
    // always nice to see the deployment with something else than internals
    final String base = tomcat.getService().findConnectors().length > 0 ? (configuration.getActiveProtocol() + "://" + tomcat.getHost().getName() + ':' + configuration.getActivePort()) : "";
    new LogFacade(Meecrowave.class.getName()).info("--------------- " + base + meta.context);
    final OWBJarScanner scanner = new OWBJarScanner();
    final StandardContext ctx = new StandardContext() {

        @Override
        public void setApplicationEventListeners(final Object[] listeners) {
            if (listeners == null) {
                super.setApplicationEventListeners(null);
                return;
            }
            // if we don't -> no @RequestScoped in request listeners :(
            for (int i = 1; i < listeners.length; i++) {
                if (OWBAutoSetup.EagerBootListener.class.isInstance(listeners[i])) {
                    final Object first = listeners[0];
                    listeners[0] = listeners[i];
                    listeners[i] = first;
                    break;
                }
            }
            // and finally let it go after our re-ordering
            super.setApplicationEventListeners(listeners);
        }
    };
    ctx.setPath(meta.context);
    ctx.setName(meta.context);
    ctx.setJarScanner(scanner);
    ctx.setInstanceManager(new CDIInstanceManager());
    ofNullable(meta.docBase).ifPresent(d -> {
        try {
            ctx.setDocBase(meta.docBase.getCanonicalPath());
        } catch (final IOException e) {
            ctx.setDocBase(meta.docBase.getAbsolutePath());
        }
    });
    ofNullable(configuration.getTomcatFilter()).ifPresent(filter -> {
        try {
            scanner.setJarScanFilter(JarScanFilter.class.cast(Thread.currentThread().getContextClassLoader().loadClass(filter).newInstance()));
        } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    });
    final AtomicReference<Runnable> releaseSCI = new AtomicReference<>();
    final ServletContainerInitializer meecrowaveInitializer = (c, ctx1) -> {
        ctx1.setAttribute("meecrowave.configuration", getConfiguration());
        ctx1.setAttribute("meecrowave.instance", Meecrowave.this);
        new OWBAutoSetup().onStartup(c, ctx1);
        if (Cxfs.IS_PRESENT) {
            new CxfCdiAutoSetup().onStartup(c, ctx1);
        }
        new TomcatAutoInitializer().onStartup(c, ctx1);
        if (configuration.isInjectServletContainerInitializer()) {
            final Field f;
            try {
                // now cdi is on, we can inject cdi beans in ServletContainerInitializer
                f = StandardContext.class.getDeclaredField("initializers");
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
            } catch (final Exception e) {
                throw new IllegalStateException("Bad tomcat version", e);
            }
            final List<AutoCloseable> cc;
            try {
                cc = ((Map<ServletContainerInitializer, Set<Class<?>>>) f.get(ctx)).keySet().stream().filter(i -> !i.getClass().getName().startsWith(Meecrowave.class.getName())).map(i -> {
                    try {
                        return this.inject(i);
                    } catch (final IllegalArgumentException iae) {
                        return null;
                    }
                }).filter(Objects::nonNull).collect(toList());
            } catch (final IllegalAccessException e) {
                throw new IllegalStateException("Can't read initializers", e);
            }
            releaseSCI.set(() -> cc.forEach(closeable -> {
                try {
                    closeable.close();
                } catch (final Exception e) {
                    throw new IllegalStateException(e);
                }
            }));
        }
    };
    ctx.addLifecycleListener(new MeecrowaveContextConfig(configuration, meta.docBase != null, meecrowaveInitializer, meta.redeployCallback));
    ctx.addLifecycleListener(event -> {
        switch(event.getType()) {
            case Lifecycle.BEFORE_START_EVENT:
                if (configuration.getWebSessionCookieConfig() != null) {
                    final Properties p = new Properties();
                    try {
                        p.load(new StringReader(configuration.getWebSessionCookieConfig()));
                    } catch (final IOException e) {
                        throw new IllegalArgumentException(e);
                    }
                    if (p.containsKey("domain")) {
                        ctx.setSessionCookieDomain(p.getProperty("domain"));
                    }
                    if (p.containsKey("path")) {
                        ctx.setSessionCookiePath(p.getProperty("path"));
                    }
                    if (p.containsKey("name")) {
                        ctx.setSessionCookieName(p.getProperty("name"));
                    }
                    if (p.containsKey("use-trailing-slash")) {
                        ctx.setSessionCookiePathUsesTrailingSlash(Boolean.parseBoolean(p.getProperty("use-trailing-slash")));
                    }
                    if (p.containsKey("http-only")) {
                        ctx.setUseHttpOnly(Boolean.parseBoolean(p.getProperty("http-only")));
                    }
                    if (p.containsKey("secured")) {
                        final SessionCookieConfig sessionCookieConfig = ctx.getServletContext().getSessionCookieConfig();
                        sessionCookieConfig.setSecure(Boolean.parseBoolean(p.getProperty("secured")));
                    }
                }
                break;
            case Lifecycle.AFTER_START_EVENT:
                ctx.getResources().setCachingAllowed(configuration.isWebResourceCached());
                break;
            case Lifecycle.BEFORE_INIT_EVENT:
                if (configuration.getLoginConfig() != null) {
                    ctx.setLoginConfig(configuration.getLoginConfig().build());
                }
                for (final SecurityConstaintBuilder sc : configuration.getSecurityConstraints()) {
                    ctx.addConstraint(sc.build());
                }
                if (configuration.getWebXml() != null) {
                    ctx.getServletContext().setAttribute(Globals.ALT_DD_ATTR, configuration.getWebXml());
                }
                break;
            default:
        }
    });
    // after having configured the security!!!
    ctx.addLifecycleListener(new Tomcat.FixContextListener());
    ctx.addServletContainerInitializer(meecrowaveInitializer, emptySet());
    if (configuration.isUseTomcatDefaults()) {
        ctx.setSessionTimeout(configuration.getWebSessionTimeout() != null ? configuration.getWebSessionTimeout() : 30);
        ctx.addWelcomeFile("index.html");
        ctx.addWelcomeFile("index.htm");
        Tomcat.addDefaultMimeTypeMappings(ctx);
    } else if (configuration.getWebSessionTimeout() != null) {
        ctx.setSessionTimeout(configuration.getWebSessionTimeout());
    }
    ofNullable(meta.consumer).ifPresent(c -> c.accept(ctx));
    if (configuration.isQuickSession() && ctx.getManager() == null) {
        final StandardManager manager = new StandardManager();
        manager.setSessionIdGenerator(new StandardSessionIdGenerator() {

            @Override
            protected void getRandomBytes(final byte[] bytes) {
                ThreadLocalRandom.current().nextBytes(bytes);
            }

            @Override
            public String toString() {
                return "MeecrowaveSessionIdGenerator@" + System.identityHashCode(this);
            }
        });
        ctx.setManager(manager);
    }
    if (configuration.isAntiResourceLocking() && StandardContext.class.isInstance(ctx)) {
        StandardContext.class.cast(ctx).setAntiResourceLocking(true);
    }
    configuration.getInitializers().forEach(i -> ctx.addServletContainerInitializer(i, emptySet()));
    configuration.getGlobalContextConfigurers().forEach(it -> it.accept(ctx));
    final Host host = tomcat.getHost();
    host.addChild(ctx);
    final ClassLoader classLoader = ctx.getLoader().getClassLoader();
    if (host.getState().isAvailable()) {
        fire(new StartListening(findFirstConnector(), host, ctx), classLoader);
    }
    contexts.put(meta.context, () -> {
        if (host.getState().isAvailable()) {
            fire(new StopListening(findFirstConnector(), host, ctx), classLoader);
        }
        ofNullable(releaseSCI.get()).ifPresent(Runnable::run);
        tomcat.getHost().removeChild(ctx);
    });
    return this;
}
Also used : MeecrowaveContextConfig(org.apache.meecrowave.tomcat.MeecrowaveContextConfig) ProvidedLoader(org.apache.meecrowave.tomcat.ProvidedLoader) SessionCookieConfig(javax.servlet.SessionCookieConfig) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection) SecretKeySpec(javax.crypto.spec.SecretKeySpec) ServerSocket(java.net.ServerSocket) URLClassLoader(java.net.URLClassLoader) Host(org.apache.catalina.Host) StopListening(org.apache.meecrowave.api.StopListening) Map(java.util.Map) SAXParser(javax.xml.parsers.SAXParser) Path(java.nio.file.Path) Log4j2Log(org.apache.meecrowave.logging.tomcat.Log4j2Log) LifecycleException(org.apache.catalina.LifecycleException) Set(java.util.Set) CDI(javax.enterprise.inject.spi.CDI) CDIInstanceManager(org.apache.meecrowave.tomcat.CDIInstanceManager) StandardCharsets(java.nio.charset.StandardCharsets) WebBeansContext(org.apache.webbeans.config.WebBeansContext) ResourceFinder(org.apache.xbean.finder.ResourceFinder) Stream(java.util.stream.Stream) ConfigurableBus(org.apache.meecrowave.cxf.ConfigurableBus) JarScanFilter(org.apache.tomcat.JarScanFilter) Log4j2s(org.apache.meecrowave.logging.log4j2.Log4j2s) TomcatAutoInitializer(org.apache.meecrowave.tomcat.TomcatAutoInitializer) Log4j2Logger(org.apache.meecrowave.logging.jul.Log4j2Logger) Connector(org.apache.catalina.connector.Connector) StandardHost(org.apache.catalina.core.StandardHost) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) CreationalContext(javax.enterprise.context.spi.CreationalContext) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) StreamSupport(java.util.stream.StreamSupport) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig) ManagementFactory(java.lang.management.ManagementFactory) Properties(java.util.Properties) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) Files(java.nio.file.Files) Cxfs(org.apache.meecrowave.cxf.Cxfs) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ValueTransformer(org.apache.meecrowave.service.ValueTransformer) Field(java.lang.reflect.Field) File(java.io.File) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) DefaultHandler(org.xml.sax.helpers.DefaultHandler) StringReader(java.io.StringReader) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) Pipeline(org.apache.catalina.Pipeline) BeanManager(javax.enterprise.inject.spi.BeanManager) URL(java.net.URL) Lifecycle(org.apache.catalina.Lifecycle) Priotities(org.apache.meecrowave.service.Priotities) Catalina(org.apache.catalina.startup.Catalina) OWBJarScanner(org.apache.meecrowave.tomcat.OWBJarScanner) Http2Protocol(org.apache.coyote.http2.Http2Protocol) IO(org.apache.meecrowave.io.IO) LifecycleState(org.apache.catalina.LifecycleState) Collectors.toSet(java.util.stream.Collectors.toSet) Server(org.apache.catalina.Server) StartListening(org.apache.meecrowave.api.StartListening) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) StandardSessionIdGenerator(org.apache.catalina.util.StandardSessionIdGenerator) ServiceLoader(java.util.ServiceLoader) Substitutor(org.apache.meecrowave.lang.Substitutor) Objects(java.util.Objects) Base64(java.util.Base64) List(java.util.List) Realm(org.apache.catalina.Realm) SAXException(org.xml.sax.SAXException) Writer(java.io.Writer) StandardContext(org.apache.catalina.core.StandardContext) OWBAutoSetup(org.apache.meecrowave.openwebbeans.OWBAutoSetup) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) SAXParserFactory(javax.xml.parsers.SAXParserFactory) Valve(org.apache.catalina.Valve) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Cipher(javax.crypto.Cipher) Option(org.apache.xbean.recipe.Option) BiPredicate(java.util.function.BiPredicate) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Log4j2Shutdown(org.apache.meecrowave.logging.log4j2.Log4j2Shutdown) Attributes(org.xml.sax.Attributes) Comparator.comparing(java.util.Comparator.comparing) ROOT(java.util.Locale.ROOT) InjectionTarget(javax.enterprise.inject.spi.InjectionTarget) CxfCdiAutoSetup(org.apache.meecrowave.cxf.CxfCdiAutoSetup) OutputStream(java.io.OutputStream) Collections.emptySet(java.util.Collections.emptySet) MalformedURLException(java.net.MalformedURLException) Log4j2LoggerFactory(org.apache.meecrowave.logging.openwebbeans.Log4j2LoggerFactory) Optional.ofNullable(java.util.Optional.ofNullable) LoggingAccessLogPattern(org.apache.meecrowave.tomcat.LoggingAccessLogPattern) FileWriter(java.io.FileWriter) Globals(org.apache.catalina.Globals) Configuration(org.apache.meecrowave.configuration.Configuration) StandardManager(org.apache.catalina.session.StandardManager) FileInputStream(java.io.FileInputStream) Context(org.apache.catalina.Context) Registry(org.apache.tomcat.util.modeler.Registry) Consumer(java.util.function.Consumer) Tomcat(org.apache.catalina.startup.Tomcat) Collectors.toList(java.util.stream.Collectors.toList) InputStream(java.io.InputStream) Tomcat(org.apache.catalina.startup.Tomcat) Set(java.util.Set) Collectors.toSet(java.util.stream.Collectors.toSet) Collections.emptySet(java.util.Collections.emptySet) CxfCdiAutoSetup(org.apache.meecrowave.cxf.CxfCdiAutoSetup) JarScanFilter(org.apache.tomcat.JarScanFilter) Properties(java.util.Properties) OWBJarScanner(org.apache.meecrowave.tomcat.OWBJarScanner) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Field(java.lang.reflect.Field) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) CDIInstanceManager(org.apache.meecrowave.tomcat.CDIInstanceManager) OWBAutoSetup(org.apache.meecrowave.openwebbeans.OWBAutoSetup) TomcatAutoInitializer(org.apache.meecrowave.tomcat.TomcatAutoInitializer) MeecrowaveContextConfig(org.apache.meecrowave.tomcat.MeecrowaveContextConfig) StringReader(java.io.StringReader) URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) SessionCookieConfig(javax.servlet.SessionCookieConfig) StartListening(org.apache.meecrowave.api.StartListening) StandardManager(org.apache.catalina.session.StandardManager) AtomicReference(java.util.concurrent.atomic.AtomicReference) Host(org.apache.catalina.Host) StandardHost(org.apache.catalina.core.StandardHost) StopListening(org.apache.meecrowave.api.StopListening) IOException(java.io.IOException) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) LifecycleException(org.apache.catalina.LifecycleException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) MalformedURLException(java.net.MalformedURLException) StandardSessionIdGenerator(org.apache.catalina.util.StandardSessionIdGenerator) StandardContext(org.apache.catalina.core.StandardContext)

Example 13 with SessionCookieConfig

use of javax.servlet.SessionCookieConfig in project alf.io by alfio-event.

the class Initializer method configureSessionCookie.

private void configureSessionCookie(ServletContext servletContext) {
    SessionCookieConfig config = servletContext.getSessionCookieConfig();
    config.setHttpOnly(true);
    Validate.notNull(environment, "environment cannot be null!");
    // set secure cookie only if current environment doesn't strictly need HTTP
    config.setSecure(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
    // https://issues.jboss.org/browse/WFLY-3448 ?
    config.setPath(servletContext.getContextPath() + "/");
}
Also used : SessionCookieConfig(javax.servlet.SessionCookieConfig)

Example 14 with SessionCookieConfig

use of javax.servlet.SessionCookieConfig 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)

Example 15 with SessionCookieConfig

use of javax.servlet.SessionCookieConfig in project spring-boot by spring-projects.

the class DefaultServletWebServerFactoryCustomizerTests method customizeSessionProperties.

@Test
public void customizeSessionProperties() throws Exception {
    Map<String, String> map = new HashMap<>();
    map.put("server.session.timeout", "123");
    map.put("server.session.tracking-modes", "cookie,url");
    map.put("server.session.cookie.name", "testname");
    map.put("server.session.cookie.domain", "testdomain");
    map.put("server.session.cookie.path", "/testpath");
    map.put("server.session.cookie.comment", "testcomment");
    map.put("server.session.cookie.http-only", "true");
    map.put("server.session.cookie.secure", "true");
    map.put("server.session.cookie.max-age", "60");
    bindProperties(map);
    ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
    ServletContext servletContext = mock(ServletContext.class);
    SessionCookieConfig sessionCookieConfig = mock(SessionCookieConfig.class);
    given(servletContext.getSessionCookieConfig()).willReturn(sessionCookieConfig);
    this.customizer.customize(factory);
    triggerInitializers(factory, servletContext);
    verify(factory).setSessionTimeout(123);
    verify(servletContext).setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL));
    verify(sessionCookieConfig).setName("testname");
    verify(sessionCookieConfig).setDomain("testdomain");
    verify(sessionCookieConfig).setPath("/testpath");
    verify(sessionCookieConfig).setComment("testcomment");
    verify(sessionCookieConfig).setHttpOnly(true);
    verify(sessionCookieConfig).setSecure(true);
    verify(sessionCookieConfig).setMaxAge(60);
}
Also used : ConfigurableServletWebServerFactory(org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory) HashMap(java.util.HashMap) ServletContext(javax.servlet.ServletContext) SessionCookieConfig(javax.servlet.SessionCookieConfig) Test(org.junit.Test)

Aggregations

SessionCookieConfig (javax.servlet.SessionCookieConfig)20 HashMap (java.util.HashMap)4 SessionHandler (org.eclipse.jetty.server.session.SessionHandler)4 ServletContext (javax.servlet.ServletContext)3 Field (java.lang.reflect.Field)2 Map (java.util.Map)2 JspPropertyGroupDescriptor (javax.servlet.descriptor.JspPropertyGroupDescriptor)2 TaglibDescriptor (javax.servlet.descriptor.TaglibDescriptor)2 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)1 WebSessionCookieConfig (com.sun.enterprise.web.session.WebSessionCookieConfig)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 FileWriter (java.io.FileWriter)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 StringReader (java.io.StringReader)1 Writer (java.io.Writer)1 ManagementFactory (java.lang.management.ManagementFactory)1