Package org.xmpp.packet

Examples of org.xmpp.packet.Presence


            }
        }
    }

    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;
    }
View Full Code Here


        String roomID = packet.getFrom().getNode();
        // Get the sessionID
        String sessionID = packet.getFrom().getNode();
        synchronized (sessionID.intern()) {
            if (packet instanceof Presence) {
                Presence presence = (Presence)packet;
                if (Presence.Type.error == presence.getType()) {
                    // A configuration must be wrong (eg. workgroup is not allowed to create rooms).
                    // Log the error presence
                    String warnMessage = "Possible server misconfiguration. Received error " +
                        "presence:" + presence.toXML();
                    Log.warn(warnMessage);
                    return;
                }
                // Get the JID of the presence's user
                Element mucUser = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
                // Skip this presence if no extended info was included in the presence
                if (mucUser == null) {
                    return;
                }
                Element item = mucUser.element("item");
                // Skip this presence if no item was included in the presence
                if (item == null) {
                    return;
                }
                // Skip this presence if it's the presence of this workgroup in the room
                if (workgroupName.equals(packet.getFrom().getResource())) {
                    return;
                }
                JID presenceFullJID = new JID(item.attributeValue("jid"));
                String presenceJID = presenceFullJID.toBareJID();
                // Invoke the room interceptor before processing the presence
                interceptorManager.invokeInterceptors(getJID().toBareJID(), packet, false, false);
                // Get the userID associated to this sessionID
                UserRequest initialRequest = requests.get(sessionID);
                // Add the new presence to the list of sent packets
                Map<Packet, java.util.Date> messageList = transcripts.get(roomID);
                if (messageList == null) {
                    messageList = new LinkedHashMap<Packet, java.util.Date>();
                    transcripts.put(roomID, messageList);
                    // Trigger the event that a chat support has started
                    WorkgroupEventDispatcher.chatSupportStarted(this, sessionID);
                }
                messageList.put(packet.createCopy(), new java.util.Date());

                // Update the number of occupants in the room.
                boolean occupantAdded = false;
                Set<String> set = occupantsCounter.get(roomID);
                if (set == null) {
                    set = new HashSet<String>();
                    occupantsCounter.put(roomID, set);
                }
                if (presence.isAvailable()) {
                    occupantAdded = set.add(presenceJID);
                }
                else {
                    String xpath = "/presence/*[name()='x']/*[name()='status']";
                    Element status = (Element)presence.getElement().selectSingleNode(xpath);
                    if (status == null || !"303".equals(status.attributeValue("code"))) {
                        // Remove the occupant unless the occupant is changing his nickname
                        set.remove(presenceJID);
                    }
                }
                // If the presence belongs to an Agent then create/update a track
                // Look for an agent whose JID matches the presence's JID
                String agentJID = null;
                for (Agent agent : getAgents()) {
                    if (agent.getAgentJID().toBareJID().equals(presenceJID)) {
                        agentJID = agent.getAgentJID().toBareJID();
                    }
                }
                if (agentJID != null) {
                    AgentSession agentSession;
                    // Update the current chats that the agent is having
                    try {
                        agentSession = agentManager.getAgentSession(presenceFullJID);
                        if (agentSession != null) {
                            if (presence.isAvailable()) {
                                if (occupantAdded) {
                                    agentSession.addChatInfo(this, sessionID, initialRequest, new java.util.Date());
                                    // Trigger the event that an agent has joined a chat session
                                    WorkgroupEventDispatcher.agentJoinedChatSupport(this, sessionID, agentSession);
                                }
                            }
                            else {
                                agentSession.removeChatInfo(this, sessionID);
                                // Trigger the event that an agent has left a chat session
                                WorkgroupEventDispatcher.agentLeftChatSupport(this, sessionID, agentSession);
                            }
                        }
                    }
                    catch (AgentNotFoundException e) {
                        // Do nothing since the AgentSession was not found
                    }
                    if (presence.isAvailable()) {
                        if (occupantAdded) {
                            // Store in the DB that an agent has joined a room
                            DbWorkgroup.updateJoinedSession(sessionID, agentJID, true);
                        }
                    }
                    else {
                        // Store in the DB that an agent has left a room
                        DbWorkgroup.updateJoinedSession(sessionID, agentJID, false);
                    }
                }
                else {
                    if (occupantAdded) {
                        // Notify the request that the user has joined a support session
                        initialRequest.supportStarted(roomID);
                    }
                }
                if (occupantAdded) {
                    initialRequest.userJoinedRoom(new JID(packet.getFrom().toBareJID()), presenceFullJID);
                }

                // If just the user has left the room, just persist the transcript
                boolean isAgent = false;
                try {
                    isAgent = agentManager.getAgentSession(presenceFullJID) != null;
                }
                catch (AgentNotFoundException e) {
                    // Ignore.
                }

                if (!((Presence)packet).isAvailable() && !isAgent) {
                    // Build the XML for the transcript
                    Map<Packet, java.util.Date> map = transcripts.get(roomID);
                    StringBuilder buf = new StringBuilder();
                    buf.append("<transcript>");
                    for (Packet p : map.keySet()) {
                        java.util.Date date = map.get(p);
                        // Add the delay information
                        if (p instanceof Message) {
                            Message storedMessage = (Message)p;
                            Element delay = storedMessage.addChildElement("x", "jabber:x:delay");
                            delay.addAttribute("stamp", UTC_FORMAT.format(date));
                            if (ModelUtil.hasLength(storedMessage.getBody())) {
                                buf.append(p.toXML());
                            }
                        }
                        else {
                            Presence storedPresence = (Presence)p;
                            Element delay = storedPresence.addChildElement("x", "jabber:x:delay");
                            delay.addAttribute("stamp", UTC_FORMAT.format(date));
                            buf.append(p.toXML());
                        }
                        // Append an XML representation of the packet to the string buffer
                    }
                    buf.append("</transcript>");
                    // Save the transcript (in XML) to the DB
                    DbWorkgroup.updateTranscript(sessionID, buf.toString(), new java.util.Date());
                }

                // If the agent and the user left the room then proceed to dump the transcript to
                // the DB and destroy the room
                if (!((Presence)packet).isAvailable() && set.isEmpty()) {
                    // Delete the counter of occupants for this room
                    occupantsCounter.remove(roomID);
                    initialRequest = requests.remove(sessionID);
                    if (initialRequest != null && initialRequest.hasJoinedRoom()) {
                        // Notify the request that the support session has finished
                        initialRequest.supportEnded();
                    }
                    // Build the XML for the transcript
                    Map<Packet, java.util.Date> map = transcripts.get(roomID);
                    StringBuilder buf = new StringBuilder();
                    buf.append("<transcript>");
                    for (Packet p : map.keySet()) {
                        java.util.Date date = map.get(p);
                        // Add the delay information
                        if (p instanceof Message) {
                            Message storedMessage = (Message)p;
                            Element delay = storedMessage.addChildElement("x", "jabber:x:delay");
                            delay.addAttribute("stamp", UTC_FORMAT.format(date));
                            if (ModelUtil.hasLength(storedMessage.getBody())) {
                                buf.append(p.toXML());
                            }
                        }
                        else {
                            Presence storedPresence = (Presence)p;
                            Element delay = storedPresence.addChildElement("x", "jabber:x:delay");
                            delay.addAttribute("stamp", UTC_FORMAT.format(date));
                            buf.append(p.toXML());
                        }
                        // Append an XML representation of the packet to the string buffer
                    }
View Full Code Here

           
            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());
            }
View Full Code Here

        Map<Packet, java.util.Date> packets = transcripts.get(roomID);
        if (packets != null) {
            Collection<String> processed = new ArrayList<String>();
            for (Packet p : packets.keySet()) {
                if (p instanceof Presence) {
                    Presence presence = (Presence)p;
                    // Get the JID of the presence's user
                    String userJID = presence.getChildElement("x",
                        "http://jabber.org/protocol/muc#user")
                        .element("item")
                        .attributeValue("jid");
                    // Only add information about the first presence so we know the time when the
                    // occupant joined the room
                    if (!processed.contains(userJID)) {
                        processed.add(userJID);
                        Element occupantInfo = occupantsInfo.addElement("occupant");
                        occupantInfo.addElement("jid").setText(userJID);
                        occupantInfo.addElement("nickname").setText(presence.getFrom().getResource());
                        occupantInfo.addElement("joined").setText(UTC_FORMAT.format(packets.get(p)));
                    }
                }
            }
        }
View Full Code Here

                // Only create item if user was not already subscribed to workgroup's presence
                if (!presenceSubscribers.contains(sender.toBareJID())) {
                    createRosterItem(sender);
                }
                // Reply that the subscription request was approved
                Presence reply = new Presence();
                reply.setTo(sender);
                reply.setFrom(workgroup.getJID());
                reply.setType(Presence.Type.subscribed);
                workgroup.send(reply);
                // Send the presence of the workgroup to the user that requested it
                sendPresence(packet.getFrom());
            }
            else if (Presence.Type.unsubscribe == packet.getType()) {
                // Remove sender from the workgroup roster
                deleteRosterItem(sender);
                // Send confirmation of unsubscription
                Presence reply = new Presence();
                reply.setTo(sender);
                reply.setFrom(workgroup.getJID());
                reply.setType(Presence.Type.unsubscribed);
                workgroup.send(reply);
                // Send unavailable presence of the workgroup
                reply = new Presence();
                reply.setTo(sender);
                reply.setFrom(workgroup.getJID());
                reply.setType(Presence.Type.unavailable);
                workgroup.send(reply);
            }
            else if (Presence.Type.subscribed == packet.getType()) {
                // ignore
            }
            else if (Presence.Type.unsubscribed == packet.getType()) {
                // ignore
            }
            else if (Presence.Type.probe == packet.getType()) {
                // Send the presence of the workgroup to the user that requested it
                sendPresence(packet.getFrom());
            }
            else {
                try {
                    agentToWorkgroup(packet);
                }
                catch (AgentNotFoundException e) {
                    Presence reply = new Presence();
                    reply.setError(new PacketError(PacketError.Condition.not_authorized));
                    reply.setTo(packet.getFrom());
                    reply.setFrom(workgroup.getJID());
                    workgroup.send(reply);

                    StringBuilder errorMessage = new StringBuilder();
                    errorMessage.append("Sender: ");
                    errorMessage.append(packet.getFrom().toString());
                    errorMessage.append(" Workgroup: ");
                    errorMessage.append(workgroup.getJID().toString());
                    Log.debug(errorMessage.toString(), e);
                }
            }

        }
        catch (Exception e) {
            Log.error(e.getMessage(), e);
            Presence reply = new Presence();
            reply.setError(new PacketError(PacketError.Condition.internal_server_error));
            reply.setTo(packet.getFrom());
            reply.setFrom(workgroup.getJID());
            workgroup.send(reply);
        }
    }
View Full Code Here

     * Sends the presence of the workgroup to the specified JID address.
     *
     * @param address the XMPP address that will receive the presence of the workgroup.
     */
    public void sendPresence(JID address) {
        Presence presence = new Presence();
        presence.setTo(address);
        presence.setFrom(workgroup.getJID());

        Presence.Type type;
        if (workgroup.isAvailable()) {
            type = null;
            // Add the a child element that will contain information about the workgroup
            Element child = presence.addChildElement("workgroup",
                    "http://jivesoftware.com/protocol/workgroup");
            // Add the last modification date of the workgroup
            child.addElement("lastModified").setText(UTC_FORMAT.format(workgroup.getModificationDate()));
        }
        else {
            type = Presence.Type.unavailable;
            // Add the a child element that will contain information about the workgroup
            Element child = presence.addChildElement("workgroup",
                    "http://jivesoftware.com/protocol/workgroup");
            // Add the last modification date of the workgroup
            child.addElement("lastModified").setText(UTC_FORMAT.format(workgroup.getModificationDate()));
        }
        presence.setType(type);
        workgroup.send(presence);
    }
View Full Code Here

        TaskEngine.getInstance().submit(new Runnable() {
            public void run() {
                try {
                    for (String bareJID : presenceSubscribers) {
                        // Cancel the previously granted subscription request
                        Presence reply = new Presence();
                        reply.setTo(bareJID);
                        reply.setFrom(workgroup.getJID());
                        reply.setType(Presence.Type.unsubscribed);
                        workgroup.send(reply);
                    }
                    // Delete the subscribers from the database
                    deleteRosterItems();
                }
View Full Code Here

                // Add new agent session.
                agentSession = agent.createSession(packet.getFrom());
                if (agentSession == null) {
                    // User is not able to join since an existing session from another resource already exists
                    Presence reply = new Presence();
                    reply.setID(packet.getID());
                    reply.setTo(packet.getFrom());
                    reply.setFrom(packet.getTo());
                    reply.setError(PacketError.Condition.not_allowed);
                    workgroup.send(reply);
                    return;
                }
            }
View Full Code Here

                    // Nickname exists in room, and belongs to this user, pretend to kick the previous instance.
                    // The previous instance will see that they are disconnected, and the new instance will
                    // "take over" the previous role.  Participants in the room shouldn't notice anything
                    // has occurred.
                    String reason = "Your account signed into this chatroom with the same nickname from another location.";
                    Presence updatedPresence = new Presence(Presence.Type.unavailable);
                    updatedPresence.setFrom(occupants.get(nickname.toLowerCase()).getRoleAddress());
                    updatedPresence.setTo(occupants.get(nickname.toLowerCase()).getUserAddress());
                    Element frag = updatedPresence.addChildElement(
                            "x", "http://jabber.org/protocol/muc#user");

                    // Set the person who performed the kick ("you" effectively)
                    frag.addElement("item").addElement("actor").setText(user.getAddress().toString());
                    // Add the reason why the user was kicked
                    frag.element("item").addElement("reason").setText(reason);
                    // Add the status code 307 that indicates that the user was kicked
                    frag.addElement("status").addAttribute("code", "307");

                    router.route(updatedPresence);
                }
                else {
                    // Nickname is already used, and not by the same JID
                    throw new UserAlreadyExistsException();
                }
            }
            // If the room is password protected and the provided password is incorrect raise a
            // Unauthorized exception
            if (isPasswordProtected()) {
                if (password == null || !password.equals(getPassword())) {
                    throw new UnauthorizedException();
                }
            }
            // If another user attempts to join the room with a nickname reserved by the first user
            // raise a ConflictException
            if (members.containsValue(nickname)) {
                if (!nickname.equals(members.get(user.getAddress().toBareJID()))) {
                    throw new ConflictException();
                }
            }
            if (isLoginRestrictedToNickname()) {
                String reservedNickname = members.get(user.getAddress().toBareJID());
                if (reservedNickname != null && !nickname.equals(reservedNickname)) {
                    throw new NotAcceptableException();
                }
            }

            // Set the corresponding role based on the user's affiliation
            MUCRole.Role role;
            MUCRole.Affiliation affiliation;
            if (isOwner) {
                // The user is an owner. Set the role and affiliation accordingly.
                role = MUCRole.Role.moderator;
                affiliation = MUCRole.Affiliation.owner;
            }
            else if (mucService.getSysadmins().contains(user.getAddress().toBareJID())) {
                // 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
                role = MUCRole.Role.moderator;
                affiliation = MUCRole.Affiliation.owner;
            }
            else if (admins.contains(user.getAddress().toBareJID())) {
                // The user is an admin. Set the role and affiliation accordingly.
                role = MUCRole.Role.moderator;
                affiliation = MUCRole.Affiliation.admin;
            }
            else if (members.containsKey(user.getAddress().toBareJID())) {
                // The user is a member. Set the role and affiliation accordingly.
                role = MUCRole.Role.participant;
                affiliation = MUCRole.Affiliation.member;
            }
            else if (outcasts.contains(user.getAddress().toBareJID())) {
                // The user is an outcast. Raise a "Forbidden" exception.
                throw new ForbiddenException();
            }
            else {
                // The user has no affiliation (i.e. NONE). Set the role accordingly.
                if (isMembersOnly()) {
                    // The room is members-only and the user is not a member. Raise a
                    // "Registration Required" exception.
                    throw new RegistrationRequiredException();
                }
                role = (isModerated() ? MUCRole.Role.visitor : MUCRole.Role.participant);
                affiliation = MUCRole.Affiliation.none;
            }
            // Create a new role for this user in this room
            joinRole = new LocalMUCRole(mucService, this, nickname, role, affiliation, user, presence, router);
            // Add the new user as an occupant of this room
            occupants.put(nickname.toLowerCase(), joinRole);
            // Update the tables of occupants based on the bare and full JID
            List<MUCRole> list = occupantsByBareJID.get(user.getAddress().toBareJID());
            if (list == null) {
                list = new ArrayList<MUCRole>();
                occupantsByBareJID.put(user.getAddress().toBareJID(), list);
            }
            list.add(joinRole);
            occupantsByFullJID.put(user.getAddress(), joinRole);
        }
        finally {
            lock.writeLock().unlock();
        }
        // Notify other cluster nodes that a new occupant joined the room
        CacheFactory.doClusterTask(new OccupantAddedEvent(this, joinRole));

        // Send presence of existing occupants to new occupant
        sendInitialPresences(joinRole);
        // 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.
        boolean isRoomNew = isLocked() && creationDate.getTime() == lockedTime;
        try {
            // Send the presence of this new occupant to existing occupants
            Presence joinPresence = joinRole.getPresence().createCopy();
            if (isRoomNew) {
                Element frag = joinPresence.getChildElement("x", "http://jabber.org/protocol/muc#user");
                frag.addElement("status").addAttribute("code", "201");
            }
            broadcastPresence(joinPresence);
        }
        catch (Exception e) {
View Full Code Here

    private void sendInitialPresences(LocalMUCRole joinRole) {
        for (MUCRole occupant : occupants.values()) {
            if (occupant == joinRole) {
                continue;
            }
            Presence occupantPresence = occupant.getPresence();
            // Skip to the next occupant if we cannot send presence of this occupant
            if (hasToCheckRoleToBroadcastPresence()) {
                Element frag = occupantPresence.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"))) {
                    continue;
                }
            }
            // Don't include the occupant's JID if the room is semi-anon and the new occupant
            // is not a moderator
            if (!canAnyoneDiscoverJID() && MUCRole.Role.moderator != joinRole.getRole()) {
                occupantPresence = occupantPresence.createCopy();
                Element frag = occupantPresence.getChildElement("x",
                        "http://jabber.org/protocol/muc#user");
                frag.element("item").addAttribute("jid", null);
            }
            joinRole.send(occupantPresence);
        }
View Full Code Here

TOP

Related Classes of org.xmpp.packet.Presence

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.