org.xmpp.packet.Message Java Examples

The following examples show how to use org.xmpp.packet.Message. 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: StanzaIDUtilTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil#findFirstUniqueAndStableStanzaID(Packet, String)} can parse a stanza that contains a
 * stanza ID.
 */
@Test
public void testParseUUIDValue() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );
    final String expected = "de305d54-75b4-431b-adb2-eb6b9e546013";
    final Element toOverwrite = input.getElement().addElement( "stanza-id", "urn:xmpp:sid:0" );
    toOverwrite.addAttribute( "id", expected );
    toOverwrite.addAttribute( "by", self.toString() );

    // Execute system under test.
    final String result = StanzaIDUtil.findFirstUniqueAndStableStanzaID( input, self.toString() );

    // Verify results.
    assertEquals( expected, result );
}
 
Example #2
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 #3
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 #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: 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 #6
Source File: StanzaIDUtilTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil.generateUniqueAndStableStanzaID} generates a UUID value
 * if the provided input does not have a 'origin-id' value
 */
@Test
public void testGenerateUUIDWhenNoOriginIDPresent() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();

    // Execute system under test.
    final String result = StanzaIDUtil.generateUniqueAndStableStanzaID( input );

    // Verify results.
    Assert.assertNotNull( result );
    try
    {
        UUID.fromString( result );
    }
    catch ( IllegalArgumentException ex )
    {
        Assert.fail();
    }
}
 
Example #7
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 #8
Source File: PacketCopier.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
        throws PacketRejectedException {
    // Queue intercepted packet only if there are subscribers interested
    if (!subscribers.isEmpty()) {
        boolean queue = false;
        Class packetClass = packet.getClass();
        for (Subscription subscription : subscribers.values()) {
            if (subscription.isPresenceEnabled() && packetClass == Presence.class) {
                queue = true;
            }
            else if (subscription.isMessageEnabled() && packetClass == Message.class) {
                queue = true;
            }
            else if (subscription.isIQEnabled() && packetClass == IQ.class) {
                queue = true;
            }
        }
        if (queue) {
            // Queue packet with extra information and let the background thread process it
            packetQueue.add(new InterceptedPacket(packet, incoming, processed));
        }
    }
}
 
Example #9
Source File: StanzaIDUtilTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil#findFirstUniqueAndStableStanzaID(Packet, String)} can parse a stanza that contains a
 * stanza ID that is not a UUID value. OF-2026
 */
@Test
public void testParseNonUUIDValue() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );
    final String expected = "not-a-uuid";
    final Element toOverwrite = input.getElement().addElement( "stanza-id", "urn:xmpp:sid:0" );
    toOverwrite.addAttribute( "id", expected );
    toOverwrite.addAttribute( "by", self.toString() );

    // Execute system under test.
    final String result = StanzaIDUtil.findFirstUniqueAndStableStanzaID( input, self.toString() );

    // Verify results.
    assertEquals( expected, result );
}
 
Example #10
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 (that do not have a child element)
 *
 * @see <a href="https://igniterealtime.org/issues/browse/OF-1087">OF-1087</a>
 */
@Test
public void testNamespaceOnEmptyStanzaWithoutChildElement() throws Exception
{
    // Setup fixture
    final Message message = new Message();
    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\"/>", result );
}
 
Example #11
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 #12
Source File: StanzaIDUtilTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil.ensureUniqueAndStableStanzaID} adds a stanza-id element
 * with proper 'by' and UUID value if the provided input does not have a 'origin-id'
 * element.
 */
@Test
public void testGeneratesStanzaIDElement() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );

    // Execute system under test.
    final Packet result = StanzaIDUtil.ensureUniqueAndStableStanzaID( input, self );

    // Verify results.
    Assert.assertNotNull( result );
    final Element stanzaIDElement = result.getElement().element( QName.get( "stanza-id", "urn:xmpp:sid:0" ) );
    Assert.assertNotNull( stanzaIDElement );
    try
    {
        UUID.fromString( stanzaIDElement.attributeValue( "id" ) );
    }
    catch ( IllegalArgumentException ex )
    {
        Assert.fail();
    }
    assertEquals( self.toString(), stanzaIDElement.attributeValue( "by" ) );
}
 
Example #13
Source File: StanzaIDUtilTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil.ensureUniqueAndStableStanzaID} does not overwrites
 * a stanza-id element when another is present with a different 'by' value.
 */
@Test
public void testDontOverwriteStanzaIDElement() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );
    final String notExpected = "de305d54-75b4-431b-adb2-eb6b9e546013";
    final Element toOverwrite = input.getElement().addElement( "stanza-id", "urn:xmpp:sid:0" );
    toOverwrite.addAttribute( "by", new JID( "someoneelse" ).toString() );
    toOverwrite.addAttribute( "id", notExpected );

    // Execute system under test.
    final Packet result = StanzaIDUtil.ensureUniqueAndStableStanzaID( input, self );

    // Verify results.
    Assert.assertNotNull( result );
    final List<Element> elements = result.getElement().elements( QName.get( "stanza-id", "urn:xmpp:sid:0" ) );
    assertEquals( 2, elements.size() );
}
 
Example #14
Source File: ForwardTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Test
public void testForwarded() {
    Message message = new Message();
    message.setType(Message.Type.chat);
    message.setBody("Tests");
    message.addExtension(new DataForm(DataForm.Type.submit));

    Forwarded forwarded = new Forwarded(message);
    Forwarded forwarded2 = new Forwarded(message);
    String xml1 = forwarded.getElement().asXML();
    String xml2 = forwarded2.getElement().asXML();
    assertEquals("<forwarded xmlns=\"urn:xmpp:forward:0\"><message xmlns=\"jabber:client\" type=\"chat\"><body>Tests</body><x xmlns=\"jabber:x:data\" type=\"submit\"/></message></forwarded>", xml1);
    assertEquals("<forwarded xmlns=\"urn:xmpp:forward:0\"><message xmlns=\"jabber:client\" type=\"chat\"><body>Tests</body><x xmlns=\"jabber:x:data\" type=\"submit\"/></message></forwarded>", xml2);
}
 
Example #15
Source File: OfflineMessageStoreTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldStoreNormalMessages() {
    // XEP-0160: Messages with a 'type' attribute whose value is "normal" (or messages with no 'type' attribute) SHOULD be stored offline.
    Message message = new Message();
    message.setType(Message.Type.normal);
    assertTrue(OfflineMessageStore.shouldStoreMessage(message));

    Message message2 = new Message();
    assertTrue(OfflineMessageStore.shouldStoreMessage(message2));
}
 
Example #16
Source File: StanzaIDUtilTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil.generateUniqueAndStableStanzaID} uses the 'origin-id' provided value,
 * if that's present, even when the value is not a UUID.
 */
@Test
public void testUseOriginIDWhenPresentNonUUID() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final String expected = "not-a-uuid";
    input.getElement().addElement( "origin-id", "urn:xmpp:sid:0" ).addAttribute( "id", expected );

    // Execute system under test.
    final String result = StanzaIDUtil.generateUniqueAndStableStanzaID( input );

    // Verify results.
    assertEquals( expected, result );
}
 
Example #17
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 #18
Source File: OfflineMessageStrategy.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void store(Message message) {
    final boolean stored = messageStore.addMessage(message);
    // Inform listeners that an offline message was stored
    if (stored && !listeners.isEmpty()) {
        for (OfflineMessageListener listener : listeners) {
            try {
                listener.messageStored(message);    
            } catch (Exception e) {
                Log.warn("An exception occurred while dispatching a 'messageStored' event!", e);
            }
        }
    }
}
 
Example #19
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 #20
Source File: PEPService.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void broadcast(Node node, Message message, Collection<JID> jids) {
    if ( Log.isTraceEnabled() ) {
        Log.trace( "Service '{}' is broadcasting a notification on node '{}' to a collection of JIDs: {}", this.getServiceID(), node.getUniqueIdentifier().getNodeId(), jids.stream().map(JID::toString).collect(Collectors.joining(", ")) );
    }
    message.setFrom(getAddress());
    for (JID jid : jids) {
        message.setTo(jid);
        message.setID(StringUtils.randomString(8));
        router.route(message);
    }
}
 
Example #21
Source File: NodeAffiliate.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an event notification to the affiliate for the deleted items. The event
 * notification may contain one or many published items based on the items included
 * in the original publication. If the affiliate has many subscriptions and many
 * items were deleted then the affiliate will get a notification for each set
 * of items that affected the same subscriptions.
 *
 * @param notification the message to sent to the subscribers. The message will be completed
 *        with the items to include in each notification.
 * @param event the event Element included in the notification message. Passed as an
 *        optimization to avoid future look ups.
 * @param leafNode the leaf node where the items where deleted from.
 * @param publishedItems the list of items that were deleted.
 */
void sendDeletionNotifications(Message notification, Element event, LeafNode leafNode,
        List<PublishedItem> publishedItems) {

    if (!publishedItems.isEmpty()) {
        Map<List<NodeSubscription>, List<PublishedItem>> itemsBySubs =
                getItemsBySubscriptions(leafNode, publishedItems);

        // Send one notification for published items that affect the same subscriptions
        for (List<NodeSubscription> nodeSubscriptions : itemsBySubs.keySet()) {
            // Add items information
            Element items = event.addElement("items");
            items.addAttribute("node", leafNode.getUniqueIdentifier().getNodeId());
            for (PublishedItem publishedItem : itemsBySubs.get(nodeSubscriptions)) {
                // Add retract information to the event notification
                Element item = items.addElement("retract");
                if (leafNode.isItemRequired()) {
                    item.addAttribute("id", publishedItem.getID());
                }
            }
            // Send the event notification
            sendEventNotification(notification, nodeSubscriptions);
            // Remove the added items information
            event.remove(items);
        }
    }
}
 
Example #22
Source File: OfflineMessageStoreTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotStoreEmptyChatMessagesWithOnlyChatStatesAndThread() {
    Message message = new Message();
    message.setType(Message.Type.chat);
    message.setThread("1234");
    PacketExtension chatState = new PacketExtension("composing", "http://jabber.org/protocol/chatstates");
    message.addExtension(chatState);
    assertFalse(OfflineMessageStore.shouldStoreMessage(message));
}
 
Example #23
Source File: PubSubModule.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void broadcast(Node node, Message message, Collection<JID> jids) {
    // TODO Possibly use a thread pool for sending packets (based on the jids size)
    message.setFrom(getAddress());
    for (JID jid : jids) {
        message.setTo(jid);
        message.setID(StringUtils.randomString(8));
        router.route(message);
    }
}
 
Example #24
Source File: CollectionNode.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void broadcastCollectionNodeEvent(Node child, Message notification) {
    // Get affected subscriptions (of this node and all parent nodes)
    Collection<NodeSubscription> subscriptions = new ArrayList<>();
    subscriptions.addAll(getSubscriptions(child));
    for (CollectionNode parentNode : getParents()) {
        subscriptions.addAll(parentNode.getSubscriptions(child));
    }
    // TODO Possibly use a thread pool for sending packets (based on the jids size)
    for (NodeSubscription subscription : subscriptions) {
        getService().sendNotification(subscription.getNode(), notification, subscription.getJID());
    }
}
 
Example #25
Source File: SessionManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Change the priority of a session, that was already available, associated with the sender.
 *
 * @param session   The session whose presence priority has been modified
 * @param oldPriority The old priority for the session
 */
public void changePriority(LocalClientSession session, int oldPriority) {
    if (session.getAuthToken().isAnonymous()) {
        // Do nothing if the session belongs to an anonymous user
        return;
    }
    int newPriority = session.getPresence().getPriority();
    if (newPriority < 0 || oldPriority >= 0) {
        // Do nothing if new presence priority is not positive and old presence negative
        return;
    }

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

    // User sessions had negative presence before this change so deliver messages
    if (!session.isAnonymousUser() && session.canFloodOfflineMessages()) {
        OfflineMessageStore messageStore = server.getOfflineMessageStore();
        Collection<OfflineMessage> messages = messageStore.getMessages(session.getAuthToken().getUsername(), true);
        for (Message message : messages) {
            session.process(message);
        }
    }
}
 
Example #26
Source File: SessionManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a message with a given subject and body to one or more user sessions related to the
 * specified address. If address is null or the address's node is null then the message will be
 * sent to all the user sessions. But if the address includes a node but no resource then
 * the message will be sent to all the user sessions of the requeted user (defined by the node).
 * Finally, if the address is a full JID then the message will be sent to the session associated
 * to the full JID. If no session is found then the message is not sent.
 *
 * @param address the address that defines the sessions that will receive the message.
 * @param subject the subject to broadcast.
 * @param body    the body to broadcast.
 */
public void sendServerMessage(JID address, String subject, String body) {
    Message packet = createServerMessage(subject, body);
    if (address == null || address.getNode() == null || !userManager.isRegisteredUser(address)) {
        broadcast(packet);
    }
    else if (address.getResource() == null || address.getResource().length() < 1) {
        userBroadcast(address.getNode(), packet);
    }
    else {
        routingTable.routePacket(address, packet, true);
    }
}
 
Example #27
Source File: HistoryStrategy.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Obtain the current history as an iterator of messages to play back to a new room member.
 * 
 * @return An iterator of Message objects to be sent to the new room member.
 */
public Iterator<Message> getMessageHistory(){
    LinkedList<Message> list = new LinkedList<>(history);
    // Sort messages. Messages may be out of order when running inside of a cluster
    Collections.sort(list, new MessageComparator());
    return list.iterator();
}
 
Example #28
Source File: MessageCarbonsTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Test
public void testReceived() {
    Message message = new Message();
    message.setType(Message.Type.chat);
    message.setBody("Tests");

    Forwarded forwarded = new Forwarded(message);

    Received received = new Received(forwarded);
    String xml = received.getElement().asXML();
    assertEquals("<received xmlns=\"urn:xmpp:carbons:2\"><forwarded xmlns=\"urn:xmpp:forward:0\"><message xmlns=\"jabber:client\" type=\"chat\"><body>Tests</body></message></forwarded></received>", xml);
}
 
Example #29
Source File: BookmarkInterceptor.java    From openfire-ofmeet-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * XEP-0048 'Bookmarks' describes a storage element that contains the list of bookmarks that we intend to
 * add to in this method. Such a storage element can be transmitted in a number of different ways, including
 * XEP-0049 "Private XML Storage" and XEP-0223 "Persistent Storage of Private Data via PubSub".
 *
 * @param packet The packet in which to search for a 'storage' element (cannot be null).
 * @return The storage element, or null when no such element was found.
 */
static Element findStorageElement( final Packet packet )
{
    if ( packet instanceof IQ )
    {
        final IQ iq = (IQ) packet;
        final Element childElement = iq.getChildElement();
        if ( childElement == null || iq.getType() != IQ.Type.result )
        {
            return null;
        }

        switch ( childElement.getNamespaceURI() )
        {
            // A "Private XML Storage (XEP-0049) Bookmarks" result stanza.
            case "jabber:iq:private":
                return findStorageElementInPrivateXmlStorage( childElement );

            // a "Persistent Storage of Private Data via PubSub (XEP-0048 / XEP-0223)" Bookmarks result.
            case "http://jabber.org/protocol/pubsub":
                return findStorageElementInPubsub( childElement );

            default:
                return null;
        }
    }

    if ( packet instanceof Message )
    {
        final Message message = (Message) packet;

        // Check for a "Persistent Storage of Private Data via PubSub (XEP-0048 / XEP-0223)" Bookmarks event notification.
        return findStorageElementInPubsub( message.getChildElement( "event", "http://jabber.org/protocol/pubsub#event" ) );
    }

    return null;
}
 
Example #30
Source File: PubSubModule.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void sendNotification(Node node, Message message, JID jid) {
    message.setFrom(getAddress());
    message.setTo(jid);
    message.setID(StringUtils.randomString(8));
    router.route(message);
}