Search in sources :

Example 1 with ThreadSetupHandler

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

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

the class Bootstrap method handleDeployment.

@Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
    WebSocketDeploymentInfo info = (WebSocketDeploymentInfo) deploymentInfo.getServletContextAttributes().get(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
    if (info == null) {
        return;
    }
    XnioWorker worker = info.getWorker();
    if (worker == null) {
        ServerWebSocketContainer defaultContainer = UndertowContainerProvider.getDefaultContainer();
        if (defaultContainer == null) {
            throw JsrWebSocketLogger.ROOT_LOGGER.xnioWorkerWasNullAndNoDefault();
        }
        JsrWebSocketLogger.ROOT_LOGGER.xnioWorkerWasNull();
        worker = defaultContainer.getXnioWorker();
    }
    ByteBufferPool buffers = info.getBuffers();
    if (buffers == null) {
        ServerWebSocketContainer defaultContainer = UndertowContainerProvider.getDefaultContainer();
        if (defaultContainer == null) {
            throw JsrWebSocketLogger.ROOT_LOGGER.bufferPoolWasNullAndNoDefault();
        }
        JsrWebSocketLogger.ROOT_LOGGER.bufferPoolWasNull();
        buffers = defaultContainer.getBufferPool();
    }
    final List<ThreadSetupHandler> setup = new ArrayList<>();
    setup.add(new ContextClassLoaderSetupAction(deploymentInfo.getClassLoader()));
    setup.addAll(deploymentInfo.getThreadSetupActions());
    InetSocketAddress bind = null;
    if (info.getClientBindAddress() != null) {
        bind = new InetSocketAddress(info.getClientBindAddress(), 0);
    }
    List<Extension> extensions = new ArrayList<>();
    for (ExtensionHandshake e : info.getExtensions()) {
        extensions.add(new ExtensionImpl(e.getName(), Collections.emptyList()));
    }
    ServerWebSocketContainer container = new ServerWebSocketContainer(deploymentInfo.getClassIntrospecter(), servletContext.getClassLoader(), worker, buffers, setup, info.isDispatchToWorkerThread(), bind, info.getReconnectHandler(), extensions);
    try {
        for (Class<?> annotation : info.getAnnotatedEndpoints()) {
            container.addEndpoint(annotation);
        }
        for (ServerEndpointConfig programatic : info.getProgramaticEndpoints()) {
            container.addEndpoint(programatic);
        }
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
    servletContext.setAttribute(ServerContainer.class.getName(), container);
    info.containerReady(container);
    SecurityActions.addContainer(deploymentInfo.getClassLoader(), container);
    deploymentInfo.addListener(Servlets.listener(WebSocketListener.class));
}
Also used : ByteBufferPool(io.undertow.connector.ByteBufferPool) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) XnioWorker(org.xnio.XnioWorker) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) ServletExtension(io.undertow.servlet.ServletExtension) Extension(javax.websocket.Extension) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) ContextClassLoaderSetupAction(io.undertow.servlet.core.ContextClassLoaderSetupAction) ExtensionHandshake(io.undertow.websockets.extensions.ExtensionHandshake) DeploymentException(javax.websocket.DeploymentException) ServerContainer(javax.websocket.server.ServerContainer)

Example 3 with ThreadSetupHandler

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

the class DeploymentManagerImpl method deploy.

@Override
public void deploy() {
    final DeploymentInfo deploymentInfo = originalDeployment.clone();
    if (deploymentInfo.getServletStackTraces() == ServletStackTraces.ALL) {
        UndertowServletLogger.REQUEST_LOGGER.servletStackTracesAll(deploymentInfo.getDeploymentName());
    }
    deploymentInfo.validate();
    final DeploymentImpl deployment = new DeploymentImpl(this, deploymentInfo, servletContainer);
    this.deployment = deployment;
    final ServletContextImpl servletContext = new ServletContextImpl(servletContainer, deployment);
    deployment.setServletContext(servletContext);
    handleExtensions(deploymentInfo, servletContext);
    final List<ThreadSetupHandler> setup = new ArrayList<>();
    setup.add(ServletRequestContextThreadSetupAction.INSTANCE);
    setup.add(new ContextClassLoaderSetupAction(deploymentInfo.getClassLoader()));
    setup.addAll(deploymentInfo.getThreadSetupActions());
    deployment.setThreadSetupActions(setup);
    deployment.getServletPaths().setWelcomePages(deploymentInfo.getWelcomePages());
    if (deploymentInfo.getDefaultEncoding() != null) {
        deployment.setDefaultCharset(Charset.forName(deploymentInfo.getDefaultEncoding()));
    }
    handleDeploymentSessionConfig(deploymentInfo, servletContext);
    deployment.setSessionManager(deploymentInfo.getSessionManagerFactory().createSessionManager(deployment));
    deployment.getSessionManager().setDefaultSessionTimeout(deploymentInfo.getDefaultSessionTimeout());
    try {
        deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Object>() {

            @Override
            public Void call(HttpServerExchange exchange, Object ignore) throws Exception {
                final ApplicationListeners listeners = createListeners();
                listeners.start();
                deployment.setApplicationListeners(listeners);
                //now create the servlets and filters that we know about. We can still get more later
                createServletsAndFilters(deployment, deploymentInfo);
                //first initialize the temp dir
                initializeTempDir(servletContext, deploymentInfo);
                //then run the SCI's
                for (final ServletContainerInitializerInfo sci : deploymentInfo.getServletContainerInitializers()) {
                    final InstanceHandle<? extends ServletContainerInitializer> instance = sci.getInstanceFactory().createInstance();
                    try {
                        instance.getInstance().onStartup(sci.getHandlesTypes(), servletContext);
                    } finally {
                        instance.release();
                    }
                }
                deployment.getSessionManager().registerSessionListener(new SessionListenerBridge(deployment, listeners, servletContext));
                for (SessionListener listener : deploymentInfo.getSessionListeners()) {
                    deployment.getSessionManager().registerSessionListener(listener);
                }
                initializeErrorPages(deployment, deploymentInfo);
                initializeMimeMappings(deployment, deploymentInfo);
                listeners.contextInitialized();
                //run
                HttpHandler wrappedHandlers = ServletDispatchingHandler.INSTANCE;
                wrappedHandlers = wrapHandlers(wrappedHandlers, deploymentInfo.getInnerHandlerChainWrappers());
                if (!deploymentInfo.isSecurityDisabled()) {
                    HttpHandler securityHandler = setupSecurityHandlers(wrappedHandlers);
                    wrappedHandlers = new PredicateHandler(DispatcherTypePredicate.REQUEST, securityHandler, wrappedHandlers);
                }
                HttpHandler outerHandlers = wrapHandlers(wrappedHandlers, deploymentInfo.getOuterHandlerChainWrappers());
                wrappedHandlers = new PredicateHandler(DispatcherTypePredicate.REQUEST, outerHandlers, wrappedHandlers);
                wrappedHandlers = handleDevelopmentModePersistentSessions(wrappedHandlers, deploymentInfo, deployment.getSessionManager(), servletContext);
                MetricsCollector metrics = deploymentInfo.getMetricsCollector();
                if (metrics != null) {
                    wrappedHandlers = new MetricsChainHandler(wrappedHandlers, metrics, deployment);
                }
                if (deploymentInfo.getCrawlerSessionManagerConfig() != null) {
                    wrappedHandlers = new CrawlerSessionManagerHandler(deploymentInfo.getCrawlerSessionManagerConfig(), wrappedHandlers);
                }
                final ServletInitialHandler servletInitialHandler = SecurityActions.createServletInitialHandler(deployment.getServletPaths(), wrappedHandlers, deployment, servletContext);
                HttpHandler initialHandler = wrapHandlers(servletInitialHandler, deployment.getDeploymentInfo().getInitialHandlerChainWrappers());
                initialHandler = new HttpContinueReadHandler(initialHandler);
                if (deploymentInfo.getUrlEncoding() != null) {
                    initialHandler = Handlers.urlDecodingHandler(deploymentInfo.getUrlEncoding(), initialHandler);
                }
                deployment.setInitialHandler(initialHandler);
                deployment.setServletHandler(servletInitialHandler);
                //make sure we have a fresh set of servlet paths
                deployment.getServletPaths().invalidate();
                servletContext.initDone();
                return null;
            }
        }).call(null, null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    //any problems with the paths won't get detected until the data is initialize
    //so we force initialization here
    deployment.getServletPaths().initData();
    state = State.DEPLOYED;
}
Also used : MetricsCollector(io.undertow.servlet.api.MetricsCollector) HttpHandler(io.undertow.server.HttpHandler) ServletInitialHandler(io.undertow.servlet.handlers.ServletInitialHandler) ServletContainerInitializerInfo(io.undertow.servlet.api.ServletContainerInitializerInfo) ServletContextImpl(io.undertow.servlet.spec.ServletContextImpl) ArrayList(java.util.ArrayList) PredicateHandler(io.undertow.server.handlers.PredicateHandler) ServletException(javax.servlet.ServletException) HttpServerExchange(io.undertow.server.HttpServerExchange) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) HttpContinueReadHandler(io.undertow.server.handlers.HttpContinueReadHandler) CrawlerSessionManagerHandler(io.undertow.servlet.handlers.CrawlerSessionManagerHandler) SessionListener(io.undertow.server.session.SessionListener) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo)

Example 4 with ThreadSetupHandler

use of io.undertow.servlet.api.ThreadSetupHandler in project wildfly by wildfly.

the class DistributableSessionManagerFactory method createSessionManager.

@Override
public io.undertow.server.session.SessionManager createSessionManager(final Deployment deployment) {
    DeploymentInfo info = deployment.getDeploymentInfo();
    boolean statisticsEnabled = info.getMetricsCollector() != null;
    RecordableInactiveSessionStatistics inactiveSessionStatistics = statisticsEnabled ? new RecordableInactiveSessionStatistics() : null;
    IdentifierFactory<String> factory = new IdentifierFactoryAdapter(info.getSessionIdGenerator());
    LocalContextFactory<LocalSessionContext> localContextFactory = new LocalSessionContextFactory();
    SessionListeners listeners = new SessionListeners();
    SessionExpirationListener expirationListener = new UndertowSessionExpirationListener(deployment, listeners);
    SessionManagerConfiguration<LocalSessionContext> configuration = new SessionManagerConfiguration<LocalSessionContext>() {

        @Override
        public ServletContext getServletContext() {
            return deployment.getServletContext();
        }

        @Override
        public IdentifierFactory<String> getIdentifierFactory() {
            return factory;
        }

        @Override
        public SessionExpirationListener getExpirationListener() {
            return expirationListener;
        }

        @Override
        public LocalContextFactory<LocalSessionContext> getLocalContextFactory() {
            return localContextFactory;
        }

        @Override
        public Recordable<ImmutableSession> getInactiveSessionRecorder() {
            return inactiveSessionStatistics;
        }
    };
    SessionManager<LocalSessionContext, Batch> manager = this.factory.createSessionManager(configuration);
    Batcher<Batch> batcher = manager.getBatcher();
    info.addThreadSetupAction(new ThreadSetupHandler() {

        @Override
        public <T, C> Action<T, C> create(Action<T, C> action) {
            return new Action<T, C>() {

                @Override
                public T call(HttpServerExchange exchange, C context) throws Exception {
                    Batch batch = batcher.suspendBatch();
                    try (BatchContext ctx = batcher.resumeBatch(batch)) {
                        return action.call(exchange, context);
                    }
                }
            };
        }
    });
    RecordableSessionManagerStatistics statistics = (inactiveSessionStatistics != null) ? new DistributableSessionManagerStatistics(manager, inactiveSessionStatistics) : null;
    return new DistributableSessionManager(info.getDeploymentName(), manager, listeners, statistics);
}
Also used : ImmutableSession(org.wildfly.clustering.web.session.ImmutableSession) SessionManagerConfiguration(org.wildfly.clustering.web.session.SessionManagerConfiguration) HttpServerExchange(io.undertow.server.HttpServerExchange) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) SessionExpirationListener(org.wildfly.clustering.web.session.SessionExpirationListener) SessionListeners(io.undertow.server.session.SessionListeners) Batch(org.wildfly.clustering.ee.Batch) IdentifierFactoryAdapter(org.wildfly.clustering.web.undertow.IdentifierFactoryAdapter) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) BatchContext(org.wildfly.clustering.ee.BatchContext)

Aggregations

ThreadSetupHandler (io.undertow.servlet.api.ThreadSetupHandler)4 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)3 HttpServerExchange (io.undertow.server.HttpServerExchange)2 ArrayList (java.util.ArrayList)2 ByteBufferPool (io.undertow.connector.ByteBufferPool)1 HandlerWrapper (io.undertow.server.HandlerWrapper)1 HttpHandler (io.undertow.server.HttpHandler)1 HttpContinueReadHandler (io.undertow.server.handlers.HttpContinueReadHandler)1 PredicateHandler (io.undertow.server.handlers.PredicateHandler)1 SecureRandomSessionIdGenerator (io.undertow.server.session.SecureRandomSessionIdGenerator)1 SessionListener (io.undertow.server.session.SessionListener)1 SessionListeners (io.undertow.server.session.SessionListeners)1 ServletExtension (io.undertow.servlet.ServletExtension)1 MetricsCollector (io.undertow.servlet.api.MetricsCollector)1 ServletContainerInitializerInfo (io.undertow.servlet.api.ServletContainerInitializerInfo)1 ServletSessionConfig (io.undertow.servlet.api.ServletSessionConfig)1 ContextClassLoaderSetupAction (io.undertow.servlet.core.ContextClassLoaderSetupAction)1 CrawlerSessionManagerHandler (io.undertow.servlet.handlers.CrawlerSessionManagerHandler)1 ServletInitialHandler (io.undertow.servlet.handlers.ServletInitialHandler)1 ServletContextImpl (io.undertow.servlet.spec.ServletContextImpl)1