Search in sources :

Example 6 with SessionConfig

use of io.undertow.server.session.SessionConfig in project undertow by undertow-io.

the class AsyncWebSocketHttpServerExchange method getSession.

@Override
public Object getSession() {
    SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
    SessionConfig sessionCookieConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
    if (sm != null && sessionCookieConfig != null) {
        return sm.getSession(exchange, sessionCookieConfig);
    }
    return null;
}
Also used : SessionManager(io.undertow.server.session.SessionManager) SessionConfig(io.undertow.server.session.SessionConfig)

Example 7 with SessionConfig

use of io.undertow.server.session.SessionConfig in project undertow by undertow-io.

the class SessionServer method main.

public static void main(String[] args) {
    PathHandler pathHandler = new PathHandler();
    pathHandler.addPrefixPath("/", new HttpHandler() {

        public void handleRequest(HttpServerExchange exchange) throws Exception {
            StringBuilder sb = new StringBuilder();
            sb.append("<form action='addToSession' >");
            sb.append("<label>Attribute Name</label>");
            sb.append("<input name='attrName' />");
            sb.append("<label>Attribute Value</label>");
            sb.append("<input name='value' />");
            sb.append("<button>Save to Session</button>");
            // To retrive the SessionManager use the attachmentKey
            SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
            // same goes to SessionConfig
            SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
            sb.append("</form>");
            sb.append("<a href='/destroySession'>Destroy Session</a>");
            sb.append("<br/>");
            Session session = sm.getSession(exchange, sessionConfig);
            if (session == null)
                session = sm.createSession(exchange, sessionConfig);
            sb.append("<ul>");
            for (String string : session.getAttributeNames()) {
                sb.append("<li>" + string + " : " + session.getAttribute(string) + "</li>");
            }
            sb.append("</ul>");
            exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "text/html;");
            exchange.getResponseSender().send(sb.toString());
        }
    });
    pathHandler.addPrefixPath("/addToSession", new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
            SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
            Map<String, Deque<String>> reqParams = exchange.getQueryParameters();
            Session session = sm.getSession(exchange, sessionConfig);
            if (session == null)
                session = sm.createSession(exchange, sessionConfig);
            Deque<String> deque = reqParams.get("attrName");
            Deque<String> dequeVal = reqParams.get("value");
            session.setAttribute(deque.getLast(), dequeVal.getLast());
            exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
            exchange.getResponseHeaders().put(Headers.LOCATION, "/");
            exchange.getResponseSender().close();
        }
    });
    pathHandler.addPrefixPath("/destroySession", new HttpHandler() {

        public void handleRequest(HttpServerExchange exchange) throws Exception {
            SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
            SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
            Session session = sm.getSession(exchange, sessionConfig);
            if (session == null)
                session = sm.createSession(exchange, sessionConfig);
            session.invalidate(exchange);
            exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
            exchange.getResponseHeaders().put(Headers.LOCATION, "/");
            exchange.getResponseSender().close();
        }
    });
    SessionManager sessionManager = new InMemorySessionManager("SESSION_MANAGER");
    SessionCookieConfig sessionConfig = new SessionCookieConfig();
    /*
         * Use the sessionAttachmentHandler to add the sessionManager and
         * sessionCofing to the exchange of every request
         */
    SessionAttachmentHandler sessionAttachmentHandler = new SessionAttachmentHandler(sessionManager, sessionConfig);
    // set as next handler your root handler
    sessionAttachmentHandler.setNext(pathHandler);
    System.out.println("Open the url and fill the form to add attributes into the session");
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(sessionAttachmentHandler).build();
    server.start();
}
Also used : HttpHandler(io.undertow.server.HttpHandler) SessionManager(io.undertow.server.session.SessionManager) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) PathHandler(io.undertow.server.handlers.PathHandler) SessionConfig(io.undertow.server.session.SessionConfig) Deque(java.util.Deque) HttpServerExchange(io.undertow.server.HttpServerExchange) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler) SessionCookieConfig(io.undertow.server.session.SessionCookieConfig) Map(java.util.Map) Undertow(io.undertow.Undertow) Session(io.undertow.server.session.Session) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager)

Example 8 with SessionConfig

use of io.undertow.server.session.SessionConfig in project undertow by undertow-io.

the class ServletContextImpl method initDone.

public void initDone() {
    initialized = true;
    Set<SessionTrackingMode> trackingMethods = sessionTrackingModes;
    SessionConfig sessionConfig = sessionCookieConfig;
    if (trackingMethods != null && !trackingMethods.isEmpty()) {
        if (sessionTrackingModes.contains(SessionTrackingMode.SSL)) {
            sessionConfig = new SslSessionConfig(deployment.getSessionManager());
        } else {
            if (sessionTrackingModes.contains(SessionTrackingMode.COOKIE) && sessionTrackingModes.contains(SessionTrackingMode.URL)) {
                sessionCookieConfig.setFallback(new PathParameterSessionConfig(sessionCookieConfig.getName().toLowerCase(Locale.ENGLISH)));
            } else if (sessionTrackingModes.contains(SessionTrackingMode.URL)) {
                sessionConfig = new PathParameterSessionConfig(sessionCookieConfig.getName().toLowerCase(Locale.ENGLISH));
            }
        }
    }
    SessionConfigWrapper wrapper = deploymentInfo.getSessionConfigWrapper();
    if (wrapper != null) {
        sessionConfig = wrapper.wrap(sessionConfig, deployment);
    }
    this.sessionConfig = new ServletContextSessionConfig(sessionConfig);
    this.onWritePossibleTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, WriteListener>() {

        @Override
        public Void call(HttpServerExchange exchange, WriteListener context) throws Exception {
            context.onWritePossible();
            return null;
        }
    });
    this.runnableTask = new ThreadSetupHandler.Action<Void, Runnable>() {

        @Override
        public Void call(HttpServerExchange exchange, Runnable context) throws Exception {
            context.run();
            return null;
        }
    };
    this.onDataAvailableTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, ReadListener>() {

        @Override
        public Void call(HttpServerExchange exchange, ReadListener context) throws Exception {
            context.onDataAvailable();
            return null;
        }
    });
    this.onAllDataReadTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, ReadListener>() {

        @Override
        public Void call(HttpServerExchange exchange, ReadListener context) throws Exception {
            context.onAllDataRead();
            return null;
        }
    });
    this.invokeActionTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, ThreadSetupHandler.Action<Void, Object>>() {

        @Override
        public Void call(HttpServerExchange exchange, ThreadSetupHandler.Action<Void, Object> context) throws Exception {
            context.call(exchange, null);
            return null;
        }
    });
}
Also used : PrivilegedAction(java.security.PrivilegedAction) SessionTrackingMode(javax.servlet.SessionTrackingMode) PathParameterSessionConfig(io.undertow.server.session.PathParameterSessionConfig) SslSessionConfig(io.undertow.server.session.SslSessionConfig) PathParameterSessionConfig(io.undertow.server.session.PathParameterSessionConfig) SessionConfig(io.undertow.server.session.SessionConfig) ReadListener(javax.servlet.ReadListener) ServletException(javax.servlet.ServletException) FileNotFoundException(java.io.FileNotFoundException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) HttpServerExchange(io.undertow.server.HttpServerExchange) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) SslSessionConfig(io.undertow.server.session.SslSessionConfig) SessionConfigWrapper(io.undertow.servlet.api.SessionConfigWrapper) WriteListener(javax.servlet.WriteListener)

Example 9 with SessionConfig

use of io.undertow.server.session.SessionConfig in project undertow by undertow-io.

the class ServletContextImpl method getSession.

public HttpSessionImpl getSession(final ServletContextImpl originalServletContext, final HttpServerExchange exchange, boolean create) {
    SessionConfig c = originalServletContext.getSessionConfig();
    HttpSessionImpl httpSession = exchange.getAttachment(sessionAttachmentKey);
    if (httpSession != null && httpSession.isInvalid()) {
        exchange.removeAttachment(sessionAttachmentKey);
        httpSession = null;
    }
    if (httpSession == null) {
        final SessionManager sessionManager = deployment.getSessionManager();
        Session session = sessionManager.getSession(exchange, c);
        if (session != null) {
            httpSession = SecurityActions.forSession(session, this, false);
            exchange.putAttachment(sessionAttachmentKey, httpSession);
        } else if (create) {
            String existing = c.findSessionId(exchange);
            if (originalServletContext != this) {
                //this is a cross context request
                //we need to make sure there is a top level session
                originalServletContext.getSession(originalServletContext, exchange, true);
            } else if (existing != null) {
                if (deploymentInfo.isCheckOtherSessionManagers()) {
                    boolean found = false;
                    for (String deploymentName : deployment.getServletContainer().listDeployments()) {
                        DeploymentManager deployment = this.deployment.getServletContainer().getDeployment(deploymentName);
                        if (deployment != null) {
                            if (deployment.getDeployment().getSessionManager().getSession(existing) != null) {
                                found = true;
                                break;
                            }
                        }
                    }
                    if (!found) {
                        c.clearSession(exchange, existing);
                    }
                } else {
                    c.clearSession(exchange, existing);
                }
            }
            final Session newSession = sessionManager.createSession(exchange, c);
            httpSession = SecurityActions.forSession(newSession, this, true);
            exchange.putAttachment(sessionAttachmentKey, httpSession);
        }
    }
    return httpSession;
}
Also used : DeploymentManager(io.undertow.servlet.api.DeploymentManager) SessionManager(io.undertow.server.session.SessionManager) SslSessionConfig(io.undertow.server.session.SslSessionConfig) PathParameterSessionConfig(io.undertow.server.session.PathParameterSessionConfig) SessionConfig(io.undertow.server.session.SessionConfig) Session(io.undertow.server.session.Session)

Example 10 with SessionConfig

use of io.undertow.server.session.SessionConfig in project wildfly by wildfly.

the class DistributableSessionManagerTestCase method getSessionNotExists.

@Test
public void getSessionNotExists() {
    HttpServerExchange exchange = new HttpServerExchange(null);
    Batcher<Batch> batcher = mock(Batcher.class);
    Batch batch = mock(Batch.class);
    SessionConfig config = mock(SessionConfig.class);
    String sessionId = "session";
    when(config.findSessionId(exchange)).thenReturn(sessionId);
    when(this.manager.findSession(sessionId)).thenReturn(null);
    when(this.manager.getBatcher()).thenReturn(batcher);
    when(batcher.createBatch()).thenReturn(batch);
    io.undertow.server.session.Session sessionAdapter = this.adapter.getSession(exchange, config);
    assertNull(sessionAdapter);
    verify(batch).close();
    verify(batcher, never()).suspendBatch();
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) Batch(org.wildfly.clustering.ee.Batch) SessionConfig(io.undertow.server.session.SessionConfig) Test(org.junit.Test)

Aggregations

SessionConfig (io.undertow.server.session.SessionConfig)16 HttpServerExchange (io.undertow.server.HttpServerExchange)10 Test (org.junit.Test)8 SessionManager (io.undertow.server.session.SessionManager)6 Batch (org.wildfly.clustering.ee.Batch)6 Session (io.undertow.server.session.Session)5 AuthenticatedSession (io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession)3 PathParameterSessionConfig (io.undertow.server.session.PathParameterSessionConfig)2 SslSessionConfig (io.undertow.server.session.SslSessionConfig)2 Map (java.util.Map)2 BatchContext (org.wildfly.clustering.ee.BatchContext)2 Undertow (io.undertow.Undertow)1 AuthenticatedSessionManager (io.undertow.security.api.AuthenticatedSessionManager)1 SecurityContext (io.undertow.security.api.SecurityContext)1 HttpHandler (io.undertow.server.HttpHandler)1 PathHandler (io.undertow.server.handlers.PathHandler)1 InMemorySessionManager (io.undertow.server.session.InMemorySessionManager)1 SessionAttachmentHandler (io.undertow.server.session.SessionAttachmentHandler)1 SessionCookieConfig (io.undertow.server.session.SessionCookieConfig)1 SessionListener (io.undertow.server.session.SessionListener)1