Example usage for javax.servlet.http HttpSessionBindingListener HttpSessionBindingListener

List of usage examples for javax.servlet.http HttpSessionBindingListener HttpSessionBindingListener

Introduction

In this page you can find the example usage for javax.servlet.http HttpSessionBindingListener HttpSessionBindingListener.

Prototype

HttpSessionBindingListener

Source Link

Usage

From source file:com.adito.core.CoreUtil.java

/**
 * Method to get the session temp download file.
 * /*from   w w  w.j  av a  2 s . c o m*/
 * @param session
 * @return File
 * @throws Exception
 */
public static File getTempDownloadDirectory(SessionInfo session) throws Exception {
    final File tempDownloadDirectory = new File(ContextHolder.getContext().getTempDirectory(),
            TempStore.TEMP_DOWNLOAD_MOUNT_NAME);
    // create the download store if it does not exist.
    if (!tempDownloadDirectory.exists()) {
        if (!tempDownloadDirectory.mkdirs()) {
            throw new Exception("Could not create temporary download directory "
                    + tempDownloadDirectory.getAbsolutePath() + ".");
        }
    }
    // now create the actual session folder
    final File tempSessionDownloadDirectory = new File(tempDownloadDirectory,
            session.getUser().getPrincipalName() + "." + session.getHttpSession().getId());
    if (!tempSessionDownloadDirectory.exists()) {

        // Hook for cleaning up on logout
        session.getHttpSession().setAttribute(DownloadContent.FILES_DOWNLOAD_CLEANUP_SESSION_HOOK,
                new HttpSessionBindingListener() {

                    public void valueBound(HttpSessionBindingEvent event) {
                    }

                    public void valueUnbound(HttpSessionBindingEvent event) {
                        if (log.isInfoEnabled()) {
                            log.info(
                                    "Cleaning up temporary download directory " + tempSessionDownloadDirectory);
                        }
                        Util.delTree(tempSessionDownloadDirectory);
                    }
                });

        if (!tempSessionDownloadDirectory.mkdirs()) {
            throw new Exception("Could not create temporary session download directory "
                    + tempSessionDownloadDirectory.getAbsolutePath() + " for user "
                    + session.getUser().getPrincipalName() + ".");
        }
    }
    return tempSessionDownloadDirectory;
}

From source file:com.adito.security.DefaultLogonController.java

public void initialiseSession(HttpSession session, User user) throws UserDatabaseException {
    if (log.isInfoEnabled())
        log.info("Initialising session " + session.getId() + " with user "
                + (user == null ? "[none]" : user.getPrincipalName()));
    PropertyProfile profile = (PropertyProfile) session.getAttribute(Constants.SELECTED_PROFILE);
    session.setAttribute(Constants.USER, user);
    String logonInfo = MessageResources.getMessageResources("com.adito.navigation.ApplicationResources")
            .getMessage("footer.info", user.getPrincipalName(),
                    SimpleDateFormat.getDateTimeInstance().format(new Date()));
    session.setAttribute(Constants.LOGON_INFO, logonInfo);
    try {/* w  w  w  .  ja  va  2 s. co  m*/
        List profiles = ResourceUtil.filterResources(user, ProfilesFactory.getInstance()
                .getPropertyProfiles(user.getPrincipalName(), true, user.getRealm().getResourceId()), true);
        session.setAttribute(Constants.PROFILES, profiles);
        if (profiles.size() == 0) {
            throw new UserDatabaseException("You do not have permission to use any profiles.");
        }
        String startupProfile = Property.getProperty(new UserAttributeKey(user, User.USER_STARTUP_PROFILE));
        if (profiles.size() < 2) {
            profile = (PropertyProfile) profiles.get(0);
        } else if (!startupProfile.equals(ProfilesListDataSource.SELECT_ON_LOGIN)) {
            int profileId = Integer.parseInt(startupProfile);
            profile = null;
            for (Iterator i = profiles.iterator(); i.hasNext();) {
                PropertyProfile p = (PropertyProfile) i.next();
                if (profileId == p.getResourceId()) {
                    profile = p;
                    break;
                }
            }
            if (profile == null) {
                profile = ProfilesFactory.getInstance().getPropertyProfile(null, "Default",
                        UserDatabaseManager.getInstance().getDefaultUserDatabase().getRealm().getResourceId());
            }
        }
        if (profile != null) {
            if (log.isInfoEnabled())
                log.info("Switching user " + user.getPrincipalName() + " to profile "
                        + profile.getResourceName());
            session.setAttribute(Constants.SELECTED_PROFILE, profile);
        }
    } catch (Exception e) {
        throw new UserDatabaseException("Failed to initialise profiles.", e);
    }
    final String logonTicket = (String) session.getAttribute(Constants.LOGON_TICKET);
    session.setAttribute(Constants.LOGOFF_HOOK, new HttpSessionBindingListener() {
        public void valueBound(HttpSessionBindingEvent evt) {
        }

        public void valueUnbound(HttpSessionBindingEvent evt) {
            if (log.isDebugEnabled())
                log.debug("Session unbound");
            // We should should only log off completely if no other
            // session has
            // the logon ticket
            SessionInfo currentTicketSessionInfo = ((SessionInfo) logons.get(logonTicket));
            if (currentTicketSessionInfo == null
                    || evt.getSession().getId().equals(currentTicketSessionInfo.getHttpSession().getId())) {
                if (log.isDebugEnabled())
                    log.debug("Session (" + evt.getSession().getId()
                            + ") unbound is the current session for ticket " + logonTicket
                            + " so a logoff will be performed.");
                logoff(logonTicket);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Session unbound is NOT the current session, ignoring.");
            }
        }
    });
    if (log.isDebugEnabled())
        log.debug("Using profile: " + (profile == null ? "DEFAULT" : profile.getResourceName()) + ")");
    session.removeAttribute(Constants.SESSION_LOCKED);

    resetSessionTimeout(user, profile, session);
}

From source file:com.sslexplorer.security.DefaultLogonController.java

public void initialiseSession(HttpSession session, User user) throws UserDatabaseException {
    if (log.isInfoEnabled())
        log.info("Initialising session " + session.getId() + " with user "
                + (user == null ? "[none]" : user.getPrincipalName()));
    PropertyProfile profile = (PropertyProfile) session.getAttribute(Constants.SELECTED_PROFILE);
    session.setAttribute(Constants.USER, user);
    String logonInfo = MessageResources.getMessageResources("com.sslexplorer.navigation.ApplicationResources")
            .getMessage("footer.info", user.getPrincipalName(),
                    SimpleDateFormat.getDateTimeInstance().format(new Date()));
    session.setAttribute(Constants.LOGON_INFO, logonInfo);
    try {//from w  ww  . j  a  v a 2 s .  c om
        List profiles = ResourceUtil.filterResources(user, ProfilesFactory.getInstance()
                .getPropertyProfiles(user.getPrincipalName(), true, user.getRealm().getResourceId()), true);
        session.setAttribute(Constants.PROFILES, profiles);
        if (profiles.size() == 0) {
            throw new UserDatabaseException("You do not have permission to use any profiles.");
        }
        String startupProfile = Property.getProperty(new UserAttributeKey(user, User.USER_STARTUP_PROFILE));
        if (profiles.size() < 2) {
            profile = (PropertyProfile) profiles.get(0);
        } else if (!startupProfile.equals(ProfilesListDataSource.SELECT_ON_LOGIN)) {
            int profileId = Integer.parseInt(startupProfile);
            profile = null;
            for (Iterator i = profiles.iterator(); i.hasNext();) {
                PropertyProfile p = (PropertyProfile) i.next();
                if (profileId == p.getResourceId()) {
                    profile = p;
                    break;
                }
            }
            if (profile == null) {
                profile = ProfilesFactory.getInstance().getPropertyProfile(null, "Default",
                        UserDatabaseManager.getInstance().getDefaultUserDatabase().getRealm().getResourceId());
            }
        }
        if (profile != null) {
            if (log.isInfoEnabled())
                log.info("Switching user " + user.getPrincipalName() + " to profile "
                        + profile.getResourceName());
            session.setAttribute(Constants.SELECTED_PROFILE, profile);
        }
    } catch (Exception e) {
        throw new UserDatabaseException("Failed to initialise profiles.", e);
    }
    final String logonTicket = (String) session.getAttribute(Constants.LOGON_TICKET);
    session.setAttribute(Constants.LOGOFF_HOOK, new HttpSessionBindingListener() {
        public void valueBound(HttpSessionBindingEvent evt) {
        }

        public void valueUnbound(HttpSessionBindingEvent evt) {
            if (log.isDebugEnabled())
                log.debug("Session unbound");
            // We should should only log off completely if no other
            // session has
            // the logon ticket
            SessionInfo currentTicketSessionInfo = ((SessionInfo) logons.get(logonTicket));
            if (currentTicketSessionInfo == null
                    || evt.getSession().getId().equals(currentTicketSessionInfo.getHttpSession().getId())) {
                if (log.isDebugEnabled())
                    log.debug("Session (" + evt.getSession().getId()
                            + ") unbound is the current session for ticket " + logonTicket
                            + " so a logoff will be performed.");
                logoff(logonTicket);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Session unbound is NOT the current session, ignoring.");
            }
        }
    });
    if (log.isDebugEnabled())
        log.debug("Using profile: " + (profile == null ? "DEFAULT" : profile.getResourceName()) + ")");
    session.removeAttribute(Constants.SESSION_LOCKED);

    resetSessionTimeout(user, profile, session);
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Sessions01() {
    final AtomicBoolean valueBound = new AtomicBoolean(false);
    final AtomicBoolean valueUnbound = new AtomicBoolean(false);
    final HttpSessionBindingListener bindingListener = new HttpSessionBindingListener() {

        @Override/*from  w w w .jav a2s.c o  m*/
        public void valueUnbound(HttpSessionBindingEvent event) {
            valueUnbound.set(true);
        }

        @Override
        public void valueBound(HttpSessionBindingEvent event) {
            valueBound.set(true);
        }
    };
    final AtomicBoolean sessionCreated = new AtomicBoolean(false);
    final AtomicBoolean sessionDestroyed = new AtomicBoolean(false);
    HttpSessionListener sessionListener = new HttpSessionListener() {

        @Override
        public void sessionDestroyed(HttpSessionEvent se) {
            sessionDestroyed.set(true);
        }

        @Override
        public void sessionCreated(HttpSessionEvent se) {
            sessionCreated.set(true);
        }
    };
    HttpServlet sessionServlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            HttpSession session = request.getSession();
            if (session.getAttribute("test.attribute") == null) {
                session.setAttribute("test.attribute", bindingListener);
                response.getWriter().print("created");
            } else {
                session.invalidate();
                response.getWriter().print("invalidated");
            }
        }

    };
    ServiceRegistration<Servlet> servletReg = null;
    ServiceRegistration<HttpSessionListener> sessionListenerReg = null;
    Dictionary<String, Object> servletProps = new Hashtable<String, Object>();
    servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/sessions");
    String actual = null;
    CookieHandler previous = CookieHandler.getDefault();
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    try {
        servletReg = getBundleContext().registerService(Servlet.class, sessionServlet, servletProps);
        Dictionary<String, String> listenerProps = new Hashtable<String, String>();
        listenerProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_LISTENER, "true");
        sessionListenerReg = getBundleContext().registerService(HttpSessionListener.class, sessionListener,
                listenerProps);

        sessionCreated.set(false);
        valueBound.set(false);
        sessionDestroyed.set(false);
        valueUnbound.set(false);
        // first call will create the session
        actual = requestAdvisor.request("sessions");
        assertEquals("Wrong result", "created", actual);
        assertTrue("No sessionCreated called", sessionCreated.get());
        assertTrue("No valueBound called", valueBound.get());
        assertFalse("sessionDestroyed was called", sessionDestroyed.get());
        assertFalse("valueUnbound was called", valueUnbound.get());

        sessionCreated.set(false);
        valueBound.set(false);
        sessionDestroyed.set(false);
        valueUnbound.set(false);
        // second call will invalidate the session
        actual = requestAdvisor.request("sessions");
        assertEquals("Wrong result", "invalidated", actual);
        assertFalse("sessionCreated was called", sessionCreated.get());
        assertFalse("valueBound was called", valueBound.get());
        assertTrue("No sessionDestroyed called", sessionDestroyed.get());
        assertTrue("No valueUnbound called", valueUnbound.get());

        sessionCreated.set(false);
        sessionDestroyed.set(false);
        valueBound.set(false);
        valueUnbound.set(false);
        // calling again should create the session again
        actual = requestAdvisor.request("sessions");
        assertEquals("Wrong result", "created", actual);
        assertTrue("No sessionCreated called", sessionCreated.get());
        assertTrue("No valueBound called", valueBound.get());
    } catch (Exception e) {
        fail("Unexpected exception: " + e);
    } finally {
        if (servletReg != null) {
            servletReg.unregister();
        }
        if (sessionListenerReg != null) {
            sessionListenerReg.unregister();
        }
        CookieHandler.setDefault(previous);
    }
}

From source file:org.polymap.service.fs.webdav.WebDavServer.java

/**
 * Initializes a new session for the given user.
 * <p/>//from w  w w .ja  v a 2  s. c om
 * This method is called by {@link SecurityManagerAdapter}
 * 
 * @param user
 * @return The specified user.
 */
public static Principal createNewSession(final Principal user) {
    HttpServletRequest req = com.bradmcevoy.http.ServletRequest.getRequest();
    final HttpSession session = req.getSession();

    // HTTP session timeout: 30min
    session.setMaxInactiveInterval(30 * 60);

    FsPlugin.getDefault().sessionContextProvider.mapContext(user.getName(), true);
    final SessionContext sessionContext = SessionContext.current();

    // ContentManager
    Locale locale = req.getLocale();
    sessionContext.setAttribute("contentManager",
            ContentManager.forUser(user.getName(), locale, sessionContext));

    // invalidate HTTP session when context is destroyed
    sessionContext.addSessionListener(new ISessionListener() {
        public void beforeDestroy() {
            log.info("SessionContext is destroyed -> invalidating HTTP session");
            try {
                //sessionContext.removeSessionListener( this );
                session.invalidate();
            } catch (Exception e) {
                log.warn("HTTP session already invalidated: " + e);
            }
        }
    });
    // session destroy listener
    session.setAttribute("sessionListener", new HttpSessionBindingListener() {
        public void valueBound(HttpSessionBindingEvent ev) {
        }

        public void valueUnbound(HttpSessionBindingEvent ev) {
            //
            sessionContext.execute(new Runnable() {
                public void run() {
                    ContentManager.releaseSession(user.getName());
                }
            });
            // prevent life-lock
            if (!sessionContext.isDestroyed() && sessionContext.getAttribute("destroying") == null) {
                sessionContext.setAttribute("destroying", true);
                FsPlugin.getDefault().sessionContextProvider.destroyContext(sessionContext.getSessionKey());
                log.info("HTTP Session destroyed: " + session.getId() + ", user: " + user);
            }
        }
    });
    log.info("New HTTP session: " + session.getId() + ", user: " + user);
    return user;
}