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

The following examples show how to use org.xmpp.packet.Presence#setTo() . 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
/**
 * Sends the presences of other connected resources to the resource that just connected.
 *
 * @param session the newly created session.
 */
private void broadcastPresenceOfOtherResource(LocalClientSession session) {
    if (!SessionManager.isOtherResourcePresenceEnabled()) {
        return;
    }
    Presence presence;
    // Get list of sessions of the same user
    JID searchJID = new JID(session.getAddress().getNode(), session.getAddress().getDomain(), null);
    List<JID> addresses = routingTable.getRoutes(searchJID, null);
    for (JID address : addresses) {
        if (address.equals(session.getAddress())) {
            continue;
        }
        // Send the presence of an existing session to the session that has just changed
        // the presence
        ClientSession userSession = routingTable.getClientRoute(address);
        presence = userSession.getPresence().createCopy();
        presence.setTo(session.getAddress());
        session.process(presence);
    }
}
 
Example 2
Source File: SessionManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * 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).
 *
 * @param originatingResource the full JID of the session that sent the presence update.
 * @param presence the presence.
 */
public void broadcastPresenceToResources( JID originatingResource, Presence presence) {
    // RFC 6121 4.4.2 says we always send to the originating resource.
    // Also RFC 6121 4.2.2 for updates.
    presence.setTo(originatingResource);
    routingTable.routePacket(originatingResource, presence, false);
    if (!SessionManager.isOtherResourcePresenceEnabled()) {
        return;
    }
    // Get list of sessions of the same user
    JID searchJID = new JID(originatingResource.getNode(), originatingResource.getDomain(), null);
    List<JID> addresses = routingTable.getRoutes(searchJID, null);
    for (JID address : addresses) {
        if (!originatingResource.equals(address)) {
            // Send the presence of the session whose presence has changed to
            // this user's other session(s)
            presence.setTo(address);
            routingTable.routePacket(address, presence, false);
        }
    }
}
 
Example 3
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 4
Source File: PresenceUpdateHandler.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Handle presence updates that affect roster subscriptions.
 *
 * @param presence The presence presence to handle
 * @throws PacketException if the packet is null or the packet could not be routed.
 */
public void process(Presence presence) throws PacketException {
    try {
        process((Packet)presence);
    }
    catch (UnauthorizedException e) {
        try {
            LocalSession session = (LocalSession) sessionManager.getSession(presence.getFrom());
            presence = presence.createCopy();
            if (session != null) {
                presence.setFrom(new JID(null, session.getServerName(), null, true));
                presence.setTo(session.getAddress());
            }
            else {
                JID sender = presence.getFrom();
                presence.setFrom(presence.getTo());
                presence.setTo(sender);
            }
            presence.setError(PacketError.Condition.not_authorized);
            deliverer.deliver(presence);
        }
        catch (Exception err) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), err);
        }
    }
}
 
Example 5
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Broadcasts the specified presence to all room occupants. If the presence belongs to a
 * user whose role cannot be broadcast then the presence will only be sent to the presence's
 * user. On the other hand, the JID of the user that sent the presence won't be included if the
 * room is semi-anon and the target occupant is not a moderator.
 *
 * @param presence the presence to broadcast.
 * @param isJoinPresence If the presence is sent in the context of joining the room.
 * @param sender The role of the entity that initiated the presence broadcast
 */
private void broadcastPresence(Presence presence, boolean isJoinPresence, @Nonnull MUCRole sender) {
    if (presence == null) {
        return;
    }

    // Some clients send a presence update to the room, rather than to their own nickname.
    if ( JiveGlobals.getBooleanProperty("xmpp.muc.presence.overwrite-to-room", true) && presence.getTo() != null && presence.getTo().getResource() == null && sender.getRoleAddress() != null) {
        presence.setTo( sender.getRoleAddress() );
    }

    if (!shouldBroadcastPresence(presence)) {
        // Just send the presence to the sender of the presence
        sender.send(presence);
        return;
    }

    // If FMUC is active, propagate the presence through FMUC first. Note that when a master-slave mode is active,
    // we need to wait for an echo back, before the message can be broadcasted locally. The 'propagate' method will
    // return a CompletableFuture object that is completed as soon as processing can continue.
    fmucHandler.propagate( presence, sender )
        .thenRunAsync( () -> {
            // Broadcast presence to occupants hosted by other cluster nodes
            BroadcastPresenceRequest request = new BroadcastPresenceRequest(this, sender, presence, isJoinPresence);
            CacheFactory.doClusterTask(request);

            // Broadcast presence to occupants connected to this JVM
            request = new BroadcastPresenceRequest(this, sender, presence, isJoinPresence);
            request.setOriginator(true);
            request.run();
        }
    );
}
 
Example 6
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 7
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 8
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 9
Source File: PresenceUpdateHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an unavailable presence to the entities that sent a directed (available) presence
 * to other entities.
 *
 * @param update the unavailable presence sent by the user.
 */
private void broadcastUnavailableForDirectedPresences(Presence update) {
    JID from = update.getFrom();
    if (from == null) {
        return;
    }
    if (localServer.isLocal(from)) {
        // Remove the registry of directed presences of this user
        Collection<DirectedPresence> directedPresences = null;
        
        Lock lock = CacheFactory.getLock(from.toString(), directedPresencesCache);
        try {
            lock.lock();
            directedPresences = directedPresencesCache.remove(from.toString());
        } finally {
            lock.unlock();
        }
        
        if (directedPresences != null) {
            // Iterate over all the entities that the user sent a directed presence
            for (DirectedPresence directedPresence : directedPresences) {
                for (String receiver : directedPresence.getReceivers()) {
                    Presence presence = update.createCopy();
                    presence.setTo(receiver);
                    localServer.getPresenceRouter().route(presence);
                }
            }
            localDirectedPresences.remove(from.toString());
        }
    }
}
 
Example 10
Source File: ComponentStanzaHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
protected void processPresence(Presence packet) throws UnauthorizedException {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        Presence reply = new Presence();
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    super.processPresence(packet);
}
 
Example 11
Source File: InternalComponentManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void checkPresences() {
    for (JID prober : presenceMap.keySet()) {
        JID probee = presenceMap.get(prober);

        if (routingTable.hasComponentRoute(probee)) {
            Presence presence = new Presence();
            presence.setFrom(prober);
            presence.setTo(probee);
            routingTable.routePacket(probee, presence, false);

            // No reason to hold onto prober reference.
            presenceMap.remove(prober);
        }
    }
}
 
Example 12
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 13
Source File: PresenceUpdateHandler.java    From Openfire with Apache License 2.0 4 votes vote down vote up
private void process(Presence presence, ClientSession session) throws UnauthorizedException, PacketException {
    try {
        Presence.Type type = presence.getType();
        // Available
        if (type == null) {
            if (session != null && session.getStatus() == Session.STATUS_CLOSED) {
                Log.warn("Rejected available presence: " + presence + " - " + session);
                return;
            }

            if (session != null) {
                session.setPresence(presence);
            }

            broadcastUpdate(presence.createCopy());

            if (session != null && !session.isInitialized()) {
                initSession(session);
                session.setInitialized(true);
            }

            // Notify the presence manager that the user is now available. The manager may
            // remove the last presence status sent by the user when he went offline.
            presenceManager.userAvailable(presence);
        }
        else if (Presence.Type.unavailable == type) {
            if (session != null) {
                session.setPresence(presence);
            }
            broadcastUpdate(presence.createCopy());
            broadcastUnavailableForDirectedPresences(presence);
            // Notify the presence manager that the user is now unavailable. The manager may
            // save the last presence status sent by the user and keep track when the user
            // went offline.
            presenceManager.userUnavailable(presence);
        }
        else {
            presence = presence.createCopy();
            if (session != null) {
                presence.setFrom(new JID(null, session.getServerName(), null, true));
                presence.setTo(session.getAddress());
            }
            else {
                JID sender = presence.getFrom();
                presence.setFrom(presence.getTo());
                presence.setTo(sender);
            }
            presence.setError(PacketError.Condition.bad_request);
            deliverer.deliver(presence);
        }

    }
    catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error") + ". Triggered by packet: " + presence, e);
    }
}