Java Code Examples for org.xmpp.packet.Message

The following examples show how to use org.xmpp.packet.Message. 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: StanzaIDUtilTest.java    License: 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 2
Source Project: Openfire   Source File: StanzaIDUtilTest.java    License: 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 3
Source Project: Openfire   Source File: HttpSessionDeliverable.java    License: 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 4
Source Project: Openfire   Source File: StanzaIDUtilTest.java    License: 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 5
Source Project: Openfire   Source File: StanzaIDUtilTest.java    License: 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 6
Source Project: Openfire   Source File: HttpSessionDeliverable.java    License: 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 7
Source Project: Openfire   Source File: PacketCopier.java    License: 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 8
Source Project: Openfire   Source File: StanzaIDUtilTest.java    License: 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 9
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 10
Source Project: Openfire   Source File: HttpSessionDeliverable.java    License: 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 11
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 12
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 13
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 14
/**
 * 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 15
Source Project: Openfire   Source File: OfflineMessageStoreTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotStoreHeadlineMessages() {
    // XEP-0160: "headline" message types SHOULD NOT be stored offline
    Message message = new Message();
    message.setType(Message.Type.headline);
    assertFalse(OfflineMessageStore.shouldStoreMessage(message));
}
 
Example 16
Source Project: Openfire   Source File: XMPPServer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Asynchronously send a message to every administrator on the system.
 *
 * @param message The message to send
 * @return the future result of sending the message.
 */
public Future<?> sendMessageToAdmins(final String message) {
    return TaskEngine.getInstance().submit(() -> {
        final MessageRouter messageRouter = getMessageRouter();
        final Collection<JID> admins = XMPPServer.getInstance().getAdmins();
        final Message notification = new Message();
        notification.setFrom(getServerInfo().getXMPPDomain());
        notification.setBody(message);
        admins.forEach(jid -> {
            logger.debug("Sending message to admin [jid={}, message={}]", jid, message);
            notification.setTo(jid);
            messageRouter.route(notification);
        });
    });
}
 
Example 17
Source Project: onos   Source File: XmppControllerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void processUpstreamEvent(XmppDeviceId deviceId, Packet packet) {
    if (packet instanceof IQ) {
        IQ iq = (IQ) packet;
        String namespace = iq.getChildElement().getNamespace().getURI();
        notifyIqListeners(iq, namespace);
    }
    if (packet instanceof Message) {
        notifyMessageListeners((Message) packet);
    }
    if (packet instanceof Presence) {
        notifyPresenceListeners((Presence) packet);
    }
}
 
Example 18
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 19
Source Project: Openfire   Source File: MultiUserChatServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void logConversation(final MUCRoom room, final Message message, final JID sender) {
    // Only log messages that have a subject or body. Otherwise ignore it.
    if (message.getSubject() != null || message.getBody() != null) {
        getArchiver().archive( new ConversationLogEntry( new Date(), room, message, sender) );
    }
}
 
Example 20
Source Project: Openfire   Source File: IQMUCvCardHandler.java    License: 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 21
Source Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sends the room history to a user that just joined the room.
 */
private void sendRoomHistoryAfterJoin( @Nonnull final LocalMUCUser user, @Nonnull MUCRole joinRole, @Nullable HistoryRequest historyRequest )
{
    if (historyRequest == null) {
        Log.trace( "Sending default room history to user '{}' that joined room '{}'.", user.getAddress(), this.getJID() );
        final Iterator<Message> history = roomHistory.getMessageHistory();
        while (history.hasNext()) {
            joinRole.send(history.next());
        }
    } else {
        Log.trace( "Sending user-requested room history to user '{}' that joined room '{}'.", user.getAddress(), this.getJID() );
        historyRequest.sendHistory(joinRole, roomHistory);
    }
}
 
Example 22
Source Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serverBroadcast(String msg) {
    Message message = new Message();
    message.setType(Message.Type.groupchat);
    message.setBody(msg);
    message.setFrom(role.getRoleAddress());
    broadcast(message, role);
}
 
Example 23
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 24
Source Project: onos   Source File: XmppDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRecognizePacket() throws Exception {
    Packet iqPacket = xmppDecoder.recognizeAndReturnXmppPacket(iqElement);
    assertThat(iqPacket, is(instanceOf(IQ.class)));
    Packet messagePacket = xmppDecoder.recognizeAndReturnXmppPacket(messageElement);
    assertThat(messagePacket, is(instanceOf(Message.class)));
    Packet presencePacket = xmppDecoder.recognizeAndReturnXmppPacket(presenceElement);
    assertThat(presencePacket, is(instanceOf(Presence.class)));
    Element wrongElement = new DefaultElement("test");
    try {
        xmppDecoder.recognizeAndReturnXmppPacket(wrongElement);
    } catch (Exception e) {
        assertThat(e, is(instanceOf(UnsupportedStanzaTypeException.class)));
    }
}
 
Example 25
Source Project: Openfire   Source File: OfflineMessageStoreTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldStoreEmptyChatMessagesWithOtherExtensions() {
    Message message = new Message();
    message.setType(Message.Type.chat);
    PacketExtension chatState = new PacketExtension("composing", "http://jabber.org/protocol/chatstates");
    message.addExtension(chatState);
    PacketExtension packetExtension2 = new PacketExtension("received", "urn:xmpp:receipts");
    message.addExtension(packetExtension2);
    assertTrue(OfflineMessageStore.shouldStoreMessage(message));
}
 
Example 26
Source Project: Openfire   Source File: MessageCarbonsTest.java    License: 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 27
Source Project: Openfire   Source File: HistoryStrategy.java    License: 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 Project: Openfire   Source File: PubSubModule.java    License: 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 29
Source Project: Openfire   Source File: PubSubModule.java    License: 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);
}
 
Example 30
Source Project: Openfire   Source File: StanzaIDUtilTest.java    License: 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 );
}