Search in sources :

Example 16 with HttpSessionListener

use of javax.servlet.http.HttpSessionListener in project tomcat by apache.

the class StandardSessionContext method expire.

/**
     * Perform the internal processing required to invalidate this session,
     * without triggering an exception if the session has already expired.
     *
     * @param notify Should we notify listeners about the demise of
     *  this session?
     */
public void expire(boolean notify) {
    // isValid is false
    if (!isValid)
        return;
    synchronized (this) {
        // entered as per bug 56339
        if (expiring || !isValid)
            return;
        if (manager == null)
            return;
        // Mark this session as "being expired"
        expiring = true;
        // Notify interested application event listeners
        // FIXME - Assumes we call listeners in reverse order
        Context context = manager.getContext();
        // listeners
        if (notify) {
            ClassLoader oldContextClassLoader = null;
            try {
                oldContextClassLoader = context.bind(Globals.IS_SECURITY_ENABLED, null);
                Object[] listeners = context.getApplicationLifecycleListeners();
                if (listeners != null && listeners.length > 0) {
                    HttpSessionEvent event = new HttpSessionEvent(getSession());
                    for (int i = 0; i < listeners.length; i++) {
                        int j = (listeners.length - 1) - i;
                        if (!(listeners[j] instanceof HttpSessionListener))
                            continue;
                        HttpSessionListener listener = (HttpSessionListener) listeners[j];
                        try {
                            context.fireContainerEvent("beforeSessionDestroyed", listener);
                            listener.sessionDestroyed(event);
                            context.fireContainerEvent("afterSessionDestroyed", listener);
                        } catch (Throwable t) {
                            ExceptionUtils.handleThrowable(t);
                            try {
                                context.fireContainerEvent("afterSessionDestroyed", listener);
                            } catch (Exception e) {
                            // Ignore
                            }
                            manager.getContext().getLogger().error(sm.getString("standardSession.sessionEvent"), t);
                        }
                    }
                }
            } finally {
                context.unbind(Globals.IS_SECURITY_ENABLED, oldContextClassLoader);
            }
        }
        if (ACTIVITY_CHECK) {
            accessCount.set(0);
        }
        // Remove this session from our manager's active sessions
        manager.remove(this, true);
        // Notify interested session event listeners
        if (notify) {
            fireSessionEvent(Session.SESSION_DESTROYED_EVENT, null);
        }
        // Call the logout method
        if (principal instanceof TomcatPrincipal) {
            TomcatPrincipal gp = (TomcatPrincipal) principal;
            try {
                gp.logout();
            } catch (Exception e) {
                manager.getContext().getLogger().error(sm.getString("standardSession.logoutfail"), e);
            }
        }
        // We have completed expire of this session
        setValid(false);
        expiring = false;
        // Unbind any objects associated with this session
        String[] keys = keys();
        ClassLoader oldContextClassLoader = null;
        try {
            oldContextClassLoader = context.bind(Globals.IS_SECURITY_ENABLED, null);
            for (int i = 0; i < keys.length; i++) {
                removeAttributeInternal(keys[i], notify);
            }
        } finally {
            context.unbind(Globals.IS_SECURITY_ENABLED, oldContextClassLoader);
        }
    }
}
Also used : Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) HttpSessionListener(javax.servlet.http.HttpSessionListener) HttpSessionEvent(javax.servlet.http.HttpSessionEvent) IOException(java.io.IOException) NotSerializableException(java.io.NotSerializableException) WriteAbortedException(java.io.WriteAbortedException) TomcatPrincipal(org.apache.catalina.TomcatPrincipal)

Example 17 with HttpSessionListener

use of javax.servlet.http.HttpSessionListener in project drill by axbaretto.

the class WebServer method createSessionHandler.

/**
 * @return A {@link SessionHandler} which contains a {@link HashSessionManager}
 */
private SessionHandler createSessionHandler(final SecurityHandler securityHandler) {
    SessionManager sessionManager = new HashSessionManager();
    sessionManager.setMaxInactiveInterval(config.getInt(ExecConstants.HTTP_SESSION_MAX_IDLE_SECS));
    sessionManager.addEventListener(new HttpSessionListener() {

        @Override
        public void sessionCreated(HttpSessionEvent se) {
        }

        @Override
        public void sessionDestroyed(HttpSessionEvent se) {
            final HttpSession session = se.getSession();
            if (session == null) {
                return;
            }
            final Object authCreds = session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
            if (authCreds != null) {
                final SessionAuthentication sessionAuth = (SessionAuthentication) authCreds;
                securityHandler.logout(sessionAuth);
                session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
            }
            // Clear all the resources allocated for this session
            @SuppressWarnings("resource") final WebSessionResources webSessionResources = (WebSessionResources) session.getAttribute(WebSessionResources.class.getSimpleName());
            if (webSessionResources != null) {
                webSessionResources.close();
                session.removeAttribute(WebSessionResources.class.getSimpleName());
            }
        }
    });
    return new SessionHandler(sessionManager);
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) HttpSessionListener(javax.servlet.http.HttpSessionListener) HashSessionManager(org.eclipse.jetty.server.session.HashSessionManager) HashSessionManager(org.eclipse.jetty.server.session.HashSessionManager) SessionManager(org.eclipse.jetty.server.SessionManager) HttpSession(javax.servlet.http.HttpSession) HttpSessionEvent(javax.servlet.http.HttpSessionEvent) SessionAuthentication(org.eclipse.jetty.security.authentication.SessionAuthentication)

Example 18 with HttpSessionListener

use of javax.servlet.http.HttpSessionListener in project tomcat70 by apache.

the class StandardContext method listenerStart.

/**
 * Configure the set of instantiated application event listeners
 * for this Context.  Return <code>true</code> if all listeners wre
 * initialized successfully, or <code>false</code> otherwise.
 */
public boolean listenerStart() {
    if (log.isDebugEnabled())
        log.debug("Configuring application event listeners");
    // Instantiate the required listeners
    ApplicationListener[] listeners = applicationListeners;
    Object[] results = new Object[listeners.length];
    boolean ok = true;
    for (int i = 0; i < results.length; i++) {
        if (getLogger().isDebugEnabled())
            getLogger().debug(" Configuring event listener class '" + listeners[i] + "'");
        try {
            ApplicationListener listener = listeners[i];
            results[i] = getInstanceManager().newInstance(listener.getClassName());
            if (listener.isPluggabilityBlocked()) {
                noPluggabilityListeners.add(results[i]);
            }
        } catch (Throwable t) {
            t = ExceptionUtils.unwrapInvocationTargetException(t);
            ExceptionUtils.handleThrowable(t);
            getLogger().error(sm.getString("standardContext.applicationListener", listeners[i].getClassName()), t);
            ok = false;
        }
    }
    if (!ok) {
        getLogger().error(sm.getString("standardContext.applicationSkipped"));
        return (false);
    }
    // Sort listeners in two arrays
    ArrayList<Object> eventListeners = new ArrayList<Object>();
    ArrayList<Object> lifecycleListeners = new ArrayList<Object>();
    for (int i = 0; i < results.length; i++) {
        if ((results[i] instanceof ServletContextAttributeListener) || (results[i] instanceof ServletRequestAttributeListener) || (results[i] instanceof ServletRequestListener) || (results[i] instanceof HttpSessionAttributeListener)) {
            eventListeners.add(results[i]);
        }
        if ((results[i] instanceof ServletContextListener) || (results[i] instanceof HttpSessionListener)) {
            lifecycleListeners.add(results[i]);
        }
    }
    // list.
    for (Object eventListener : getApplicationEventListeners()) {
        eventListeners.add(eventListener);
    }
    setApplicationEventListeners(eventListeners.toArray());
    for (Object lifecycleListener : getApplicationLifecycleListeners()) {
        lifecycleListeners.add(lifecycleListener);
        if (lifecycleListener instanceof ServletContextListener) {
            noPluggabilityListeners.add(lifecycleListener);
        }
    }
    setApplicationLifecycleListeners(lifecycleListeners.toArray());
    if (getLogger().isDebugEnabled())
        getLogger().debug("Sending application start events");
    // Ensure context is not null
    getServletContext();
    context.setNewServletContextListenerAllowed(false);
    Object[] instances = getApplicationLifecycleListeners();
    if (instances == null || instances.length == 0) {
        return ok;
    }
    ServletContextEvent event = new ServletContextEvent(getServletContext());
    ServletContextEvent tldEvent = null;
    if (noPluggabilityListeners.size() > 0) {
        noPluggabilityServletContext = new NoPluggabilityServletContext(getServletContext());
        tldEvent = new ServletContextEvent(noPluggabilityServletContext);
    }
    for (int i = 0; i < instances.length; i++) {
        if (instances[i] == null)
            continue;
        if (!(instances[i] instanceof ServletContextListener))
            continue;
        ServletContextListener listener = (ServletContextListener) instances[i];
        try {
            fireContainerEvent("beforeContextInitialized", listener);
            if (noPluggabilityListeners.contains(listener)) {
                listener.contextInitialized(tldEvent);
            } else {
                listener.contextInitialized(event);
            }
            fireContainerEvent("afterContextInitialized", listener);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            fireContainerEvent("afterContextInitialized", listener);
            getLogger().error(sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t);
            ok = false;
        }
    }
    return (ok);
}
Also used : ServletContextAttributeListener(javax.servlet.ServletContextAttributeListener) ServletRequestAttributeListener(javax.servlet.ServletRequestAttributeListener) HttpSessionListener(javax.servlet.http.HttpSessionListener) ServletContextListener(javax.servlet.ServletContextListener) ServletRequestListener(javax.servlet.ServletRequestListener) ArrayList(java.util.ArrayList) SecurityConstraint(org.apache.catalina.deploy.SecurityConstraint) ApplicationListener(org.apache.catalina.deploy.ApplicationListener) HttpSessionAttributeListener(javax.servlet.http.HttpSessionAttributeListener) ServletContextEvent(javax.servlet.ServletContextEvent)

Example 19 with HttpSessionListener

use of javax.servlet.http.HttpSessionListener in project tomcat70 by apache.

the class StandardSessionContext method expire.

/**
 * Perform the internal processing required to invalidate this session,
 * without triggering an exception if the session has already expired.
 *
 * @param notify Should we notify listeners about the demise of
 *  this session?
 */
public void expire(boolean notify) {
    // isValid is false
    if (!isValid)
        return;
    synchronized (this) {
        // entered as per bug 56339
        if (expiring || !isValid)
            return;
        if (manager == null)
            return;
        // Mark this session as "being expired"
        expiring = true;
        // Notify interested application event listeners
        // FIXME - Assumes we call listeners in reverse order
        Context context = (Context) manager.getContainer();
        // The call to expire() may not have been triggered by the webapp.
        // Make sure the webapp's class loader is set when calling the
        // listeners
        ClassLoader oldTccl = null;
        if (context.getLoader() != null && context.getLoader().getClassLoader() != null) {
            oldTccl = Thread.currentThread().getContextClassLoader();
            if (Globals.IS_SECURITY_ENABLED) {
                PrivilegedAction<Void> pa = new PrivilegedSetTccl(context.getLoader().getClassLoader());
                AccessController.doPrivileged(pa);
            } else {
                Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader());
            }
        }
        try {
            Object[] listeners = context.getApplicationLifecycleListeners();
            if (notify && (listeners != null)) {
                HttpSessionEvent event = new HttpSessionEvent(getSession());
                for (int i = 0; i < listeners.length; i++) {
                    int j = (listeners.length - 1) - i;
                    if (!(listeners[j] instanceof HttpSessionListener))
                        continue;
                    HttpSessionListener listener = (HttpSessionListener) listeners[j];
                    try {
                        context.fireContainerEvent("beforeSessionDestroyed", listener);
                        listener.sessionDestroyed(event);
                        context.fireContainerEvent("afterSessionDestroyed", listener);
                    } catch (Throwable t) {
                        ExceptionUtils.handleThrowable(t);
                        try {
                            context.fireContainerEvent("afterSessionDestroyed", listener);
                        } catch (Exception e) {
                        // Ignore
                        }
                        manager.getContainer().getLogger().error(sm.getString("standardSession.sessionEvent"), t);
                    }
                }
            }
        } finally {
            if (oldTccl != null) {
                if (Globals.IS_SECURITY_ENABLED) {
                    PrivilegedAction<Void> pa = new PrivilegedSetTccl(oldTccl);
                    AccessController.doPrivileged(pa);
                } else {
                    Thread.currentThread().setContextClassLoader(oldTccl);
                }
            }
        }
        if (ACTIVITY_CHECK) {
            accessCount.set(0);
        }
        // Remove this session from our manager's active sessions
        manager.remove(this, true);
        // Notify interested session event listeners
        if (notify) {
            fireSessionEvent(Session.SESSION_DESTROYED_EVENT, null);
        }
        // Call the logout method
        if (principal instanceof GenericPrincipal) {
            GenericPrincipal gp = (GenericPrincipal) principal;
            try {
                gp.logout();
            } catch (Exception e) {
                manager.getContainer().getLogger().error(sm.getString("standardSession.logoutfail"), e);
            }
        }
        // We have completed expire of this session
        setValid(false);
        expiring = false;
        // Unbind any objects associated with this session
        String[] keys = keys();
        if (oldTccl != null) {
            if (Globals.IS_SECURITY_ENABLED) {
                PrivilegedAction<Void> pa = new PrivilegedSetTccl(context.getLoader().getClassLoader());
                AccessController.doPrivileged(pa);
            } else {
                Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader());
            }
        }
        try {
            for (int i = 0; i < keys.length; i++) {
                removeAttributeInternal(keys[i], notify);
            }
        } finally {
            if (oldTccl != null) {
                if (Globals.IS_SECURITY_ENABLED) {
                    PrivilegedAction<Void> pa = new PrivilegedSetTccl(oldTccl);
                    AccessController.doPrivileged(pa);
                } else {
                    Thread.currentThread().setContextClassLoader(oldTccl);
                }
            }
        }
    }
}
Also used : Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) StandardContext(org.apache.catalina.core.StandardContext) HttpSessionListener(javax.servlet.http.HttpSessionListener) IOException(java.io.IOException) NotSerializableException(java.io.NotSerializableException) WriteAbortedException(java.io.WriteAbortedException) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) HttpSessionEvent(javax.servlet.http.HttpSessionEvent) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl)

Example 20 with HttpSessionListener

use of javax.servlet.http.HttpSessionListener in project tomee by apache.

the class HttpSessionImplTest method run.

@Test
public void run() throws URISyntaxException {
    final HttpRequest req = new HttpRequestImpl(new URI("http://localhost:1234/foo"));
    final javax.servlet.http.HttpSession session = req.getSession();
    Reflections.set(session, "listeners", Collections.<Object>singletonList(new HttpSessionListener() {

        private int count = 0;

        @Override
        public void sessionCreated(final HttpSessionEvent se) {
        // no-op
        }

        @Override
        public void sessionDestroyed(final HttpSessionEvent se) {
            se.getSession().setAttribute("seen", ++count);
        }
    }));
    session.invalidate();
    final long c1 = Integer.class.cast(session.getAttribute("seen"));
    session.invalidate();
    final long c2 = Integer.class.cast(session.getAttribute("seen"));
    assertEquals(c1, c2);
}
Also used : HttpSessionListener(javax.servlet.http.HttpSessionListener) HttpSessionEvent(javax.servlet.http.HttpSessionEvent) URI(java.net.URI) Test(org.junit.Test)

Aggregations

HttpSessionListener (javax.servlet.http.HttpSessionListener)22 HttpSessionEvent (javax.servlet.http.HttpSessionEvent)15 HttpSession (javax.servlet.http.HttpSession)9 IOException (java.io.IOException)7 ServletException (javax.servlet.ServletException)5 NotSerializableException (java.io.NotSerializableException)4 WriteAbortedException (java.io.WriteAbortedException)4 ServletContext (javax.servlet.ServletContext)4 ServletContextAttributeListener (javax.servlet.ServletContextAttributeListener)4 ServletContextListener (javax.servlet.ServletContextListener)4 HttpSessionAttributeListener (javax.servlet.http.HttpSessionAttributeListener)4 Context (org.apache.catalina.Context)4 SessionAuthentication (org.eclipse.jetty.security.authentication.SessionAuthentication)4 SessionHandler (org.eclipse.jetty.server.session.SessionHandler)4 ServletRequestAttributeListener (javax.servlet.ServletRequestAttributeListener)3 ServletRequestListener (javax.servlet.ServletRequestListener)3 HttpSessionIdListener (javax.servlet.http.HttpSessionIdListener)3 Test (org.junit.Test)3 ListenerInfo (io.undertow.servlet.api.ListenerInfo)2 ManagedListener (io.undertow.servlet.core.ManagedListener)2