Java Code Examples for org.xmpp.packet.JID#equals()

The following examples show how to use org.xmpp.packet.JID#equals() . 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: Roster.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * A shared group of the user has been renamed. Update the existing roster items with the new
 * name of the shared group and make a roster push for all the available resources.
 *
 * @param users group users of the renamed group.
 */
void shareGroupRenamed(Collection<JID> users) {
    JID userJID = getUserJID();
    for (JID user : users) {
        if (userJID.equals(user)) {
            continue;
        }
        RosterItem item;
        try {
            // Get the RosterItem for the *local* user to add
            item = getRosterItem(user);
            // Broadcast to all the user resources of the updated roster item
            broadcast(item, true);
        } catch (UserNotFoundException e) {
            // Do nothing since the contact does not exist in the user's roster. (strange case!)
            // Log.warn( "Unexpected error while broadcasting shared group rename for user '{}'!", user, e);
        }
    }
}
 
Example 4
Source File: PresenceAccess.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canSubscribe(Node node, JID owner, JID subscriber) {
    // Let node owners and sysadmins always subcribe to the node
    if (node.isAdmin(owner)) {
        return true;
    }
    XMPPServer server = XMPPServer.getInstance();
    for (JID nodeOwner : node.getOwners()) {
        // Give access to the owner of the roster :)
        if (nodeOwner.equals(owner)) {
            return true;
        }
        // Check that the node owner is a local user
        if (server.isLocal(nodeOwner)) {
            try {
                Roster roster = server.getRosterManager().getRoster(nodeOwner.getNode());
                RosterItem item = roster.getRosterItem(owner);
                // Check that the subscriber is subscribe to the node owner's presence
                return item != null && (RosterItem.SUB_BOTH == item.getSubStatus() ||
                        RosterItem.SUB_FROM == item.getSubStatus());
            }
            catch (UserNotFoundException e) {
                // Do nothing
            }
        }
        else {
            // Owner of the node is a remote user. This should never happen.
            Log.warn("Node with access model Presence has a remote user as owner: {}",node.getUniqueIdentifier());
        }
    }
    return false;
}
 
Example 5
Source File: RosterAccess.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canSubscribe(Node node, JID owner, JID subscriber) {
    // Let node owners and sysadmins always subscribe to the node
    if (node.isAdmin(owner)) {
        return true;
    }
    for (JID nodeOwner : node.getOwners()) {
        if (nodeOwner.equals(owner)) {
            return true;
        }
    }
    // Check that the subscriber is a local user
    XMPPServer server = XMPPServer.getInstance();
    if (server.isLocal(owner)) {
        GroupManager gMgr = GroupManager.getInstance();
        Collection<String> nodeGroups = node.getRosterGroupsAllowed();
        for (String groupName : nodeGroups) {
            try {
                Group group = gMgr.getGroup(groupName);
                // access allowed if the node group is visible to the subscriber
                if (server.getRosterManager().isGroupVisible(group, owner)) {
                    return true;
                }
            } catch (GroupNotFoundException gnfe){ 
                // ignore
            }
        }
    }
    else {
        // Subscriber is a remote user. This should never happen.
        Log.warn("Node with access model Roster has a remote user as subscriber: {}", node.getUniqueIdentifier());
    }
    return false;
}
 
Example 6
Source File: Node.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the list of subscriptions owned by the specified user. The subscription owner
 * may have more than one subscription based on {@link #isMultipleSubscriptionsEnabled()}.
 * Each subscription may have a different subscription JID if the owner wants to receive
 * notifications in different resources (or even JIDs).
 *
 * @param owner the owner of the subscriptions.
 * @return the list of subscriptions owned by the specified user.
 */
public Collection<NodeSubscription> getSubscriptions(JID owner) {
    Collection<NodeSubscription> subscriptions = new ArrayList<>();
    for (NodeSubscription subscription : subscriptionsByID.values()) {
        if (owner.equals(subscription.getOwner())) {
            subscriptions.add(subscription);
        }
    }
    return subscriptions;
}
 
Example 7
Source File: Node.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link NodeAffiliate} of the specified {@link JID} or {@code null}
 * if none was found. Users that have a subscription with the node will ALWAYS
 * have an affiliation even if the affiliation is of type {@code none}.
 *
 * @param jid the JID of the user to look his affiliation with this node.
 * @return the NodeAffiliate of the specified JID or {@code null} if none was found.
 */
public NodeAffiliate getAffiliate(JID jid) {
    for (NodeAffiliate affiliate : affiliates) {
        if (jid.equals(affiliate.getJID())) {
            return affiliate;
        }
    }
    return null;
}
 
Example 8
Source File: SessionManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Change the priority of a session, that was already available, associated with the sender.
 *
 * @param session   The session whose presence priority has been modified
 * @param oldPriority The old priority for the session
 */
public void changePriority(LocalClientSession session, int oldPriority) {
    if (session.getAuthToken().isAnonymous()) {
        // Do nothing if the session belongs to an anonymous user
        return;
    }
    int newPriority = session.getPresence().getPriority();
    if (newPriority < 0 || oldPriority >= 0) {
        // Do nothing if new presence priority is not positive and old presence negative
        return;
    }

    // Check presence's priority of other available resources
    JID searchJID = session.getAddress().asBareJID();
    for (JID address : routingTable.getRoutes(searchJID, null)) {
        if (address.equals(session.getAddress())) {
            continue;
        }
        ClientSession otherSession = routingTable.getClientRoute(address);
        if (otherSession.getPresence().getPriority() >= 0) {
            return;
        }
    }

    // User sessions had negative presence before this change so deliver messages
    if (!session.isAnonymousUser() && session.canFloodOfflineMessages()) {
        OfflineMessageStore messageStore = server.getOfflineMessageStore();
        Collection<OfflineMessage> messages = messageStore.getMessages(session.getAuthToken().getUsername(), true);
        for (Message message : messages) {
            session.process(message);
        }
    }
}
 
Example 9
Source File: Roster.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the list of users that belong ONLY to a shared group of this user. If the contact
 * belongs to the personal roster and a shared group then it wont' be included in the answer.
 *
 * @param sharedGroups the shared groups of this user.
 * @return the list of users that belong ONLY to a shared group of this user.
 */
private Map<JID, List<Group>> getSharedUsers(Collection<Group> sharedGroups) {
    final RosterManager rosterManager = XMPPServer.getInstance().getRosterManager();
    // Get the users to process from the shared groups. Users that belong to different groups
    // will have one entry in the map associated with all the groups
    Map<JID, List<Group>> sharedGroupUsers = new HashMap<>();
    for (Group group : sharedGroups) {
        // Get all the users that should be in this roster
        Collection<JID> users = rosterManager.getSharedUsersForRoster(group, this);
        // Add the users of the group to the general list of users to process
        JID userJID = getUserJID();
        for (JID jid : users) {
            // Add the user to the answer if the user doesn't belong to the personal roster
            // (since we have already added the user to the answer)
            boolean isRosterItem = rosterItems.containsKey(jid.toBareJID());
            if (!isRosterItem && !userJID.equals(jid)) {
                List<Group> groups = sharedGroupUsers.get(jid);
                if (groups == null) {
                    groups = new ArrayList<>();
                    sharedGroupUsers.put(jid, groups);
                }
                groups.add(group);
            }
        }
    }
    return sharedGroupUsers;
}
 
Example 10
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 4 votes vote down vote up
public void occupantAdded(OccupantAddedEvent event) {
    // Create a proxy for the occupant that joined the room from another cluster node
    RemoteMUCRole joinRole = new RemoteMUCRole(mucService, event);
    JID bareJID = event.getUserAddress().asBareJID();
    String nickname = event.getNickname();
    lock.writeLock().lock();
    try {
        List<MUCRole> occupants = occupantsByNickname.computeIfAbsent(nickname.toLowerCase(), nick -> new CopyOnWriteArrayList<>());
        // Do not add new occupant with one with same nickname already exists
        // sanity check; make sure the nickname is owned by the same JID
        if (occupants.size() > 0) {
            JID existingJID = occupants.get(0).getUserAddress().asBareJID();
            if (!bareJID.equals(existingJID)) {
                Log.warn(MessageFormat.format("Conflict detected; {0} requested nickname '{1}'; already being used by {2}", bareJID, nickname, existingJID));
                return;
            }
        }
        // Add the new user as an occupant of this room
        occupants.add(joinRole);
        // Update the tables of occupants based on the bare and full JID
        occupantsByBareJID.computeIfAbsent(bareJID, jid->new CopyOnWriteArrayList<>()).add(joinRole);
        occupantsByFullJID.put(event.getUserAddress(), joinRole);

        // Update the date when the last occupant left the room
        setEmptyDate(null);
        if (event.isOriginator()) {
            // Fire event that occupant joined the room
            MUCEventDispatcher.occupantJoined(getRole().getRoleAddress(), event.getUserAddress(), joinRole.getNickname());
        }
    }
    finally {
        lock.writeLock().unlock();
    }
    // Check if we need to send presences of the new occupant to occupants hosted by this JVM
    if (event.isSendPresence()) {
        for (MUCRole occupant : occupantsByFullJID.values()) {
            if (occupant.isLocal()) {
                occupant.send(event.getPresence().createCopy());
            }
        }
    }
}
 
Example 11
Source File: RoutingTableImpl.java    From Openfire with Apache License 2.0 4 votes vote down vote up
private void ccMessage(JID originalRecipient, Message message) {
    // We don't want to CC a message that is already a CC
    final Element receivedElement = message.getChildElement(Received.NAME, Received.NAMESPACE);
    final boolean isCC = receivedElement != null;
    if (message.getType() == Message.Type.chat && !isCC) {
        List<JID> routes = getRoutes(originalRecipient.asBareJID(), null);
        for (JID ccJid : routes) {
            // The receiving server MUST NOT send a forwarded copy to the full JID the original <message/> stanza was addressed to, as that recipient receives the original <message/> stanza.
            if (!ccJid.equals(originalRecipient)) {
                ClientSession clientSession = getClientRoute(ccJid);
                if (clientSession.isMessageCarbonsEnabled()) {
                    Message carbon = new Message();
                    // The wrapping message SHOULD maintain the same 'type' attribute value;
                    carbon.setType(message.getType());
                    // the 'from' attribute MUST be the Carbons-enabled user's bare JID
                    carbon.setFrom(ccJid.asBareJID());
                    // and the 'to' attribute MUST be the full JID of the resource receiving the copy
                    carbon.setTo(ccJid);
                    // The content of the wrapping message MUST contain a <received/> element qualified by the namespace "urn:xmpp:carbons:2", which itself contains a <forwarded/> element qualified by the namespace "urn:xmpp:forward:0" that contains the original <message/>.
                    carbon.addExtension(new Received(new Forwarded(message)));

                    try {
                        final RoutableChannelHandler localRoute = localRoutingTable.getRoute(ccJid);
                        if (localRoute != null) {
                            // This session is on a local cluster node
                            localRoute.process(carbon);
                        } else {
                            // The session is not on a local cluster node, so try a remote
                            final ClientRoute remoteRoute = getClientRouteForLocalUser(ccJid);
                            if (remotePacketRouter != null // If we're in a cluster
                                && remoteRoute != null // and we've found a route to the other node
                                && !remoteRoute.getNodeID().equals(XMPPServer.getInstance().getNodeID())) { // and it really is a remote node
                                // Try and route the packet to the remote session
                                remotePacketRouter.routePacket(remoteRoute.getNodeID().toByteArray(), ccJid, carbon);
                            } else {
                                Log.warn("Unable to find route to CC remote user {}", ccJid);
                            }
                        }
                    } catch (UnauthorizedException e) {
                        Log.error("Unable to route packet {}", message, e);
                    }
                }
            }
        }
    }
}
 
Example 12
Source File: RosterManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Notification that a Group user has been added. Update the group users' roster accordingly.
 *
 * @param group the group where the user was added.
 * @param users the users to update their rosters
 * @param addedUser the username of the user that has been added to the group.
 */
private void groupUserAdded(Group group, Collection<JID> users, JID addedUser) {
    // Get the roster of the added user.
    Roster addedUserRoster = null;
    if (server.isLocal(addedUser)) {
        addedUserRoster = rosterCache.get(addedUser.getNode());
    }

    // Iterate on all the affected users and update their rosters
    for (JID userToUpdate : users) {
        if (!addedUser.equals(userToUpdate)) {
            // Get the roster to update
            Roster roster = null;
            if (server.isLocal(userToUpdate)) {
                // Check that the user exists, if not then continue with the next user
                try {
                    UserManager.getInstance().getUser(userToUpdate.getNode());
                }
                catch (UserNotFoundException e) {
                    continue;
                }
                roster = rosterCache.get(userToUpdate.getNode());
            }
            // Only update rosters in memory
            if (roster != null) {
                roster.addSharedUser(group, addedUser);
            }
            // Check if the roster is still not in memory
            if (addedUserRoster == null && server.isLocal(addedUser)) {
                addedUserRoster =
                        rosterCache.get(addedUser.getNode());
            }
            // Update the roster of the newly added group user.
            if (addedUserRoster != null) {
                Collection<Group> groups = GroupManager.getInstance().getGroups(userToUpdate);
                addedUserRoster.addSharedUser(userToUpdate, groups, group);
            }
            if (!server.isLocal(addedUser)) {
                // Susbcribe to the presence of the remote user. This is only necessary for
                // remote users and may only work with remote users that **automatically**
                // accept presence subscription requests
                sendSubscribeRequest(userToUpdate, addedUser, true);
            }
            if (!server.isLocal(userToUpdate)) {
                // Susbcribe to the presence of the remote user. This is only necessary for
                // remote users and may only work with remote users that **automatically**
                // accept presence subscription requests
                sendSubscribeRequest(addedUser, userToUpdate, true);
            }
        }
    }
}
 
Example 13
Source File: NodeSubscription.java    From Openfire with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if the specified user is allowed to modify or cancel the subscription. Users
 * that are allowed to modify/cancel the subscription are: the entity that is recieving the
 * notifications, the owner of the subscriptions or sysadmins of the pubsub service.
 *
 * @param user the user that is trying to cancel the subscription.
 * @return true if the specified user is allowed to modify or cancel the subscription.
 */
boolean canModify(JID user) {
    return user.equals(getJID()) || user.toBareJID().equals(getOwner().toBareJID()) || node.getService().isServiceAdmin(user);
}