How to add custom XML element to Message using PacketInterceptor in Openfire plugin using XMPP

623 views Asked by At

I want to add custom XML to an incoming message packet. To do that as part of plugin implementation I have written a PacketInterceptor, which intercepts the message and adds an extension. Till this point everything is fine but when this message is received by the receiver, the information stored in custom xml is striped off. Only the xml element with namespaces is shown.

Incoming messages are regular text messages as shown below-

<message to='18@mcasax01/SomeResource' from='[email protected]/testbot2' id='63S0G-27' type='groupchat'>

     <body>Hi</body>

</message>

When I add custom XML to this message body, it looks as below after adding the XML in PacketInterceptor logs-

<message to='18@mcasax01/SomeResource' from='[email protected]/testbot2' id='63S0G-27' type='groupchat'>

     <body>Hi</body>

     <data value="imgURL1"/>

</message>

But when this message is received by the receiver the value attribute in data is striped off and below message is received by the participant -

<message to='17@mcasax01/SomeResource' from='[email protected]/testbot2' id='63S0G-27' type='groupchat'>

     <body>Hi</body>

     <data xmlns='jabber:client'></data>

</message>

Please note that both the text and attributes are getting stripped off from data XML node.

Below is java code snippet for your reference

public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException {

    // Some code

    Message messagePacket = (Message) packet;
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("data");
    Element root1 = root.addAttribute("value", "imgURL1");
    PacketExtension pe = new PacketExtension(root1);
    messagePacket.addExtension(pe);

}
1

There are 1 answers

0
JaredHatfield On

When implementing the interceptPacket method you need to pay careful attention to the different parameters. The same XMPP packet will be intercepted multiple times. Make sure you are only intercepting incoming packets that are not processed. You do this by writing a conditional on the boolean values passed to the method.

As for ensuring the XML is created properly, you should use the addChildElement method not the addExtension method on the Message object. I've successfully used the addChildElement method before to add a timestamp to the XMPP message before it is sent to the receiver. The API for addChildElement is straightforward and avoids you having to create an entirely new document.