Class SessionManager

  • All Implemented Interfaces:
    ClusterEventListener, Module

    public class SessionManager
    extends BasicModule
    implements ClusterEventListener
    Manages the sessions associated with an account. The information maintained by the Session manager is entirely transient and does not need to be preserved between server restarts.
    Author:
    Derek DeMoro
    • Constructor Detail

      • SessionManager

        public SessionManager()
    • Method Detail

      • getInstance

        public static SessionManager getInstance()
        Returns the instance of SessionManagerImpl being used by the XMPPServer.
        Returns:
        the instance of SessionManagerImpl being used by the XMPPServer.
      • addDetached

        public void addDetached​(LocalSession localSession)
        Record a session as being detached (ie, has no connection). This is idempotent. This should really only be called by the LocalSession itself when it detaches.
        Parameters:
        localSession - the LocalSession (this) to mark as detached.
      • isDetached

        public boolean isDetached​(LocalSession localSession)
        Checks if a session is currently in the detached state (ie, has no connection, but has not been formally closed yet either).
        Parameters:
        localSession - A session
        Returns:
        true if the session is currently in 'detached' state, otherwise 'false'.
      • terminateDetached

        public void terminateDetached​(LocalSession session)
        Terminate a session that is detached. A presence 'unavailable' is broadcast for the session that's being terminated. The session will be removed from the routing table. When the provided session is not recognized as a detached session (on this cluster node), then this method will log a message but not apply any changes.
        Parameters:
        session - The (detached) session to be terminated.
      • removeDetached

        public boolean removeDetached​(LocalSession localSession)
        Remove a session as being detached. This is idempotent. This should be called by the LocalSession itself either when resumed or when closed.
        Parameters:
        localSession - the LocalSession (this) which has been resumed or closed.
      • getConnectionMultiplexerSession

        public ConnectionMultiplexerSession getConnectionMultiplexerSession​(org.xmpp.packet.JID address)
        Returns the session originated from the specified address or null if none was found. The specified address MUST contain a resource that uniquely identifies the session. A single connection manager should connect to the same node.
        Parameters:
        address - the address of the connection manager (including resource that identifies specific socket)
        Returns:
        the session originated from the specified address.
      • getConnectionMultiplexerSessions

        public List<ConnectionMultiplexerSession> getConnectionMultiplexerSessions()
        Returns all sessions originated from connection managers.
        Returns:
        all sessions originated from connection managers.
      • getConnectionMultiplexerSessions

        public List<ConnectionMultiplexerSession> getConnectionMultiplexerSessions​(String domain)
        Returns a collection with all the sessions originated from the connection manager whose domain matches the specified domain. If there is no connection manager with the specified domain then an empty list is going to be returned.
        Parameters:
        domain - the domain of the connection manager.
        Returns:
        a collection with all the sessions originated from the connection manager whose domain matches the specified domain.
      • createMultiplexerSession

        public LocalConnectionMultiplexerSession createMultiplexerSession​(Connection conn,
                                                                          org.xmpp.packet.JID address)
        Creates a new ConnectionMultiplexerSession.
        Parameters:
        conn - the connection to create the session from.
        address - the JID (may include a resource) of the connection manager's session.
        Returns:
        a newly created session.
      • nextStreamID

        public StreamID nextStreamID()
        Returns a randomly created ID to be used in a stream element.
        Returns:
        a randomly created ID to be used in a stream element.
      • createClientSession

        public LocalClientSession createClientSession​(Connection conn,
                                                      Locale language)
        Creates a new ClientSession. The new Client session will have a newly created stream ID.
        Parameters:
        conn - the connection to create the session from.
        language - The language to use for the new session.
        Returns:
        a newly created session.
      • createClientSession

        public LocalClientSession createClientSession​(Connection conn,
                                                      StreamID id)
        Creates a new ClientSession with the specified streamID.
        Parameters:
        conn - the connection to create the session from.
        id - the streamID to use for the new session.
        Returns:
        a newly created session.
      • createClientSession

        public LocalClientSession createClientSession​(Connection conn,
                                                      StreamID id,
                                                      Locale language)
        Creates a new ClientSession with the specified streamID.
        Parameters:
        conn - the connection to create the session from.
        id - the streamID to use for the new session.
        language - The language to use for the new session.
        Returns:
        a newly created session.
      • createClientHttpSession

        public HttpSession createClientHttpSession​(StreamID id,
                                                   HttpConnection connection,
                                                   Locale language,
                                                   Duration wait,
                                                   int hold,
                                                   boolean isEncrypted,
                                                   Duration maxPollingInterval,
                                                   int maxRequests,
                                                   Duration maxPause,
                                                   Duration defaultInactivityTimeout,
                                                   int majorVersion,
                                                   int minorVersion)
                                            throws UnauthorizedException,
                                                   UnknownHostException
        Creates a new ClientSession with the specified streamID.
        Parameters:
        connection - the connection to create the session from.
        id - the streamID to use for the new session.
        language - The language to use for the session
        wait - The longest time it is permissible to wait for a response.
        hold - The maximum number of simultaneous waiting requests.
        isEncrypted - True if all connections on this session should be encrypted, and false if they should not.
        maxPollingInterval - The max interval within which a client can send polling requests.
        maxRequests - The max number of requests it is permissible for the session to have open at any one time.
        maxPause - The maximum length of a temporary session pause (in seconds) that the client MAY request.
        defaultInactivityTimeout - The default inactivity timeout of this session.
        majorVersion - the major version of BOSH specification which this session utilizes.
        minorVersion - the minor version of BOSH specification which this session utilizes.
        Returns:
        a newly created session.
        Throws:
        UnauthorizedException - if the server has not been initialised
        UnknownHostException - if no IP address for the peer could be found,
      • createIncomingServerSession

        public LocalIncomingServerSession createIncomingServerSession​(Connection conn,
                                                                      StreamID id,
                                                                      String fromDomain)
                                                               throws UnauthorizedException
        Creates a session for a remote server. The session should be created only after the remote server has been authenticated either using "server dialback" or SASL.
        Parameters:
        conn - the connection to the remote server.
        id - the stream ID used in the stream element when authenticating the server.
        fromDomain - The originating domain
        Returns:
        the newly created IncomingServerSession.
        Throws:
        UnauthorizedException - if the local server has not been initialized yet.
      • outgoingServerSessionCreated

        public void outgoingServerSessionCreated​(LocalOutgoingServerSession session)
        Notification message that a new OutgoingServerSession has been created. Register a listener that will react when the connection gets closed.
        Parameters:
        session - the newly created OutgoingServerSession.
      • registerIncomingServerSession

        public void registerIncomingServerSession​(String domain,
                                                  LocalIncomingServerSession session)
        Registers that a server session originated by a remote server is hosting a given domain. Notice that the remote server may be hosting several subdomains as well as virtual hosts so the same IncomingServerSession may be associated with many domains. If the remote server creates many sessions to this server (eg. one for each subdomain) then associate all the sessions with the originating server that created all the sessions.
        Parameters:
        domain - the domain that is being served by the remote server.
        session - the incoming server session to the remote server.
      • unregisterIncomingServerSession

        public void unregisterIncomingServerSession​(@Nonnull
                                                    String domain,
                                                    @Nonnull
                                                    LocalIncomingServerSession session)
        Unregisters the specified remote domain that previously originated from the specified session of a remote server. This will retain a cache entry for the session as long as there is one or more validated domains remain associated with the session.
        Parameters:
        domain - the domain that is no longer being served by the remote server.
        session - the session from which to unregister the domain.
      • unregisterIncomingServerSession

        public void unregisterIncomingServerSession​(@Nonnull
                                                    StreamID streamID)
        Unregisters a remote server session identified by a stream ID, and disassociates all associated domains.
        Parameters:
        streamID - identifier for the session to unregister.
      • addSession

        public void addSession​(LocalClientSession session)
        Add a new session to be managed. The session has been authenticated and resource binding has been done.
        Parameters:
        session - the session that was authenticated.
      • sessionAvailable

        public void sessionAvailable​(LocalClientSession session,
                                     org.xmpp.packet.Presence presence)
        Notification message sent when a client sent an available presence for the session. Making the session available means that the session is now eligible for receiving messages from other clients. Sessions whose presence is not available may only receive packets (IQ packets) from the server. Therefore, an unavailable session remains invisible to other clients.
        Parameters:
        session - the session that receieved an available presence.
        presence - the presence for the session.
      • isOtherResourcePresenceEnabled

        public static boolean isOtherResourcePresenceEnabled()
        Returns true if the session should broadcast presences to all other resources for the current client. When disabled it is not possible to broadcast presence packets to another resource of the connected user. This is desirable if you have a use case where you have many resources attached to the same user account.
        Returns:
        true if presence should be broadcast to other resources of the same account
      • broadcastPresenceToResources

        public void broadcastPresenceToResources​(org.xmpp.packet.JID originatingResource,
                                                 org.xmpp.packet.Presence presence)
        Broadcasts presence updates from the originating user's resource to any of the user's existing available resources (including the resource from where the update originates).
        Parameters:
        originatingResource - the full JID of the session that sent the presence update.
        presence - the presence.
      • sessionUnavailable

        public void sessionUnavailable​(LocalClientSession session)
        Notification message sent when a client sent an unavailable presence for the session. Making the session unavailable means that the session is not eligible for receiving messages from other clients.
        Parameters:
        session - the session that received an unavailable presence.
      • changePriority

        public void changePriority​(LocalClientSession session,
                                   int oldPriority)
        Change the priority of a session, that was already available, associated with the sender.
        Parameters:
        session - The session whose presence priority has been modified
        oldPriority - The old priority for the session
      • isAnonymousRoute

        public boolean isAnonymousRoute​(String username)
      • isAnonymousRoute

        public boolean isAnonymousRoute​(org.xmpp.packet.JID address)
      • isActiveRoute

        public boolean isActiveRoute​(String username,
                                     String resource)
      • getSession

        public ClientSession getSession​(org.xmpp.packet.JID from)
        Returns the session responsible for this JID data. The returned Session may have never sent an available presence (thus not have a route) or could be a Session that hasn't authenticated yet (i.e. preAuthenticatedSessions).
        Parameters:
        from - the sender of the packet.
        Returns:
        the Session associated with the JID.
      • getSessions

        public Collection<ClientSession> getSessions()
        Returns a list that contains all authenticated client sessions connected to the server. The list contains sessions of anonymous and non-anonymous users.
        Returns:
        a list that contains all client sessions connected to the server.
      • getIncomingServerSession

        public LocalIncomingServerSession getIncomingServerSession​(StreamID streamID)
        Returns the incoming server session hosted by this JVM that matches the specified stream ID.
        Parameters:
        streamID - the stream ID that identifies the incoming server session hosted by this JVM.
        Returns:
        the incoming server session hosted by this JVM or null if none was found.
      • getIncomingServerSessions

        public List<IncomingServerSession> getIncomingServerSessions​(String domain)
        Returns the list of sessions that were originated by a remote server. The list will be ordered chronologically. IncomingServerSession can only receive packets from the remote server but are not capable of sending packets to the remote server.
        Parameters:
        domain - the name of the remote server.
        Returns:
        the sessions that were originated by a remote server.
      • getOutgoingServerSession

        public OutgoingServerSession getOutgoingServerSession​(DomainPair pair)
        Returns a session that was originated from this server to a remote server. OutgoingServerSession an only send packets to the remote server but are not capable of receiving packets from the remote server.
        Parameters:
        pair - DomainPair describing the local and remote servers.
        Returns:
        a session that was originated from this server to a remote server.
      • getConnectionsCount

        public int getConnectionsCount​(boolean onlyLocal)
        Returns number of client sessions that are connected to the server. Sessions that are authenticated and not authenticated will be included
        Parameters:
        onlyLocal - true if only sessions connected to this JVM will be considered. Otherwise count cluster wise.
        Returns:
        number of client sessions that are connected to the server.
      • getUserSessionsCount

        public int getUserSessionsCount​(boolean onlyLocal)
        Returns number of client sessions that are authenticated with the server. This includes anonymous and non-anoymous users.
        Parameters:
        onlyLocal - true if only sessions connected to this JVM will be considered. Otherwise count cluster wise.
        Returns:
        number of client sessions that are authenticated with the server.
      • getIncomingServerSessionsCount

        public int getIncomingServerSessionsCount​(boolean onlyLocal)
        Returns number of sessions coming from remote servers. Current implementation is only counting sessions connected to this JVM and not adding up sessions connected to other cluster nodes.
        Parameters:
        onlyLocal - true if only sessions connected to this JVM will be considered. Otherwise count cluster wise.
        Returns:
        number of sessions coming from remote servers.
      • getActiveSessionCount

        public int getActiveSessionCount​(String username)
        Returns the number of sessions for a user that are available. For the count of all sessions for the user, including sessions that are just starting or closed.
        Parameters:
        username - the user.
        Returns:
        number of available sessions for a user.
        See Also:
        getConnectionsCount(boolean)
      • getSessionCount

        public int getSessionCount​(String username)
      • getComponentSessions

        public Collection<ComponentSession> getComponentSessions()
        Returns a collection with the established sessions from external components.
        Returns:
        a collection with the established sessions from external components.
      • getComponentSession

        public ComponentSession getComponentSession​(String domain)
        Returns the session of the component whose domain matches the specified domain.
        Parameters:
        domain - the domain of the component session to look for.
        Returns:
        the session of the component whose domain matches the specified domain.
      • getIncomingServers

        public Collection<String> getIncomingServers()
        Returns a collection with the domain names of the remote servers that currently have an incoming server connection to this server.
        Returns:
        a collection with the domains of the remote servers that currently have an incoming server connection to this server.
      • getOutgoingServers

        public Collection<String> getOutgoingServers()
        Returns a collection with the domain names of the remote servers that currently may receive packets sent from this server.
        Returns:
        a collection with the domains of the remote servers that currently may receive packets sent from this server.
      • broadcast

        public void broadcast​(org.xmpp.packet.Message packet)
        Broadcasts the given data to all connected sessions. Excellent for server administration messages.
        Parameters:
        packet - the packet to be broadcast.
      • userBroadcast

        public void userBroadcast​(String username,
                                  org.xmpp.packet.Packet packet)
                           throws PacketException
        Broadcasts the given data to all connected sessions for a particular user. Excellent for updating all connected resources for users such as roster pushes.
        Parameters:
        username - the user to send the boradcast to.
        packet - the packet to be broadcast.
        Throws:
        PacketException - if a packet exception occurs.
      • removeSession

        public boolean removeSession​(LocalClientSession session)
        Removes a session.
        Parameters:
        session - the session.
        Returns:
        true if the requested session was successfully removed.
      • removeSession

        public boolean removeSession​(ClientSession session,
                                     org.xmpp.packet.JID fullJID,
                                     boolean anonymous,
                                     boolean forceUnavailable)
        Removes a session.
        Parameters:
        session - the session or null when session is derived from fullJID.
        fullJID - the address of the session.
        anonymous - true if the authenticated user is anonymous.
        forceUnavailable - true if an unavailable presence must be created and routed.
        Returns:
        true if the requested session was successfully removed.
      • getConflictKickLimit

        public int getConflictKickLimit()
      • getPreAuthenticatedKeys

        public Collection<String> getPreAuthenticatedKeys()
        Returns the temporary keys used by the sessions that has not been authenticated yet. This is an utility method useful for debugging situations.
        Returns:
        the temporary keys used by the sessions that has not been authenticated yet.
      • isPreAuthenticatedSession

        public boolean isPreAuthenticatedSession​(org.xmpp.packet.JID address)
        Returns true if the specified address belongs to a preauthenticated session. Preauthenticated sessions are only available to the local cluster node when running inside of a cluster.
        Parameters:
        address - the address of the session.
        Returns:
        true if the specified address belongs to a preauthenticated session.
      • setConflictKickLimit

        public void setConflictKickLimit​(int limit)
      • getLocaleForSession

        public Locale getLocaleForSession​(org.xmpp.packet.JID address)
      • initialize

        public void initialize​(XMPPServer server)
        Description copied from class: BasicModule

        Initializes the basic module.

        Inheriting classes that choose to override this method MUST call this initialize() method before accessing BasicModule resources.

        Specified by:
        initialize in interface Module
        Overrides:
        initialize in class BasicModule
        Parameters:
        server - the server hosting this module.
      • sendServerMessage

        public void sendServerMessage​(String subject,
                                      String body)
        Sends a message with a given subject and body to all the active user sessions in the server.
        Parameters:
        subject - the subject to broadcast.
        body - the body to broadcast.
      • sendServerMessage

        public void sendServerMessage​(org.xmpp.packet.JID address,
                                      String subject,
                                      String body)
        Sends a message with a given subject and body to one or more user sessions related to the specified address. If address is null or the address's node is null then the message will be sent to all the user sessions. But if the address includes a node but no resource then the message will be sent to all the user sessions of the requested user (defined by the node). Finally, if the address is a full JID then the message will be sent to the session associated to the full JID. If no session is found then the message is not sent.
        Parameters:
        address - the address that defines the sessions that will receive the message.
        subject - the subject to broadcast.
        body - the body to broadcast.
      • start

        public void start()
                   throws IllegalStateException
        Description copied from class: BasicModule

        Starts the basic module.

        Inheriting classes that choose to override this method MUST call this start() method before accessing BasicModule resources.

        Specified by:
        start in interface Module
        Overrides:
        start in class BasicModule
        Throws:
        IllegalStateException - If start is called before initialize successfully returns
      • stop

        public void stop()
        Description copied from class: BasicModule

        Stops the basic module.

        Inheriting classes that choose to override this method MUST call this stop() method before accessing BasicModule resources.

        Specified by:
        stop in interface Module
        Overrides:
        stop in class BasicModule
      • isMultipleServerConnectionsAllowed

        public boolean isMultipleServerConnectionsAllowed()
        Returns true if remote servers are allowed to have more than one connection to this server. Having more than one connection may improve number of packets that can be transfered per second. This setting only used by the server dialback mehod.

        It is highly recommended that getServerSessionTimeout() is enabled so that dead connections to this server can be easily discarded.

        Returns:
        true if remote servers are allowed to have more than one connection to this server.
      • setMultipleServerConnectionsAllowed

        public void setMultipleServerConnectionsAllowed​(boolean allowed)
        Sets if remote servers are allowed to have more than one connection to this server. Having more than one connection may improve number of packets that can be transfered per second. This setting only used by the server dialback mehod.

        It is highly recommended that getServerSessionTimeout() is enabled so that dead connections to this server can be easily discarded.

        Parameters:
        allowed - true if remote servers are allowed to have more than one connection to this server.
      • setServerSessionTimeout

        public void setServerSessionTimeout​(int timeout)
        Sets the number of milliseconds to elapse between clearing of idle server sessions.
        Parameters:
        timeout - the number of milliseconds to elapse between clearings.
      • getServerSessionTimeout

        public int getServerSessionTimeout()
        Returns the number of milliseconds to elapse between clearing of idle server sessions.
        Returns:
        the number of milliseconds to elapse between clearing of idle server sessions.
      • setServerSessionIdleTime

        public void setServerSessionIdleTime​(int idleTime)
      • getServerSessionIdleTime

        public int getServerSessionIdleTime()
      • setSessionDetachTime

        public void setSessionDetachTime​(int idleTime)
      • getSessionDetachTime

        public int getSessionDetachTime()
      • joinedCluster

        public void joinedCluster()
        Description copied from interface: ClusterEventListener
        Notification event indicating that this JVM is now part of a cluster. At this point the XMPPServer.getNodeID() holds the new nodeID value.

        When joining the cluster as the senior cluster member the ClusterEventListener.markedAsSeniorClusterMember() event will be sent right after this event.

        At this point the CacheFactory holds clustered caches. That means that modifications to the caches will be reflected in the cluster. The clustered caches were just obtained from the cluster and no local cached data was automatically moved.

        It is generally advisable that implementations of this method:
        • enrich clustered cache data, by (re)adding data from this JVM/cluster node to relevant caches
        • invoke applicable event listeners, to reflect changes in availability of data on other cluster nodes.
        Specified by:
        joinedCluster in interface ClusterEventListener
      • joinedCluster

        public void joinedCluster​(byte[] nodeID)
        Description copied from interface: ClusterEventListener
        Notification event indicating that another JVM is now part of a cluster.

        At this point the CacheFactory of the new node holds clustered caches. That means that modifications to the caches of this JVM will be reflected in the cluster and in particular in the new node.

        Specified by:
        joinedCluster in interface ClusterEventListener
        Parameters:
        nodeID - ID of the node that joined the cluster.
      • leftCluster

        public void leftCluster()
        Description copied from interface: ClusterEventListener
        Notification event indicating that this JVM is no longer part of the cluster. This could happen when disabling clustering support, removing the enterprise plugin that provides clustering support or connection to cluster got lost.

        Moreover, if we were in a "split brain" scenario (ie. separated cluster islands) and the island were this JVM belonged was marked as "old" then all nodes of that island will get the left cluster event and joined cluster events. That means that caches will be reset and thus will need to be repopulated again with fresh data from this JVM. This also includes the case where this JVM was the senior cluster member and when the islands met again then this JVM stopped being the senior member.

        At this point the CacheFactory holds local caches. That means that modifications to the caches will only affect this JVM. It is generally advisable that implementations of this method:

        • restore relevant caches content, by repopulating the caches with data from this JVM/cluster node
        • invoke applicable event listeners, to reflect changes in availability of data on other cluster nodes.
        Specified by:
        leftCluster in interface ClusterEventListener
      • leftCluster

        public void leftCluster​(byte[] nodeID)
        Description copied from interface: ClusterEventListener
        Notification event indicating that another JVM is no longer part of the cluster. This could happen when disabling clustering support, removing the enterprise plugin that provides clustering support or connection to cluster got lost.

        Moreover, if we were in a "split brain" scenario (ie. separated cluster islands) and the island were the other JVM belonged was marked as "old" then all nodes of that island will get the left cluster event and joined cluster events. That means that caches will be reset and thus will need to be repopulated again with fresh data from this JVM. This also includes the case where the other JVM was the senior cluster member and when the islands met again then the other JVM stopped being the senior member.

        At this point the CacheFactory of the leaving node holds local caches. That means that modifications to the caches of this JVM will not affect the leaving node but other cluster members. It is generally advisable that implementations of this method invoke applicable event listeners, to reflect changes in availability of data (related to the node that left). Often, this action is orchestrated by only one of the remaining cluster nodes: the senior member.

        Specified by:
        leftCluster in interface ClusterEventListener
        Parameters:
        nodeID - ID of the node that is left the cluster.
      • markedAsSeniorClusterMember

        public void markedAsSeniorClusterMember()
        Description copied from interface: ClusterEventListener
        Notification event indicating that this JVM is now the senior cluster member. This could either happen when initially joining the cluster or when the senior cluster member node left the cluster and this JVM was marked as the new senior cluster member.

        Moreover, in the case of a "split brain" scenario (ie. separated cluster islands) each island will have its own senior cluster member. However, when the islands meet again there could only be one senior cluster member so one of the senior cluster members will stop playing that role. When that happens the JVM no longer playing that role will receive the ClusterEventListener.leftCluster() and ClusterEventListener.joinedCluster() events.

        Specified by:
        markedAsSeniorClusterMember in interface ClusterEventListener