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

The following examples show how to use org.xmpp.packet.Presence#setFrom() . These examples are extracted from open source projects. 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 Project: Openfire   File: SessionManager.java    License: 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 Project: Openfire   File: PresenceUpdateHandler.java    License: 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 3
Source Project: Openfire   File: IQMUCvCardHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void sendVCardUpdateNotification( final MUCRoom room, String hash )
{
    Log.debug("Sending vcard-temp update notification to all occupants of room {}, using hash {}", room.getName(), hash);
    final Presence notification = new Presence();
    notification.setFrom(room.getJID());
    final Element x = notification.addChildElement("x", "vcard-temp:x:update");
    final Element photo = x.addElement("photo");
    photo.setText(hash);

    for ( final MUCRole occupant : room.getOccupants() )
    {
        occupant.send(notification);
    }
}
 
Example 4
Source Project: Openfire   File: LocalMUCRoom.java    License: 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 5
Source Project: Openfire   File: SessionManager.java    License: 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 6
Source Project: Openfire   File: PresenceManagerImpl.java    License: 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 Project: Openfire   File: RosterManager.java    License: 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 Project: Openfire   File: PresenceUpdateHandler.java    License: 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 Project: Openfire   File: ComponentStanzaHandler.java    License: 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 10
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 11
Source Project: Openfire   File: LocalMUCRoom.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public MUCRole joinRoom( @Nonnull String nickname,
                         @Nullable String password,
                         @Nullable HistoryRequest historyRequest,
                         @Nonnull LocalMUCUser user,
                         @Nonnull Presence presence )
    throws UnauthorizedException, UserAlreadyExistsException, RoomLockedException, ForbiddenException,
        RegistrationRequiredException, ConflictException, ServiceUnavailableException, NotAcceptableException
{
    Log.debug( "User '{}' attempts to join room '{}' using nickname '{}'.", user.getAddress(), this.getJID(), nickname );
    MUCRole joinRole;
    boolean clientOnlyJoin; // A "client only join" here is one where the client is already joined, but has re-joined.

    lock.writeLock().lock();
    try {
        // Determine the corresponding role based on the user's affiliation
        final JID bareJID = user.getAddress().asBareJID();
        MUCRole.Role role = getRole( bareJID );
        MUCRole.Affiliation affiliation = getAffiliation( bareJID );
        if (affiliation != MUCRole.Affiliation.owner && mucService.isSysadmin(bareJID)) {
            // The user is a system administrator of the MUC service. Treat him as an owner although he won't appear in the list of owners
            Log.debug( "User '{}' is a sysadmin. Treat as owner.", user.getAddress());
            role = MUCRole.Role.moderator;
            affiliation = MUCRole.Affiliation.owner;
        }
        Log.debug( "User '{}' role and affiliation in room '{} are determined to be: {}, {}", user.getAddress(), this.getJID(), role, affiliation );

        // Verify that the attempt meets all preconditions for joining the room.
        checkJoinRoomPreconditions( user, nickname, affiliation, password, presence );

        // Is this client already joined with this nickname?
        clientOnlyJoin = alreadyJoinedWithThisNick( user, nickname );

        // TODO up to this point, room state has not been modified, even though a write-lock has been acquired. Can we optimize concurrency by locking with only a read-lock up until here?
        if (!clientOnlyJoin)
        {
            Log.debug( "Adding user '{}' as an occupant of room '{}' using nickname '{}'.", user.getAddress(), this.getJID(), nickname );

            // Create a new role for this user in this room.
            joinRole = new LocalMUCRole(mucService, this, nickname, role, affiliation, user, presence, router);

            // See if we need to join a federated room. Note that this can be blocking!
            final Future<?> join = fmucHandler.join(joinRole);
            try
            {
                // FIXME make this properly asynchronous, instead of blocking the thread!
                join.get(5, TimeUnit.MINUTES);
            }
            catch ( InterruptedException | ExecutionException | TimeoutException e )
            {
                Log.error( "An exception occurred while processing FMUC join for user '{}' in room '{}'", joinRole.getUserAddress(), joinRole.getChatRoom(), e);
            }

            addOccupantRole( joinRole );

        } else {
            // Grab the existing one.
            Log.debug( "Skip adding user '{}' as an occupant of  room '{}' using nickname '{}', as it already is. Updating occupancy with its latest presence information.", user.getAddress(), this.getJID(), nickname );
            joinRole = occupantsByFullJID.get(user.getAddress());
            joinRole.setPresence( presence ); // OF-1581: Use latest presence information.
        }
    }
    finally {
        lock.writeLock().unlock();
    }

    Log.trace( "Notify other cluster nodes that a new occupant ('{}') joined room '{}'", joinRole.getUserAddress(), joinRole.getChatRoom() );
    CacheFactory.doClusterTask(new OccupantAddedEvent(this, joinRole));

    // Exchange initial presence information between occupants of the room.
    sendInitialPresencesToNewOccupant( joinRole );
    sendInitialPresenceToExistingOccupants( joinRole );

    // If the room has just been created send the "room locked until configuration is confirmed" message.
    // It is assumed that the room is new based on the fact that it's locked and that it was locked when it was created.
    final boolean isRoomNew = isLocked() && creationDate.getTime() == lockedTime;
    if (!isRoomNew && isLocked()) {
        // TODO Verify if it's right that this check occurs only _after_ a join was deemed 'successful' and initial presences have been exchanged.
        // http://xmpp.org/extensions/xep-0045.html#enter-locked
        Log.debug( "User '{}' attempts to join room '{}' that is locked (pending configuration confirmation). Sending an error.", user.getAddress(), this.getJID() );
        final Presence presenceItemNotFound = new Presence(Presence.Type.error);
        presenceItemNotFound.setError(PacketError.Condition.item_not_found);
        presenceItemNotFound.setFrom(role.getRoleAddress());
        joinRole.send(presenceItemNotFound);
    }

    sendRoomHistoryAfterJoin( user, joinRole, historyRequest );
    sendRoomSubjectAfterJoin( user, joinRole );

    if (!clientOnlyJoin) {
        // Update the date when the last occupant left the room
        setEmptyDate(null);
        // Fire event that occupant joined the room
        MUCEventDispatcher.occupantJoined(getRole().getRoleAddress(), user.getAddress(), joinRole.getNickname());
    }
    return joinRole;
}
 
Example 12
Source Project: Openfire   File: LocalMUCRoom.java    License: Apache License 2.0 4 votes vote down vote up
public void destroyRoom(DestroyRoomRequest destroyRequest) {
    JID alternateJID = destroyRequest.getAlternateJID();
    String reason = destroyRequest.getReason();
    Collection<MUCRole> removedRoles = new CopyOnWriteArrayList<>();
    lock.writeLock().lock();
    try {
        boolean hasRemoteOccupants = false;
        // Remove each occupant
        for (MUCRole leaveRole : occupantsByFullJID.values()) {

            if (leaveRole != null) {
                // Add the removed occupant to the list of removed occupants. We are keeping a
                // list of removed occupants to process later outside of the lock.
                if (leaveRole.isLocal()) {
                    removedRoles.add(leaveRole);
                }
                else {
                    hasRemoteOccupants = true;
                }
                removeOccupantRole(leaveRole);

                if (  destroyRequest.isOriginator() ) {
                    // Fire event that occupant left the room
                    MUCEventDispatcher.occupantLeft(leaveRole.getRoleAddress(), leaveRole.getUserAddress(), leaveRole.getNickname());
                }
            }
        }
        endTime = System.currentTimeMillis();
        // Set that the room has been destroyed
        isDestroyed = true;
        if (destroyRequest.isOriginator()) {
            if (hasRemoteOccupants) {
                // Ask other cluster nodes to remove occupants since room is being destroyed
                CacheFactory.doClusterTask(new DestroyRoomRequest(this, alternateJID, reason));
            }
            // Removes the room from the list of rooms hosted in the service
            mucService.removeChatRoom(name);
        }
    }
    finally {
        lock.writeLock().unlock();
    }
    // Send an unavailable presence to each removed occupant
    for (MUCRole removedRole : removedRoles) {
        try {
            // Send a presence stanza of type "unavailable" to the occupant
            Presence presence = createPresence(Presence.Type.unavailable);
            presence.setFrom(removedRole.getRoleAddress());

            // A fragment containing the x-extension for room destruction.
            Element fragment = presence.addChildElement("x",
                    "http://jabber.org/protocol/muc#user");
            Element item = fragment.addElement("item");
            item.addAttribute("affiliation", "none");
            item.addAttribute("role", "none");
            if (alternateJID != null) {
                fragment.addElement("destroy").addAttribute("jid", alternateJID.toString());
            }
            if (reason != null && reason.length() > 0) {
                Element destroy = fragment.element("destroy");
                if (destroy == null) {
                    destroy = fragment.addElement("destroy");
                }
                destroy.addElement("reason").setText(reason);
            }
            removedRole.send(presence);
        }
        catch (Exception e) {
            Log.error(e.getMessage(), e);
        }
    }
    if (destroyRequest.isOriginator()) {
        // Remove the room from the DB if the room was persistent
        MUCPersistenceManager.deleteFromDB(this);
        // Fire event that the room has been destroyed
        MUCEventDispatcher.roomDestroyed(getRole().getRoleAddress());
    }
}
 
Example 13
Source Project: Openfire   File: SessionManager.java    License: 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 14
Source Project: Openfire   File: SessionManager.java    License: 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);
        }
    }
}
 
Example 15
Source Project: Openfire   File: PresenceUpdateHandler.java    License: 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);
    }
}
 
Example 16
Source Project: Openfire   File: ClientStanzaHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void processPresence(Presence packet) throws UnauthorizedException {
    // Overwrite the FROM attribute to avoid spoofing
    packet.setFrom(session.getAddress());
    super.processPresence(packet);
}