Java Code Examples for org.xmpp.packet.Presence#setType()

The following examples show how to use org.xmpp.packet.Presence#setType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SessionManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Removes a session that existed on a remote cluster node.
 *
 * This method was designed to be used only in case of cluster nodes disappearing.
 *
 * This method takes responsibility for cleaning up the state in RoutingTableImpl
 * as well as SessionManager.
 *
 * @param fullJID the address of the session.
 */
public void removeRemoteClientSession( JID fullJID )
{
    // Remove route to the removed session.
    routingTable.removeClientRoute(fullJID);

    // Existing behavior when this implementation was introduced was to not dispatch SessionEvents
    // for destroyed remote sessions.

    // Non-local sessions cannot exist in the pre-Authenticated sessions list. No need to clean that up.

    // TODO only sent an unavailable presence if the user was 'available'. Unsure if this can be checked when the remote node is shut down.
    Presence offline = new Presence();
    offline.setFrom(fullJID);
    offline.setTo(new JID(null, serverName, null, true));
    offline.setType(Presence.Type.unavailable);
    router.route(offline);

    // Stop tracking information about the session and share it with other cluster nodes.
    // Note that, unlike other caches, this cache is populated only when clustering is enabled.
    sessionInfoCache.remove(fullJID.toString());

    // connectionsCounter tracks only local sessions. No need to decrement it here.
}
 
Example 2
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends presence of a leaving occupant to other occupants.
 *
 * @param leaveRole the role of the occupant that is leaving.
 */
void sendLeavePresenceToExistingOccupants(MUCRole leaveRole) {
    // Send the presence of this new occupant to existing occupants
    Log.trace( "Send presence of leaving occupant '{}' to existing occupants of room '{}'.", leaveRole.getUserAddress(), leaveRole.getChatRoom().getJID() );
    try {
        Presence originalPresence = leaveRole.getPresence();
        Presence presence = originalPresence.createCopy();
        presence.setType(Presence.Type.unavailable);
        presence.setStatus(null);
        // Change (or add) presence information about roles and affiliations
        Element childElement = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
        if (childElement == null) {
            childElement = presence.addChildElement("x", "http://jabber.org/protocol/muc#user");
        }
        Element item = childElement.element("item");
        if (item == null) {
            item = childElement.addElement("item");
        }
        item.addAttribute("role", "none");

        // Check to see if the user's original presence is one we should broadcast
        // a leave packet for. Need to check the original presence because we just
        // set the role to "none" above, which is always broadcast.
        if(!shouldBroadcastPresence(originalPresence)){
            // Inform the leaving user that he/she has left the room
            leaveRole.send(presence);
        }
        else {
            if (getOccupantsByNickname(leaveRole.getNickname()).size() <= 1) {
                // Inform the rest of the room occupants that the user has left the room
                if (JOIN_PRESENCE_ENABLE.getValue()) {
                    broadcastPresence(presence, false, leaveRole);
                }
            }
        }
    }
    catch (Exception e) {
        Log.error( "An exception occurred while sending leave presence of occupant '"+leaveRole.getUserAddress()+"' to the other occupants of room: '"+leaveRole.getChatRoom().getJID()+"'.", e);
    }
}
 
Example 3
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public Presence createPresence(Presence.Type presenceType) {
    Presence presence = new Presence();
    presence.setType(presenceType);
    presence.setFrom(role.getRoleAddress());
    return presence;
}
 
Example 4
Source File: SessionManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Handle a session that just closed.
 *
 * @param handback The session that just closed
 */
@Override
public void onConnectionClose(Object handback) {
    try {
        LocalClientSession session = (LocalClientSession) handback;
        if (session.isDetached()) {
            Log.debug("Closing session with address {} and streamID {} is detached already.", session.getAddress(), session.getStreamID());
            return;
        }
        if (session.getStreamManager().getResume()) {
            Log.debug("Closing session with address {} and streamID {} has SM enabled; detaching.", session.getAddress(), session.getStreamID());
            session.setDetached();
            return;
        } else {
            Log.debug("Closing session with address {} and streamID {} does not have SM enabled.", session.getAddress(), session.getStreamID());
        }
        try {
            if ((session.getPresence().isAvailable() || !session.wasAvailable()) &&
                    routingTable.hasClientRoute(session.getAddress())) {
                // Send an unavailable presence to the user's subscribers
                // Note: This gives us a chance to send an unavailable presence to the
                // entities that the user sent directed presences
                Presence presence = new Presence();
                presence.setType(Presence.Type.unavailable);
                presence.setFrom(session.getAddress());
                router.route(presence);
            }

            session.getStreamManager().onClose(router, serverAddress);
        }
        finally {
            // Remove the session
            removeSession(session);
        }
    }
    catch (Exception e) {
        // Can't do anything about this problem...
        Log.error(LocaleUtils.getLocalizedString("admin.error.close"), e);
    }
}
 
Example 5
Source File: PresenceManagerImpl.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void sendUnavailableFromSessions(JID recipientJID, JID userJID) {
    if (XMPPServer.getInstance().isLocal(userJID) && userManager.isRegisteredUser(userJID.getNode())) {
        for (ClientSession session : sessionManager.getSessions(userJID.getNode())) {
            // Do not send an unavailable presence if the user sent a direct available presence
            if (presenceUpdateHandler.hasDirectPresence(session.getAddress(), recipientJID)) {
                continue;
            }
            Presence presencePacket = new Presence();
            presencePacket.setType(Presence.Type.unavailable);
            presencePacket.setFrom(session.getAddress());
            // Ensure that unavailable presence is sent to all receipient's resources
            Collection<JID> recipientFullJIDs = new ArrayList<>();
            if (server.isLocal(recipientJID)) {
                for (ClientSession targetSession : sessionManager
                        .getSessions(recipientJID.getNode())) {
                    recipientFullJIDs.add(targetSession.getAddress());
                }
            }
            else {
                recipientFullJIDs.add(recipientJID);
            }
            for (JID jid : recipientFullJIDs) {
                presencePacket.setTo(jid);
                try {
                    deliverer.deliver(presencePacket);
                }
                catch (Exception e) {
                    Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
                }
            }
        }
    }
}
 
Example 6
Source File: RosterManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void sendSubscribeRequest(JID sender, JID recipient, boolean isSubscribe) {
    Presence presence = new Presence();
    presence.setFrom(sender);
    presence.setTo(recipient);
    if (isSubscribe) {
        presence.setType(Presence.Type.subscribe);
    }
    else {
        presence.setType(Presence.Type.unsubscribe);
    }
    routingTable.routePacket(recipient, presence, false);
}
 
Example 7
Source File: PresenceUpdateHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public Presence createSubscribePresence(JID senderAddress, JID targetJID, boolean isSubscribe) {
    Presence presence = new Presence();
    presence.setFrom(senderAddress);
    presence.setTo(targetJID);
    if (isSubscribe) {
        presence.setType(Presence.Type.subscribe);
    }
    else {
        presence.setType(Presence.Type.unsubscribe);
    }
    return presence;
}
 
Example 8
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Evaluate the given JID to determine what the appropriate affiliation should be
 * after a change has been made. Each affected user will be granted the highest
 * affiliation they now possess, either explicitly or implicitly via membership
 * in one or more groups. If the JID is a user, the effective affiliation is
 * applied to each presence corresponding to that user. If the given JID is a group,
 * each user in the group is evaluated to determine what their new affiliations will
 * be. The returned presence updates will be broadcast to the occupants of the room.
 * 
 * @param senderRole Typically the room itself, or an owner/admin
 * @param affiliationJID The JID for the user or group that has been changed
 * @param reason An optional reason to explain why a user was kicked from the room
 * @return List of presence updates to be delivered to the room's occupants
 */
private List<Presence> applyAffiliationChange(MUCRole senderRole, final JID affiliationJID, String reason) {
    
    // Update the presence(s) for the new affiliation and inform all occupants
    List<JID> affectedOccupants = new ArrayList<>();
    
    // first, determine which actual (user) JIDs are affected by the affiliation change
    if (GroupJID.isGroup(affiliationJID)) {
        try {
            Group group = GroupManager.getInstance().getGroup(affiliationJID);
            // check each occupant to see if they are in the group that was changed
            // if so, calculate a new affiliation (if any) for the occupant(s)
            for (JID groupMember : group.getAll()) {
                if (occupantsByBareJID.containsKey(groupMember)) {
                    affectedOccupants.add(groupMember);
                }
            }
        } catch (GroupNotFoundException gnfe) {
            Log.error("Error updating group presences for " + affiliationJID , gnfe);
        }
    } else {
        if (occupantsByBareJID.containsKey(affiliationJID)) {
            affectedOccupants.add(affiliationJID);
        }
    }
    
    // now update each of the affected occupants with a new role/affiliation
    MUCRole.Role newRole;
    MUCRole.Affiliation newAffiliation;
    List<Presence> updatedPresences = new ArrayList<>();
    // new role/affiliation may be granted via group membership
    for (JID occupantJID : affectedOccupants) {
        Log.info("Applying affiliation change for " + occupantJID);
        boolean kickMember = false, isOutcast = false;
        if (owners.includes(occupantJID)) {
            newRole = MUCRole.Role.moderator;
            newAffiliation = MUCRole.Affiliation.owner;
        }
        else if (admins.includes(occupantJID)) {
            newRole = MUCRole.Role.moderator;
            newAffiliation = MUCRole.Affiliation.admin;
        }
        // outcast trumps member when an affiliation is changed
        else if (outcasts.includes(occupantJID)) {
            newAffiliation = MUCRole.Affiliation.outcast;
            newRole = MUCRole.Role.none;
            kickMember = true;
            isOutcast = true;
        }
        else if (members.includesKey(occupantJID)) {
            newRole = MUCRole.Role.participant;
            newAffiliation = MUCRole.Affiliation.member;
        }
        else if (isMembersOnly()) {
            newRole = MUCRole.Role.none;
            newAffiliation = MUCRole.Affiliation.none;
            kickMember = true;
        }
        else {
            newRole = isModerated() ? MUCRole.Role.visitor : MUCRole.Role.participant;
            newAffiliation = MUCRole.Affiliation.none;
        }
        Log.info("New affiliation: " + newAffiliation);
        try {
            List<Presence> thisOccupant = changeOccupantAffiliation(senderRole, occupantJID, newAffiliation, newRole);
            if (kickMember) {
                // If the room is members-only, remove the user from the room including a status
                // code of 321 to indicate that the user was removed because of an affiliation change
                // a status code of 301 indicates the user was removed as an outcast
                for (Presence presence : thisOccupant) {
                    presence.setType(Presence.Type.unavailable);
                    presence.setStatus(null);
                    Element x = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
                    if (reason != null && reason.trim().length() > 0) {
                        x.element("item").addElement("reason").setText(reason);
                    }
                    x.addElement("status").addAttribute("code", isOutcast ? "301" : "321");
                    kickPresence(presence, senderRole.getUserAddress(), senderRole.getNickname());
                }
            }
            updatedPresences.addAll(thisOccupant);
        } catch (NotAllowedException e) {
            Log.error("Error updating presences for " + occupantJID, e);
        }
    }
    return updatedPresences;
}
 
Example 9
Source File: SessionManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Removes a session.
 *
 * @param session the session or null when session is derived from fullJID.
 * @param fullJID the address of the session.
 * @param anonymous true if the authenticated user is anonymous.
 * @param forceUnavailable true if an unavailable presence must be created and routed.
 * @return true if the requested session was successfully removed.
 */
public boolean removeSession(ClientSession session, JID fullJID, boolean anonymous, boolean forceUnavailable) {
    // Do nothing if server is shutting down. Note: When the server
    // is shutting down the serverName will be null.
    if (serverName == null) {
        return false;
    }

    if (session == null) {
        session = getSession(fullJID);
    }

    // Remove route to the removed session (anonymous or not)
    boolean removed = routingTable.removeClientRoute(fullJID);

    if (removed) {
        // Fire session event.
        if (anonymous) {
            SessionEventDispatcher
                    .dispatchEvent(session, SessionEventDispatcher.EventType.anonymous_session_destroyed);
        }
        else {
            SessionEventDispatcher.dispatchEvent(session, SessionEventDispatcher.EventType.session_destroyed);

        }
    }

    // Remove the session from the pre-Authenticated sessions list (if present)
    boolean preauth_removed =
            localSessionManager.getPreAuthenticatedSessions().remove(fullJID.getResource()) != null;
    // If the user is still available then send an unavailable presence
    if (forceUnavailable || session.getPresence().isAvailable()) {
        Presence offline = new Presence();
        offline.setFrom(fullJID);
        offline.setTo(new JID(null, serverName, null, true));
        offline.setType(Presence.Type.unavailable);
        router.route(offline);
    }

    // Stop tracking information about the session and share it with other cluster nodes.
    // Note that, unlike other caches, this cache is populated only when clustering is enabled.
    sessionInfoCache.remove(fullJID.toString());

    if (removed || preauth_removed) {
        // Decrement the counter of user sessions
        connectionsCounter.decrementAndGet();
        return true;
    }
    return false;
}
 
Example 10
Source File: SessionManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Close detached client sessions that haven't seen activity in more than
 * 30 minutes by default.
 */
@Override
public void run() {
    int idleTime = getSessionDetachTime();
    if (idleTime == -1) {
        return;
    }
    final long deadline = System.currentTimeMillis() - idleTime;
    for (LocalSession session : detachedSessions.values()) {
        try {
            Log.trace("Iterating over detached session '{}' ({}) to determine if it needs to be cleaned up.", session.getAddress(), session.getStreamID());
            if (session.getLastActiveDate().getTime() < deadline) {
                Log.debug("Detached session '{}' ({}) has been detached for longer than {} and will be cleaned up.", session.getAddress(), session.getStreamID(), Duration.ofMillis(idleTime));
                removeDetached(session);
                LocalClientSession clientSession = (LocalClientSession)session;

                // OF-1923: Only close the session if it has not been replaced by another session (if the session
                // has been replaced, then the condition below will compare to distinct instances). This *should* not
                // occur (but has been observed, prior to the fix of OF-1923). This check is left in as a safeguard.
                if (session == routingTable.getClientRoute(session.getAddress())) {
                    try {
                        if ((clientSession.getPresence().isAvailable() || !clientSession.wasAvailable()) &&
                            routingTable.hasClientRoute(session.getAddress())) {
                            // Send an unavailable presence to the user's subscribers
                            // Note: This gives us a chance to send an unavailable presence to the
                            // entities that the user sent directed presences
                            Presence presence = new Presence();
                            presence.setType(Presence.Type.unavailable);
                            presence.setFrom(session.getAddress());
                            router.route(presence);
                        }

                        session.getStreamManager().onClose(router, serverAddress);
                    } finally {
                        // Remove the session
                        removeSession(clientSession);
                    }
                } else {
                    Log.warn("Not removing detached session '{}' ({}) that appears to have been replaced by another session.", session.getAddress(), session.getStreamID());
                }
            } else {
                Log.trace("Detached session '{}' ({}) has been detached for {}, which is not longer than the configured maximum of {}. It will not (yet) be cleaned up.", session.getAddress(), session.getStreamID(), Duration.ofMillis(System.currentTimeMillis()-session.getLastActiveDate().getTime()), Duration.ofMillis(idleTime));
            }
        }
        catch (Throwable e) {
            Log.error("An exception occurred while trying processing detached session '{}' ({}).", session.getAddress(), session.getStreamID(), e);
        }
    }
}