cmssessionmanager.java

来自「找了很久才找到到源代码」· Java 代码 · 共 606 行 · 第 1/2 页

JAVA
606
字号
        }
        // send the broadcast only to the selected session
        CmsSessionInfo sessionInfo = m_sessionStorageProvider.get(new CmsUUID(sessionId));
        if (sessionInfo != null) {
            // double check for concurrent modification
            sessionInfo.getBroadcastQueue().add(new CmsBroadcast(cms.getRequestContext().currentUser(), message));
        }
    }

    /**
     * Sends a broadcast to all sessions of a given user.<p>
     * 
     * The user sending the message may be a real user like 
     * <code>cms.getRequestContext().currentUser()</code> or
     * <code>null</code> for a system message.<p>
     * 
     * @param fromUser the user sending the broadcast
     * @param message the message to broadcast
     * @param toUser the target (receiver) of the broadcast
     */
    public void sendBroadcast(CmsUser fromUser, String message, CmsUser toUser) {

        if (CmsStringUtil.isEmptyOrWhitespaceOnly(message)) {
            // don't broadcast empty messages
            return;
        }
        // create the broadcast
        CmsBroadcast broadcast = new CmsBroadcast(fromUser, message);
        List userSessions = getSessionInfos(toUser.getId());
        Iterator i = userSessions.iterator();
        // send the broadcast to all sessions of the selected user
        while (i.hasNext()) {
            CmsSessionInfo sessionInfo = (CmsSessionInfo)i.next();
            if (m_sessionStorageProvider.get(sessionInfo.getSessionId()) != null) {
                // double check for concurrent modification
                sessionInfo.getBroadcastQueue().add(broadcast);
            }
        }
    }

    /**
     * Switches the current user to the given user. The session info is rebuild as if the given user
     * performs a login at the workplace.
     * 
     * @param cms the current CmsObject
     * @param req the current request
     * @param user the user to switch to
     * 
     * @throws CmsException if something goes wrong
     */
    public void switchUser(CmsObject cms, HttpServletRequest req, CmsUser user) throws CmsException {

        // only user with ACCOUNT_MANAGER role are allowed to switch the user
        OpenCms.getRoleManager().checkRole(cms, CmsRole.ACCOUNT_MANAGER.forOrgUnit(user.getOuFqn()));
        CmsSessionInfo info = getSessionInfo(req);
        HttpSession session = req.getSession(false);
        if (info == null || session == null) {
            throw new CmsException(Messages.get().container(Messages.ERR_NO_SESSIONINFO_SESSION_0));
        }

        if (!OpenCms.getRoleManager().hasRole(cms, user.getName(), CmsRole.WORKPLACE_USER)) {
            throw new CmsSecurityException(Messages.get().container(Messages.ERR_NO_WORKPLACE_PERMISSIONS_0));
        }

        // get the user settings for the given user and set the start project and the site root
        CmsUserSettings settings = new CmsUserSettings(user);
        CmsProject userProject = cms.readProject(settings.getStartProject());
        String userSiteRoot = settings.getStartSite();
        CmsRequestContext context = new CmsRequestContext(
            user,
            userProject,
            null,
            userSiteRoot,
            null,
            null,
            null,
            0,
            null,
            null,
            null);
        // create a new CmsSessionInfo and store it inside the session map
        CmsSessionInfo newInfo = new CmsSessionInfo(context, info.getSessionId(), info.getMaxInactiveInterval());
        addSessionInfo(newInfo);
        // set the site root and the current project to the user preferences
        cms.getRequestContext().setSiteRoot(userSiteRoot);
        cms.getRequestContext().setCurrentProject(userProject);

        // delete the stored workplace settings, so the session has to receive them again
        session.removeAttribute(CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS);
    }

    /**
     * @see java.lang.Object#toString()
     */
    public String toString() {

        StringBuffer output = new StringBuffer();
        Iterator i = m_sessionStorageProvider.getAll().iterator();
        output.append("[CmsSessions]:\n");
        while (i.hasNext()) {
            CmsSessionInfo sessionInfo = (CmsSessionInfo)i.next();
            output.append(sessionInfo.getSessionId().toString());
            output.append(" : ");
            output.append(sessionInfo.getUserId().toString());
            output.append('\n');
        }
        return output.toString();
    }

    /**
     * Updates all session info objects, so that invalid projects 
     * are replaced by the Online project.<p>
     * 
     * @param cms the cms context
     */
    public void updateSessionInfos(CmsObject cms) {

        // get all sessions
        List userSessions = getSessionInfos();
        Iterator i = userSessions.iterator();
        while (i.hasNext()) {
            CmsSessionInfo sessionInfo = (CmsSessionInfo)i.next();
            // check is the project stored in this session is not existing anymore
            // if so, set it to the online project
            CmsUUID projectId = sessionInfo.getProject();
            try {
                cms.readProject(projectId);
            } catch (CmsException e) {
                // the project does not longer exist, update the project information with the online project
                sessionInfo.setProject(CmsProject.ONLINE_PROJECT_ID);
                addSessionInfo(sessionInfo);
            }
        }
    }

    /**
     * Adds a new session info into the session storage.<p>
     *
     * @param sessionInfo the session info to store for the id
     */
    protected void addSessionInfo(CmsSessionInfo sessionInfo) {

        m_sessionStorageProvider.put(sessionInfo);
    }

    /**
     * Returns the UUID representation for the given session id String.<p>
     * 
     * @param sessionId the session id String to return the  UUID representation for
     * 
     * @return the UUID representation for the given session id String
     */
    protected CmsUUID getSessionUUID(String sessionId) {

        return new CmsUUID(sessionId);
    }

    /**
     * Sets the storage provider.<p>
     * 
     * @param sessionStorageProvider the storage provider implementation
     */
    protected void initialize(I_CmsSessionStorageProvider sessionStorageProvider) {

        m_sessionStorageProvider = sessionStorageProvider;
        m_sessionStorageProvider.initialize();
    }

    /**
     * Called by the {@link OpenCmsListener} when a http session is created.<p>
     * 
     * @param event the http session event
     * 
     * @see javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
     * @see OpenCmsListener#sessionCreated(HttpSessionEvent)
     */
    protected void sessionCreated(HttpSessionEvent event) {

        synchronized (m_lockSessionCount) {
            m_sessionCountCurrent = (m_sessionCountCurrent <= 0) ? 1 : (m_sessionCountCurrent + 1);
            m_sessionCountTotal++;
            if (LOG.isInfoEnabled()) {
                LOG.info(Messages.get().getBundle().key(
                    Messages.LOG_SESSION_CREATED_2,
                    new Integer(m_sessionCountTotal),
                    new Integer(m_sessionCountCurrent)));
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_SESSION_CREATED_1, event.getSession().getId()));
        }
    }

    /**
     * Called by the {@link OpenCmsListener} when a http session is destroyed.<p>
     * 
     * @param event the http session event
     * 
     * @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
     * @see OpenCmsListener#sessionDestroyed(HttpSessionEvent)
     */
    protected void sessionDestroyed(HttpSessionEvent event) {

        synchronized (m_lockSessionCount) {
            m_sessionCountCurrent = (m_sessionCountCurrent <= 0) ? 0 : (m_sessionCountCurrent - 1);
            if (LOG.isInfoEnabled()) {
                LOG.info(Messages.get().getBundle().key(
                    Messages.LOG_SESSION_DESTROYED_2,
                    new Integer(m_sessionCountTotal),
                    new Integer(m_sessionCountCurrent)));
            }
        }

        CmsSessionInfo sessionInfo = getSessionInfo(event.getSession());
        CmsUUID userId = null;
        if (sessionInfo != null) {
            userId = sessionInfo.getUserId();
            m_sessionStorageProvider.remove(sessionInfo.getSessionId());
        }

        if ((userId != null) && (getSessionInfos(userId).size() == 0)) {
            // remove the temporary locks of this user from memory
            OpenCmsCore.getInstance().getLockManager().removeTempLocks(userId);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_SESSION_DESTROYED_1, event.getSession().getId()));
        }
    }

    /**
     * Removes all stored session info objects.<p>
     * 
     * @throws Exception if something goes wrong 
     */
    protected void shutdown() throws Exception {

        if (m_sessionStorageProvider != null) {
            m_sessionStorageProvider.shutdown();
        }
    }

    /**
     * Updates the the OpenCms session data used for quick authentication of users.<p>
     *
     * This is required if the user data (current group or project) was changed in
     * the requested document.<p>
     *
     * The user data is only updated if the user was authenticated to the system.
     *
     * @param cms the current OpenCms user context
     * @param req the current request
     */
    protected void updateSessionInfo(CmsObject cms, HttpServletRequest req) {

        if (!cms.getRequestContext().isUpdateSessionEnabled()) {
            // this request must not update the user session info
            // this is true for long running "thread" requests, e.g. during project publish
            return;
        }

        if (!cms.getRequestContext().currentUser().isGuestUser()) {
            // Guest user requests don't need to update the OpenCms user session information

            // get the session info object for the user
            CmsSessionInfo sessionInfo = getSessionInfo(req);
            if (sessionInfo != null) {
                // update the users session information
                sessionInfo.update(cms.getRequestContext());
                addSessionInfo(sessionInfo);
            } else {
                HttpSession session = req.getSession(false);
                // only create session info if a session is already available 
                if (session != null) {
                    // create a new session info for the user
                    sessionInfo = new CmsSessionInfo(
                        cms.getRequestContext(),
                        new CmsUUID(),
                        session.getMaxInactiveInterval());
                    // append the session info to the http session
                    session.setAttribute(CmsSessionInfo.ATTRIBUTE_SESSION_ID, sessionInfo.getSessionId().clone());
                    // update the session info user data
                    addSessionInfo(sessionInfo);
                }
            }
        }
    }

    /**
     * Validates the sessions stored in this manager and removes 
     * any sessions that have become invalidated.<p>
     */
    protected void validateSessionInfos() {

        // since this method could be called from another thread
        // we have to prevent access before initialization
        if (m_sessionStorageProvider == null) {
            return;
        }
        m_sessionStorageProvider.validate();
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?