org.xmpp.packet.Presence Java Examples

The following examples show how to use org.xmpp.packet.Presence. 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: AuditorImpl.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void audit(Packet packet, Session session) {
    if (auditManager.isEnabled()) {
        if (packet instanceof Message) {
            if (auditManager.isAuditMessage()) {
                writePacket(packet, session);
            }
        }
        else if (packet instanceof Presence) {
            if (auditManager.isAuditPresence()) {
                writePacket(packet, session);
            }
        }
        else if (packet instanceof IQ) {
            if (auditManager.isAuditIQ()) {
                writePacket(packet, session);
            }
        }
    }
}
 
Example #2
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public List<Presence> setMembersOnly(boolean membersOnly) {
    List<Presence> presences = new CopyOnWriteArrayList<>();
    if (membersOnly && !this.membersOnly) {
        // If the room was not members-only and now it is, kick occupants that aren't member
        // of the room
        for (MUCRole occupant : occupantsByFullJID.values()) {
            if (occupant.getAffiliation().compareTo(MUCRole.Affiliation.member) > 0) {
                try {
                    presences.add(kickOccupant(occupant.getRoleAddress(), null, null,
                            LocaleUtils.getLocalizedString("muc.roomIsNowMembersOnly")));
                }
                catch (NotAllowedException e) {
                    Log.error(e.getMessage(), e);
                }
            }
        }
    }
    this.membersOnly = membersOnly;
    return presences;
}
 
Example #3
Source File: PacketRouterImpl.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Routes the given packet based on packet recipient and sender. The
 * router defers actual routing decisions to other classes.
 * <h2>Warning</h2>
 * Be careful to enforce concurrency DbC of concurrent by synchronizing
 * any accesses to class resources.
 *
 * @param packet The packet to route
 */
@Override
public void route(Packet packet) {
    if (packet instanceof Message) {
        route((Message)packet);
    }
    else if (packet instanceof Presence) {
        route((Presence)packet);
    }
    else if (packet instanceof IQ) {
        route((IQ)packet);
    }
    else {
        throw new IllegalArgumentException();
    }
}
 
Example #4
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public Presence addParticipant(JID jid, String reason, MUCRole senderRole)
        throws NotAllowedException, ForbiddenException {
    if (MUCRole.Role.moderator != senderRole.getRole()) {
        throw new ForbiddenException();
    }
    // Update the presence with the new role and inform all occupants
    Presence updatedPresence = changeOccupantRole(jid, MUCRole.Role.participant);
    if (updatedPresence != null) {
        Element frag = updatedPresence.getChildElement(
                "x", "http://jabber.org/protocol/muc#user");
        // Add the reason why the user was granted voice
        if (reason != null && reason.trim().length() > 0) {
            frag.element("item").addElement("reason").setText(reason);
        }
    }
    return updatedPresence;
}
 
Example #5
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 6 votes vote down vote up
public Presence updateOccupant(UpdateOccupantRequest updateRequest) throws NotAllowedException {
    Presence result = null;
    List <MUCRole> occupants = occupantsByNickname.get(updateRequest.getNickname().toLowerCase());
    if (occupants == null || occupants.size() == 0) {
        Log.debug("Failed to update information of local room occupant; nickname: " + updateRequest.getNickname());
    } else {
        for (MUCRole occupant : occupants) {
            if (updateRequest.isAffiliationChanged()) {
                occupant.setAffiliation(updateRequest.getAffiliation());
            }
            occupant.setRole(updateRequest.getRole());
            // Notify the the cluster nodes to update the occupant
            CacheFactory.doClusterTask(new UpdateOccupant(this, occupant));
            if (result == null) {
                result = occupant.getPresence();
            }
        }
    }
    return result;
}
 
Example #6
Source File: OccupantAddedEvent.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    super.readExternal(in);
    Element packetElement = (Element) ExternalizableUtil.getInstance().readSerializable(in);
    presence = new Presence(packetElement, true);
    role = ExternalizableUtil.getInstance().readInt(in);
    affiliation = ExternalizableUtil.getInstance().readInt(in);
    voiceOnly = ExternalizableUtil.getInstance().readBoolean(in);
    roleAddress = (JID) ExternalizableUtil.getInstance().readSerializable(in);
    userAddress = (JID) ExternalizableUtil.getInstance().readSerializable(in);
    if (ExternalizableUtil.getInstance().readBoolean(in)) {
        reportedFmucAddress = (JID) ExternalizableUtil.getInstance().readSerializable(in);
    } else {
        reportedFmucAddress = null;
    }
    nodeID = NodeID.getInstance(ExternalizableUtil.getInstance().readByteArray(in));
    sendPresence = ExternalizableUtil.getInstance().readBoolean(in);
}
 
Example #7
Source File: RoutingTableImpl.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the specified packet must only be route to available client sessions.
 *
 * @param packet the packet to route.
 * @param fromServer true if the packet was created by the server.
 * @return true if the specified packet must only be route to available client sessions.
 */
private boolean routeOnlyAvailable(Packet packet, boolean fromServer) {
    if (fromServer) {
        // Packets created by the server (no matter their FROM value) must always be delivered no
        // matter the available presence of the user
        return false;
    }
    boolean onlyAvailable = true;
    JID from = packet.getFrom();
    boolean hasSender = from != null;
    if (packet instanceof IQ) {
        onlyAvailable = hasSender && !(serverName.equals(from.getDomain()) && from.getResource() == null) &&
                !componentsCache.containsKey(from.getDomain());
    }
    else if (packet instanceof Message || packet instanceof Presence) {
        onlyAvailable = !hasSender ||
                (!serverName.equals(from.toString()) && !componentsCache.containsKey(from.getDomain()));
    }
    return onlyAvailable;
}
 
Example #8
Source File: PresenceManagerImpl.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void userAvailable(Presence presence) {
    // Delete the last unavailable presence of this user since the user is now
    // available. Only perform this operation if this is an available presence sent to
    // THE SERVER and the presence belongs to a local user.
    if (presence.getTo() == null && server.isLocal(presence.getFrom())) {
        String username = presence.getFrom().getNode();
        if (username == null || !userManager.isRegisteredUser(username)) {
            // Ignore anonymous users
            return;
        }

        // Optimization: only delete the unavailable presence information if this
        // is the first session created on the server.
        if (sessionManager.getSessionCount(username) > 1) {
            return;
        }

        deleteOfflinePresenceFromDB(username);

        // Remove data from cache.
        offlinePresenceCache.remove(username);
        lastActivityCache.remove(username);
    }
}
 
Example #9
Source File: LocalMUCRole.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void setRole(MUCRole.Role newRole) throws NotAllowedException {
    // Don't allow to change the role to an owner or admin unless the new role is moderator
    if (MUCRole.Affiliation.owner == affiliation || MUCRole.Affiliation.admin == affiliation) {
        if (MUCRole.Role.moderator != newRole) {
            throw new NotAllowedException();
        }
    }
    // A moderator cannot be kicked from a room unless there has also been an affiliation change
    if (MUCRole.Role.moderator == role && MUCRole.Role.none == newRole && MUCRole.Affiliation.none != affiliation) {
        throw new NotAllowedException();
    }
    // TODO A moderator MUST NOT be able to revoke voice from a user whose affiliation is at or
    // TODO above the moderator's level.

    role = newRole;
    if (MUCRole.Role.none == role) {
        presence.setType(Presence.Type.unavailable);
        presence.setStatus(null);
    }
    calculateExtendedInformation();
}
 
Example #10
Source File: XmppControllerImplTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests adding, removing IQ listeners and handling IQ stanzas.
 */
@Test
public void handlePackets() {
    // IQ packets
    IQ iq = new IQ();
    Element element = new DefaultElement("pubsub", Namespace.get(testNamespace));
    iq.setChildElement(element);
    agent.processUpstreamEvent(jid1, iq);
    assertThat(testXmppIqListener.handledIqs, hasSize(1));
    agent.processUpstreamEvent(jid2, iq);
    assertThat(testXmppIqListener.handledIqs, hasSize(2));
    // Message packets
    Packet message = new Message();
    agent.processUpstreamEvent(jid1, message);
    assertThat(testXmppMessageListener.handledMessages, hasSize(1));
    agent.processUpstreamEvent(jid2, message);
    assertThat(testXmppMessageListener.handledMessages, hasSize(2));
    Packet presence = new Presence();
    agent.processUpstreamEvent(jid1, presence);
    assertThat(testXmppPresenceListener.handledPresenceStanzas, hasSize(1));
    agent.processUpstreamEvent(jid2, presence);
    assertThat(testXmppPresenceListener.handledPresenceStanzas, hasSize(2));
}
 
Example #11
Source File: PubSubModule.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Packet packet) {
    try {
        // Check if the packet is a disco request or a packet with namespace iq:register
        if (packet instanceof IQ) {
            if (engine.process(this, (IQ) packet) == null) {
                process((IQ) packet);
            }
        }
        else if (packet instanceof Presence) {
            engine.process(this, (Presence) packet);
        }
        else {
            engine.process(this, (Message) packet);
        }
    }
    catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        if (packet instanceof IQ) {
            // Send internal server error
            IQ reply = IQ.createResultIQ((IQ) packet);
            reply.setError(PacketError.Condition.internal_server_error);
            send(reply);
        }
    }
}
 
Example #12
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 #13
Source File: IQPEPHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void availableSession(ClientSession session, Presence presence) {
    // Do nothing if server is not enabled
    if (!isEnabled()) {
        return;
    }
    JID newlyAvailableJID = presence.getFrom();

    if (newlyAvailableJID == null) {
        return;
    }
    
    final GetNotificationsOnInitialPresence task = new GetNotificationsOnInitialPresence(newlyAvailableJID);
    executor.submit(task);
}
 
Example #14
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends presence of new occupant to existing occupants.
 *
 * @param joinRole the role of the new occupant in the room.
 */
void sendInitialPresenceToExistingOccupants(MUCRole joinRole) {
    // Send the presence of this new occupant to existing occupants
    Log.trace( "Send presence of new occupant '{}' to existing occupants of room '{}'.", joinRole.getUserAddress(), joinRole.getChatRoom().getJID() );
    try {
        final Presence joinPresence = joinRole.getPresence().createCopy();
        broadcastPresence(joinPresence, true, joinRole);
    } catch (Exception e) {
        Log.error( "An exception occurred while sending initial presence of new occupant '"+joinRole.getUserAddress()+"' to the existing occupants of room: '"+joinRole.getChatRoom().getJID()+"'.", e);
    }
}
 
Example #15
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 #16
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void send(@Nonnull Packet packet, @Nonnull MUCRole sender) {
    if (packet instanceof Message) {
        broadcast((Message)packet, sender);
    }
    else if (packet instanceof Presence) {
        broadcastPresence((Presence)packet, false, sender);
    }
    else if (packet instanceof IQ) {
        IQ reply = IQ.createResultIQ((IQ) packet);
        reply.setChildElement(((IQ) packet).getChildElement());
        reply.setError(PacketError.Condition.bad_request);
        router.route(reply);
    }
}
 
Example #17
Source File: SocketPacketWriteHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
 public void process(Packet packet) throws UnauthorizedException, PacketException {
    try {
        JID recipient = packet.getTo();
        // Check if the target domain belongs to a remote server or a component
        if (server.matchesComponent(recipient) || server.isRemote(recipient)) {
            routingTable.routePacket(recipient, packet, false);
        }
        // The target domain belongs to the local server
        else if (recipient == null || (recipient.getNode() == null && recipient.getResource() == null)) {
            // no TO was found so send back the packet to the sender
            routingTable.routePacket(packet.getFrom(), packet, false);
        }
        else if (recipient.getResource() != null || !(packet instanceof Presence)) {
            // JID is of the form <user@domain/resource>
            routingTable.routePacket(recipient, packet, false);
        }
        else {
            // JID is of the form <user@domain>
            for (JID route : routingTable.getRoutes(recipient, null)) {
                routingTable.routePacket(route, packet, false);
            }
        }
    }
    catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error.deliver") + "\n" + packet.toString(), e);
    }
}
 
Example #18
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 #19
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public Presence addModerator(JID jid, MUCRole senderRole) throws ForbiddenException {
    if (MUCRole.Affiliation.admin != senderRole.getAffiliation()
            && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
        throw new ForbiddenException();
    }
    // Update the presence with the new role and inform all occupants
    try {
        return changeOccupantRole(jid, MUCRole.Role.moderator);
    }
    catch (NotAllowedException e) {
        // We should never receive this exception....in theory
        return null;
    }
}
 
Example #20
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 #21
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public List<Presence> addAdmins(List<JID> newAdmins, MUCRole senderRole)
        throws ForbiddenException, ConflictException {
    List<Presence> answer = new ArrayList<>(newAdmins.size());
    for (JID newAdmin : newAdmins) {
        final JID bareJID = newAdmin.asBareJID();
        if (!admins.contains(bareJID)) {
            answer.addAll(addAdmin(bareJID, senderRole));
        }
    }
    return answer;
}
 
Example #22
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public List<Presence> addOwners(List<JID> newOwners, MUCRole senderRole)
        throws ForbiddenException {
    List<Presence> answer = new ArrayList<>(newOwners.size());
    for (JID newOwner : newOwners) {
        final JID bareJID = newOwner.asBareJID();
        if (!owners.contains(newOwner)) {
            answer.addAll(addOwner(bareJID, senderRole));
        }
    }
    return answer;
}
 
Example #23
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 #24
Source File: BroadcastPresenceRequest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    super.readExternal(in);
    Element packetElement = (Element) ExternalizableUtil.getInstance().readSerializable(in);
    presence = new Presence(packetElement, true);
    userAddressSender = (JID) ExternalizableUtil.getInstance().readSerializable(in);
}
 
Example #25
Source File: UpdateOccupantRequest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        Presence presence = getRoom().updateOccupant(this);
        if (presence != null) {
            answer = presence.getElement();
        }
    } catch (NotAllowedException e) {
        // Do nothing. A null return value means that the operation failed
    }
}
 
Example #26
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 #27
Source File: PresenceManagerImpl.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Presence> getPresences(String username) {
    if (username == null) {
        return null;
    }
    List<Presence> presences = new ArrayList<>();

    for (ClientSession session : sessionManager.getSessions(username)) {
        presences.add(session.getPresence());
    }
    return Collections.unmodifiableCollection(presences);
}
 
Example #28
Source File: PresenceSubscribeHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Determine and call the update method based on the item's subscription state.
 * <p/>
 *
 * @param item      The item to be updated
 * @param action    The new state change request
 * @param isSending True if the roster owner of the item is sending the new state change request
 */
private static void updateState(RosterItem item, Presence.Type action, boolean isSending) {
    Change change = getStateChange(item.getSubStatus(), action, isSending);
    if (change.getNewAsk() != null && change.getNewAsk() != item.getAskStatus()) {
        item.setAskStatus(change.getNewAsk());
    }
    if (change.getNewSub() != null && change.getNewSub() != item.getSubStatus()) {
        item.setSubStatus(change.getNewSub());
    }
    if (change.getNewRecv() != null && change.getNewRecv() != item.getRecvStatus()) {
        item.setRecvStatus(change.getNewRecv());
    }
}
 
Example #29
Source File: PresenceEventDispatcher.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Notification message indicating that an available session has changed its
 * presence. This is the case when the user presence changed the show value
 * (e.g. away, dnd, etc.) or the presence status message.
 *
 * @param session the affected session.
 * @param presence the received available presence with the new information.
 */
public static void presenceChanged(ClientSession session, Presence presence) {
    if (!listeners.isEmpty()) {
        for (PresenceEventListener listener : listeners) {
            try {
                listener.presenceChanged(session, presence); 
            } catch (Exception e) {
                Log.warn("An exception occurred while dispatching a 'presenceChanged' event!", e);
            }
        }
    }
}
 
Example #30
Source File: ClientSessionInfo.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    Element packetElement = (Element) ExternalizableUtil.getInstance().readSerializable(in);
    presence = new Presence(packetElement, true);
    if (ExternalizableUtil.getInstance().readBoolean(in)) {
        defaultList = ExternalizableUtil.getInstance().readSafeUTF(in);
    }
    if (ExternalizableUtil.getInstance().readBoolean(in)) {
        activeList = ExternalizableUtil.getInstance().readSafeUTF(in);
    }
    offlineFloodStopped = ExternalizableUtil.getInstance().readBoolean(in);
    messageCarbonsEnabled = ExternalizableUtil.getInstance().readBoolean(in);
    hasRequestedBlocklist = ExternalizableUtil.getInstance().readBoolean(in);
}