Java Code Examples for org.xmpp.packet.Presence

The following examples show how to use org.xmpp.packet.Presence. 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   Source File: LocalMUCRole.java    License: 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 2
Source Project: Openfire   Source File: AuditorImpl.java    License: 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 3
Source Project: Openfire   Source File: LocalMUCRoom.java    License: 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 4
Source Project: Openfire   Source File: LocalMUCRoom.java    License: 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 Project: Openfire   Source File: PacketRouterImpl.java    License: 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 6
Source Project: Openfire   Source File: LocalMUCRoom.java    License: 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 7
Source Project: Openfire   Source File: OccupantAddedEvent.java    License: 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 8
Source Project: Openfire   Source File: RoutingTableImpl.java    License: 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 9
Source Project: Openfire   Source File: PresenceManagerImpl.java    License: 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 10
Source Project: onos   Source File: XmppControllerImplTest.java    License: 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 Project: Openfire   Source File: PubSubModule.java    License: 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 Project: Openfire   Source File: SessionManager.java    License: 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 Project: Openfire-GCM   Source File: GcmPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private boolean checkTarget(Message msg) throws UserNotFoundException {
	if(msg.getBody() == null || msg.getBody().equals("")){
		return false;
	}
	
	JID toJID = msg.getTo().asBareJID();
	if(mDebug)Log.info("GCM Plugin check() called");

	if(!toJID.getDomain().contains(mServer.getServerInfo().getXMPPDomain())){
		return false;
	}
	
	if (mMode.equalsIgnoreCase(GcmPlugin.MODE_ALL)) {
		return true;
	} else if (mMode.equalsIgnoreCase(GcmPlugin.MODE_OFFLINE)) {
		
		String y = UserNameManager.getUserName(toJID);
		if(mDebug)Log.info("GCM Plugin getUserName(...) = " + y);
		User x = mUserManager.getUser(y);
		if(mDebug)Log.info("GCM Plugin getUser(...) = " + x.toString());
		try{
			Presence z = mPresenceManager.getPresence(x);
			if(z == null) return true;
			if(mDebug)Log.info("GCM Plugin getPresence(...) = " + z.toString());
			return !z.isAvailable();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	} else if (mMode.equalsIgnoreCase(GcmPlugin.MODE_NO_MOBILE)) {
		
	} else if (mMode.equalsIgnoreCase(GcmPlugin.MODE_EXCEPTION)) {

	}

	return true;
}
 
Example 14
Source Project: Openfire   Source File: InternalComponentManager.java    License: 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 15
Source Project: Openfire   Source File: LocalMUCRole.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setPresence(Presence newPresence) {
    // Try to remove the element whose namespace is "http://jabber.org/protocol/muc" since we
    // don't need to include that element in future presence broadcasts
    Element element = newPresence.getElement().element(QName.get("x", "http://jabber.org/protocol/muc"));
    if (element != null) {
        newPresence.getElement().remove(element);
    }

    this.presence = newPresence;
    this.presence.setFrom(getRoleAddress());
    updatePresence();
}
 
Example 16
Source Project: Openfire   Source 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 17
Source Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks all preconditions for joining a room. If one of them fails, an Exception is thrown.
 */
private void checkJoinRoomPreconditions(
        @Nonnull final LocalMUCUser user,
        @Nonnull final String nickname,
        @Nonnull final MUCRole.Affiliation affiliation,
        @Nullable final String password,
        @Nonnull final Presence presence)
    throws ServiceUnavailableException, RoomLockedException, UserAlreadyExistsException, UnauthorizedException, ConflictException, NotAcceptableException, ForbiddenException, RegistrationRequiredException
{
    Log.debug( "Checking all preconditions for user '{}' to join room '{}'.", user.getAddress(), this.getJID() );

    checkJoinRoomPreconditionDelegate( user );

    // If the room has a limit of max user then check if the limit has been reached
    checkJoinRoomPreconditionMaxOccupants( user );

    // If the room is locked and this user is not an owner raise a RoomLocked exception
    checkJoinRoomPreconditionLocked( user );

    // Check if the nickname is already used in the room
    checkJoinRoomPreconditionNicknameInUse( user, nickname );

    // If the room is password protected and the provided password is incorrect raise a
    // Unauthorized exception - unless the JID that is joining is a system admin.
    checkJoinRoomPreconditionPasswordProtection( user, password );

    // If another user attempts to join the room with a nickname reserved by the first user
    // raise a ConflictException
    checkJoinRoomPreconditionNicknameReserved( user, nickname );

    checkJoinRoomPreconditionRestrictedToNickname( user, nickname );

    // Check if the user can join the room.
    checkJoinRoomPreconditionIsOutcast( user, affiliation );

    // If the room is members-only and the user is not a member. Raise a "Registration Required" exception.
    checkJoinRoomPreconditionMemberOnly( user, affiliation );

    Log.debug( "All preconditions for user '{}' to join room '{}' have been met. User can join the room.", user.getAddress(), this.getJID() );
}
 
Example 18
Source Project: Openfire   Source File: LocalMUCRoom.java    License: 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 19
Source Project: Openfire   Source File: LocalMUCRoom.java    License: 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 20
Source Project: Openfire   Source 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 21
Source Project: Openfire   Source File: LocalMUCRoom.java    License: 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 22
Source Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks the role of the sender and returns true if the given presence should be broadcasted
 *
 * @param presence The presence to check
 * @return true if the presence should be broadcast to the rest of the room
 */
private boolean shouldBroadcastPresence(Presence presence){
    if (presence == null) {
        return false;
    }
    if (hasToCheckRoleToBroadcastPresence()) {
        Element frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
        // Check if we can broadcast the presence for this role
        if (!canBroadcastPresence(frag.element("item").attributeValue("role"))) {
            return false;
        }
    }
    return true;
}
 
Example 23
Source Project: Openfire   Source File: IQPEPHandler.java    License: 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 24
Source Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * Updates the presence of the given user with the new role information. Do nothing if the given
     * jid is not present in the room.
     *
     * @param jid the full jid of the user to update his/her role.
     * @param newRole the new role for the JID.
     * @return the updated presence of the user or null if none.
     * @throws NotAllowedException If trying to change the moderator role to an owner or an admin.
     */
    private Presence changeOccupantRole(JID jid, MUCRole.Role newRole) throws NotAllowedException {
        // Try looking the role in the bare JID list
        MUCRole role = occupantsByFullJID.get(jid);
// TODO
//            if (!isPrivilegedToChangeAffiliationAndRole(senderRole.getAffiliation(), senderRole.getRole(), role.getAffiliation(), role.getRole(), newAffiliation, newRole)) {
//                throw new NotAllowedException();
//            }
        if (role != null) {
            if (role.isLocal()) {
                // Update the presence with the new role
                role.setRole(newRole);
                // Notify the other cluster nodes to update the occupant
                CacheFactory.doClusterTask(new UpdateOccupant(this, role));
                // Prepare a new presence to be sent to all the room occupants
                return role.getPresence().createCopy();
            }
            else {
                // Ask the cluster node hosting the occupant to make the changes. Note that if the change
                // is not allowed a NotAllowedException will be thrown
                Element element = CacheFactory.doSynchronousClusterTask(
                        new UpdateOccupantRequest(this, role.getNickname(), null, newRole),
                        role.getNodeID().toByteArray());
                if (element != null) {
                    // Prepare a new presence to be sent to all the room occupants
                    return new Presence(element, true);
                }
                else {
                    throw new NotAllowedException();
                }
            }
        }
        return null;
    }
 
Example 25
Source Project: Openfire   Source File: SocketPacketWriteHandler.java    License: 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 <[email protected]/resource>
            routingTable.routePacket(recipient, packet, false);
        }
        else {
            // JID is of the form <[email protected]>
            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 26
Source Project: Openfire   Source File: LocalMUCRoom.java    License: 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 27
Source Project: Openfire   Source File: LocalMUCRoom.java    License: 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 28
Source Project: Openfire   Source File: LocalMUCRoom.java    License: 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 29
Source Project: Openfire   Source File: PresenceUpdateHandler.java    License: 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 30
Source Project: Openfire   Source File: BroadcastPresenceRequest.java    License: 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);
}