Java Code Examples for org.xmpp.packet.Message#addChildElement()

The following examples show how to use org.xmpp.packet.Message#addChildElement() . 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: LocalMUCRoom.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void sendInvitationRejection(JID to, String reason, JID sender) {
if (((MultiUserChatServiceImpl)mucService).getMUCDelegate() != null) {
        switch(((MultiUserChatServiceImpl)mucService).getMUCDelegate().sendingInvitationRejection(this, to, sender, reason)) {
                case HANDLED_BY_DELEGATE:
                    //if the delegate is taking care of it, there's nothing for us to do
                        return;
                case HANDLED_BY_OPENFIRE:
                    //continue as normal if we're asked to handle it
                        break;
            }
    }

    Message message = new Message();
    message.setFrom(role.getRoleAddress());
    message.setTo(to);
    Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user");
    frag.addElement("decline").addAttribute("from", sender.toBareJID());
    if (reason != null && reason.length() > 0) {
        frag.element("decline").addElement("reason").setText(reason);
    }

    // Send the message with the invitation
    router.route(message);
}
 
Example 2
Source File: Node.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * The node configuration has changed. If this is the first time the node is configured
 * after it was created (i.e. is not yet persistent) then do nothing. Otherwise, send
 * a notification to the node subscribers informing that the configuration has changed.
 */
private void nodeConfigurationChanged() {
    if (!isNotifiedOfConfigChanges() || !savedToDB) {
        // Do nothing if node was just created and configure or if notification
        // of config changes is disabled
        return;
    }

    // Build packet to broadcast to subscribers
    Message message = new Message();
    Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
    Element config = event.addElement("configuration");
    config.addAttribute("node", nodeID);

    if (deliverPayloads) {
        config.add(getConfigurationChangeForm().getElement());
    }
    // Send notification that the node configuration has changed
    broadcastNodeEvent(message, false);

    // And also to the subscribers of parent nodes with proper subscription depth
    final CollectionNode parent = getParent();
    if (parent != null){
        parent.childNodeModified(this, message);
    }
}
 
Example 3
Source File: HttpSessionDeliverable.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the default namespace is set on empty stanzas.
 *
 * @see <a href="https://igniterealtime.org/issues/browse/OF-1087">OF-1087</a>
 */
@Test
public void testNamespaceOnEmptyStanza() throws Exception
{
    // Setup fixture
    final Message message = new Message();
    message.addChildElement( "unittest", "unit:test:namespace" );
    final List<Packet> packets = new ArrayList<>();
    packets.add( message );

    // Execute system under test
    final HttpSession.Deliverable deliverable = new HttpSession.Deliverable( packets );
    final String result = deliverable.getDeliverable();

    // verify results
    // Note that this assertion depends on the Openfire XML parser-specific ordering of attributes.
    assertEquals( "<message xmlns=\"jabber:client\"><unittest xmlns=\"unit:test:namespace\"/></message>", result );
}
 
Example 4
Source File: HttpSessionDeliverable.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the default namespace is set on (non-empty) stanzas.
 *
 * @see <a href="https://igniterealtime.org/issues/browse/OF-1087">OF-1087</a>
 */
@Test
public void testNamespaceOnStanza() throws Exception
{
    // Setup fixture
    final Message message = new Message();
    message.setTo( "[email protected]/test" );
    message.addChildElement( "unittest", "unit:test:namespace" );
    final List<Packet> packets = new ArrayList<>();
    packets.add( message );

    // Execute system under test
    final HttpSession.Deliverable deliverable = new HttpSession.Deliverable( packets );
    final String result = deliverable.getDeliverable();

    // verify results
    // Note that this assertion depends on the Openfire XML parser-specific ordering of attributes.
    assertEquals( "<message to=\"[email protected]/test\" xmlns=\"jabber:client\"><unittest xmlns=\"unit:test:namespace\"/></message>", result );
}
 
Example 5
Source File: HttpSessionDeliverable.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the default namespace is not set on stanzas that already have defined a default namespace.
 *
 * @see <a href="https://igniterealtime.org/issues/browse/OF-1087">OF-1087</a>
 */
@Test
public void testNamespaceOnStanzaWithNamespace() throws Exception
{
    // Setup fixture
    final Message message = new Message();
    message.getElement().setQName( QName.get( "message", "unit:test:preexisting:namespace" ) );
    message.setTo( "[email protected]/test" );
    message.addChildElement( "unittest", "unit:test:namespace" );
    final List<Packet> packets = new ArrayList<>();
    packets.add( message );

    // Execute system under test
    final HttpSession.Deliverable deliverable = new HttpSession.Deliverable( packets );
    final String result = deliverable.getDeliverable();

    // verify results
    // Note that this assertion depends on the Openfire XML parser-specific ordering of attributes.
    assertEquals( "<message xmlns=\"unit:test:preexisting:namespace\" to=\"[email protected]/test\"><unittest xmlns=\"unit:test:namespace\"/></message>", result );
}
 
Example 6
Source File: IQMUCvCardHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void sendConfigChangeNotification( final MUCRoom room )
{
    Log.debug("Sending configuration change notification to all occupants of room {}", room.getName());
    final Message notification = new Message();
    notification.setType(Message.Type.groupchat);
    notification.setFrom(room.getJID());
    final Element x = notification.addChildElement("x", "http://jabber.org/protocol/muc#user");
    final Element status = x.addElement("status");
    status.addAttribute("code", "104");

    for ( final MUCRole occupant : room.getOccupants() )
    {
        occupant.send(notification);
    }
}
 
Example 7
Source File: LeafNode.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the list of published items from the node. Event notifications may be sent to
 * subscribers for the deleted items. When an affiliate has many subscriptions to the node,
 * the affiliate will get a notification for each set of items that affected the same list
 * of subscriptions.<p>
 *
 * For performance reasons the deleted published items are saved to the database
 * using a background thread. Sending event notifications to node subscribers may
 * also use another thread to ensure good performance.<p>
 *
 * @param toDelete list of items that were deleted from the node.
 */
public void deleteItems(List<PublishedItem> toDelete) {
    // Remove deleted items from the database
    for (PublishedItem item : toDelete) {
        PubSubPersistenceProviderManager.getInstance().getProvider().removePublishedItem(item);
        if (lastPublished != null && lastPublished.getID().equals(item.getID())) {
            lastPublished = null;
        }
    }
    if (isNotifiedOfRetract()) {
        // Broadcast notification deletion to subscribers
        // Build packet to broadcast to subscribers
        Message message = new Message();
        Element event =
                message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
        // Send notification that items have been deleted to subscribers and parent node
        // subscribers
        Set<NodeAffiliate> affiliatesToNotify = new HashSet<>(affiliates);
        // Get affiliates that are subscribed to a parent in the hierarchy of parent nodes
        for (CollectionNode parentNode : getParents()) {
            for (NodeSubscription subscription : parentNode.getSubscriptions()) {
                affiliatesToNotify.add(subscription.getAffiliate());
            }
        }
        // TODO Use another thread for this (if # of subscribers is > X)????
        for (NodeAffiliate affiliate : affiliatesToNotify) {
            affiliate.sendDeletionNotifications(message, event, this, toDelete);
        }
    }
}
 
Example 8
Source File: LeafNode.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Purges items that were published to the node. Only owners can request this operation.
 * This operation is only available for nodes configured to store items in the database. All
 * published items will be deleted with the exception of the last published item.
 */
public void purge() {
    PubSubPersistenceProviderManager.getInstance().getProvider().purgeNode(this);
    // Broadcast purge notification to subscribers
    // Build packet to broadcast to subscribers
    Message message = new Message();
    Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
    Element items = event.addElement("purge");
    items.addAttribute("node", nodeID);
    // Send notification that the node configuration has changed
    broadcastNodeEvent(message, false);
}
 
Example 9
Source File: Node.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes this node from memory and the database. Subscribers are going to be notified
 * that the node has been deleted after the node was successfully deleted.
 */
public void delete() {
    // Delete node from the database
    PubSubPersistenceProviderManager.getInstance().getProvider().removeNode(this);
    // Remove this node from the parent node (if any)
    if (parentIdentifier != null) {
        final CollectionNode parent = getParent();
        // Notify the parent that the node has been removed from the parent node
        if (isNotifiedOfDelete()){
            parent.childNodeDeleted(this);
        }
        parent.removeChildNode(this);
    }
    deletingNode();
    // Broadcast delete notification to subscribers (if enabled)
    if (isNotifiedOfDelete()) {
        // Build packet to broadcast to subscribers
        Message message = new Message();
        Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
        Element items = event.addElement("delete");
        items.addAttribute("node", nodeID);
        // Send notification that the node was deleted
        broadcastNodeEvent(message, true);
    }
    // Remove presence subscription when node was deleted.
    cancelPresenceSubscriptions();
    // Remove the node from memory
    getService().removeNode(nodeID);
    CacheFactory.doClusterTask(new RemoveNodeTask(this));
    // Clear collections in memory (clear them after broadcast was sent)
    affiliates.clear();
    subscriptionsByID.clear();
    subscriptionsByJID.clear();
}
 
Example 10
Source File: Node.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an event notification to the specified subscriber. The event notification may
 * include information about the affected subscriptions.
 *
 * @param subscriberJID the subscriber JID that will get the notification.
 * @param notification the message to send to the subscriber.
 * @param subIDs the list of affected subscription IDs or null when node does not
 *        allow multiple subscriptions.
 */
protected void sendEventNotification(JID subscriberJID, Message notification,
        Collection<String> subIDs) {
    Element headers = null;
    if (subIDs != null) {
        // Notate the event notification with the ID of the affected subscriptions
        headers = notification.addChildElement("headers", "http://jabber.org/protocol/shim");
        for (String subID : subIDs) {
            Element header = headers.addElement("header");
            header.addAttribute("name", "SubID");
            header.setText(subID);
        }
    }
    
    // Verify that the subscriber JID is currently available to receive notification
    // messages. This is required because the message router will deliver packets via 
    // the bare JID if a session for the full JID is not available. The "isActiveRoute"
    // condition below will prevent inadvertent delivery of multiple copies of each
    // event notification to the user, possibly multiple times (e.g. route.all-resources). 
    // (Refer to http://issues.igniterealtime.org/browse/OF-14 for more info.)
    //
    // This approach is informed by the following XEP-0060 implementation guidelines:
    //   12.2 "Intended Recipients for Notifications" - only deliver to subscriber JID
    //   12.4 "Not Routing Events to Offline Storage" - no offline storage for notifications
    //
    // Note however that this may be somewhat in conflict with the following:
    //   12.3 "Presence-Based Delivery of Events" - automatically detect user's presence
    //
    if (subscriberJID.getResource() == null ||
        SessionManager.getInstance().getSession(subscriberJID) != null) {
        getService().sendNotification(this, notification, subscriberJID);
    }

    if (headers != null) {
        // Remove the added child element that includes subscription IDs information
        notification.getElement().remove(headers);
    }
}
 
Example 11
Source File: CollectionNode.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Notification that a new node was created and added to this node. Trigger notifications
 * to node subscribers whose subscription type is {@link NodeSubscription.Type#nodes} and
 * have the proper depth.
 *
 * @param child the newly created node that was added to this node.
 */
void childNodeAdded(Node child) {
    // Build packet to broadcast to subscribers
    Message message = new Message();
    Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
    Element items = event.addElement("items");
    items.addAttribute("node", nodeID);
    Element item = items.addElement("item");
    item.addAttribute("id", child.getUniqueIdentifier().getNodeId());
    if (deliverPayloads) {
        item.add(child.getMetadataForm().getElement());
    }
    // Broadcast event notification to subscribers
    broadcastCollectionNodeEvent(child, message);
}
 
Example 12
Source File: CollectionNode.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Notification that a child node was deleted from this node. Trigger notifications
 * to node subscribers whose subscription type is {@link NodeSubscription.Type#nodes} and
 * have the proper depth.
 *
 * @param child the deleted node that was removed from this node.
 */
void childNodeDeleted(Node child) {
    // Build packet to broadcast to subscribers
    Message message = new Message();
    Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
    event.addElement("delete").addAttribute("node", child.getUniqueIdentifier().getNodeId());
    // Broadcast event notification to subscribers
    broadcastCollectionNodeEvent(child, message);
}
 
Example 13
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public void sendInvitation(JID to, String reason, MUCRole senderRole, List<Element> extensions)
        throws ForbiddenException, CannotBeInvitedException {
    if (!isMembersOnly() || canOccupantsInvite()
            || MUCRole.Affiliation.admin == senderRole.getAffiliation()
            || MUCRole.Affiliation.owner == senderRole.getAffiliation()) {
        // If the room is not members-only OR if the room is members-only and anyone can send
        // invitations or the sender is an admin or an owner, then send the invitation
        Message message = new Message();
        message.setFrom(role.getRoleAddress());
        message.setTo(to);

        if (((MultiUserChatServiceImpl)mucService).getMUCDelegate() != null) {
            switch(((MultiUserChatServiceImpl)mucService).getMUCDelegate().sendingInvitation(this, to, senderRole.getUserAddress(), reason)) {
                case HANDLED_BY_DELEGATE:
                    //if the delegate is taking care of it, there's nothing for us to do
                    return;
                case HANDLED_BY_OPENFIRE:
                    //continue as normal if we're asked to handle it
                    break;
                case REJECTED:
                    //we can't invite that person
                    throw new CannotBeInvitedException();
            }
        }

        // Add a list of extensions sent with the original message invitation (if any)
        if (extensions != null) {
            for(Element element : extensions) {
                element.setParent(null);
                message.getElement().add(element);
            }
        }
        Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user");
        // ChatUser will be null if the room itself (ie. via admin console) made the request
        if (senderRole.getUserAddress() != null) {
            frag.addElement("invite").addAttribute("from", senderRole.getUserAddress().toBareJID());
        }
        if (reason != null && reason.length() > 0) {
            Element invite = frag.element("invite");
            if (invite == null) {
                invite = frag.addElement("invite");
            }
            invite.addElement("reason").setText(reason);
        }
        if (isPasswordProtected()) {
            frag.addElement("password").setText(getPassword());
        }

        // Include the jabber:x:conference information for backward compatibility
        frag = message.addChildElement("x", "jabber:x:conference");
        frag.addAttribute("jid", role.getRoleAddress().toBareJID());

        // Send the message with the invitation
        router.route(message);
    }
    else {
        throw new ForbiddenException();
    }
}
 
Example 14
Source File: MUCRoomHistory.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new message and adds it to the history. The new message will be created based on
 * the provided information. This information will likely come from the database when loading
 * the room history from the database.
 *
 * @param senderJID the sender's JID of the message to add to the history.
 * @param nickname the sender's nickname of the message to add to the history.
 * @param sentDate the date when the message was sent to the room.
 * @param subject the subject included in the message.
 * @param body the body of the message.
 * @param stanza the stanza to add
 */
public void addOldMessage(String senderJID, String nickname, Date sentDate, String subject,
        String body, String stanza)
{
    Message message = new Message();
    message.setType(Message.Type.groupchat);
    if (stanza != null) {
        // payload initialized as XML string from DB
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        try {
            Element element = xmlReader.read(new StringReader(stanza)).getRootElement();
            for (Element child : (List<Element>)element.elements()) {
                Namespace ns = child.getNamespace();
                if (ns == null || ns.getURI().equals("jabber:client") || ns.getURI().equals("jabber:server")) {
                    continue;
                }
                Element added = message.addChildElement(child.getName(), child.getNamespaceURI());
                if (!child.getText().isEmpty()) {
                    added.setText(child.getText());
                }
                for (Attribute attr : (List<Attribute>)child.attributes()) {
                    added.addAttribute(attr.getQName(), attr.getValue());
                }
                for (Element el : (List<Element>)child.elements()) {
                    added.add(el.createCopy());
                }
            }
            if (element.attribute("id") != null) {
                message.setID(element.attributeValue("id"));
            }
        } catch (Exception ex) {
            Log.error("Failed to parse payload XML", ex);
        }
    }
    message.setSubject(subject);
    message.setBody(body);
    // Set the sender of the message
    if (nickname != null && nickname.trim().length() > 0) {
        JID roomJID = room.getRole().getRoleAddress();
        // Recreate the sender address based on the nickname and room's JID
        message.setFrom(new JID(roomJID.getNode(), roomJID.getDomain(), nickname, true));
    }
    else {
        // Set the room as the sender of the message
        message.setFrom(room.getRole().getRoleAddress());
    }

    // Add the delay information to the message
    Element delayInformation = message.addChildElement("delay", "urn:xmpp:delay");
    delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(sentDate));
    if (room.canAnyoneDiscoverJID()) {
        // Set the Full JID as the "from" attribute
        delayInformation.addAttribute("from", senderJID);
    }
    else {
        // Set the Room JID as the "from" attribute
        delayInformation.addAttribute("from", room.getRole().getRoleAddress().toString());
    }
    historyStrategy.addMessage(message);
}
 
Example 15
Source File: PacketCopier.java    From Openfire with Apache License 2.0 4 votes vote down vote up
private void processPackets() {
    List<InterceptedPacket> packets = new ArrayList<>(packetQueue.size());
    packetQueue.drainTo(packets);
    for (InterceptedPacket interceptedPacket : packets) {
        for (Map.Entry<String, Subscription> entry : subscribers.entrySet()) {
            boolean notify = false;
            String componentJID = entry.getKey();
            Subscription subscription = entry.getValue();

            if (subscription.isIncoming() == interceptedPacket.isIncoming() &&
                    subscription.isProcessed() == interceptedPacket.isProcessed()) {
                Class packetClass = interceptedPacket.getPacketClass();
                if (subscription.isPresenceEnabled() && packetClass == Presence.class) {
                    notify = true;
                }
                else if (subscription.isMessageEnabled() && packetClass == Message.class) {
                    notify = true;
                }
                else if (subscription.isIQEnabled() && packetClass == IQ.class) {
                    notify = true;
                }
            }

            if (notify) {
                try {
                    Message message = new Message();
                    message.setFrom(serverName);
                    message.setTo(componentJID);
                    Element childElement = message.addChildElement("copy",
                            "http://jabber.org/protocol/packet#event");
                    childElement.addAttribute("incoming", subscription.isIncoming() ? "true" : "false");
                    childElement.addAttribute("processed", subscription.isProcessed() ? "true" : "false");
                    childElement.addAttribute("date", XMPPDateTimeFormat.format(interceptedPacket.getCreationDate()));
                    childElement.add(interceptedPacket.getElement().createCopy());
                    // Send message notification to subscribed component
                    routingTable.routePacket(message.getTo(), message, true);
                }
                catch (Exception e) {
                    Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
                }
            }
        }
    }
}
 
Example 16
Source File: LeafNode.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Publishes the list of items to the node. Event notifications will be sent to subscribers
 * for the new published event. The published event may or may not include an item. When the
 * node is not persistent and does not require payloads then an item is not going to be created
 * nore included in the event notification.<p>
 *
 * When an affiliate has many subscriptions to the node, the affiliate will get a
 * notification for each set of items that affected the same list of subscriptions.<p>
 *
 * When an item is included in the published event then a new {@link PublishedItem} is
 * going to be created and added to the list of published item. Each published item will
 * have a unique ID in the node scope. The new published item will be added to the end
 * of the published list to keep the cronological order. When the max number of published
 * items is exceeded then the oldest published items will be removed.<p>
 *
 * For performance reasons the newly added published items and the deleted items (if any)
 * are saved to the database using a background thread. Sending event notifications to
 * node subscribers may also use another thread to ensure good performance.<p>
 *
 * @param publisher the full JID of the user that sent the new published event.
 * @param itemElements list of dom4j elements that contain info about the published items.
 */
public void publishItems(JID publisher, List<Element> itemElements) {
    List<PublishedItem> newPublishedItems = new ArrayList<>();
    if (isItemRequired()) {
        String itemID;
        Element payload;
        PublishedItem newItem;
        for (Element item : itemElements) {
            itemID = item.attributeValue("id");
            List entries = item.elements();
            payload = entries.isEmpty() ? null : (Element) entries.get(0);
            
            // Make sure that the published item has a unique ID if NOT assigned by publisher
            if (itemID == null) {
                itemID = UUID.randomUUID().toString();
            }

            // Create a new published item
            newItem = new PublishedItem(this, publisher, itemID, new Date(CacheFactory.getClusterTime()));
            newItem.setPayload(payload);
            // Add the new item to the list of published items
            newPublishedItems.add(newItem);
            setLastPublishedItem(newItem);
            // Add the new published item to the queue of items to add to the database. The
            // queue is going to be processed by another thread
            if (isPersistPublishedItems()) {
                PubSubPersistenceProviderManager.getInstance().getProvider().savePublishedItem(newItem);
            }
        }
    }

    // Build event notification packet to broadcast to subscribers
    Message message = new Message();
    Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
    // Broadcast event notification to subscribers and parent node subscribers
    Set<NodeAffiliate> affiliatesToNotify = new HashSet<>(affiliates);
    // Get affiliates that are subscribed to a parent in the hierarchy of parent nodes
    for (CollectionNode parentNode : getParents()) {
        for (NodeSubscription subscription : parentNode.getSubscriptions()) {
            affiliatesToNotify.add(subscription.getAffiliate());
        }
    }
    // TODO Use another thread for this (if # of subscribers is > X)????
    for (NodeAffiliate affiliate : affiliatesToNotify) {
        affiliate.sendPublishedNotifications(message, event, this, newPublishedItems);
    }
}