How to add a custom attribute (nickname) to your XMPP message tag in Smack 4.1

I want to add a custom attribute (nickname) to my XMPP chat message, for example the following example

<message from='*' to='*' id='123' nick='KASHIF' type='chat'><body>hello</body></message> 

I know XMPP is not recommended , but this is my requirement, since this attribute (nick) is already implemented in the iOS version of the application in which I work on.

+5
source share
2 answers

To do this, you need to edit the 2 classes of Smack 4.1

  • Stanza class ( org.jivesoftware.smack.packet )
  • PacketParserUtils class in ( org.jivesoftware.smack.util )

1. Stanza class

Define your custom attribute ( nick )

  private String nick = null; 

Define Getter and Setters

 public String getNick() { return this.nick; } public void setNick(String paramString) { this.nick = paramString; } 

Edit Constructor Stanza

 protected Stanza(Stanza p) { //add this line nick = p.getNick(); } 

Change the addCommonAttributes method

 protected void addCommonAttributes(XmlStringBuilder xml) { //add this line if(getNick()!= null) xml.optAttribute("nick", getNick()); } 

2. Class PacketParserUtils

Change parseMessage method

  public static Message parseMessage(XmlPullParser parser) throws XmlPullParserException, IOException, SmackException { //add this line message.setNick(parser.getAttributeValue("", "nick")); } 

Now you can simply set the nickname and send the message as follows

 Message message = new Message(); message.setType(Message.Type.chat); message.setStanzaId("123"); message.setTo(number); message.setNick("SHAYAN"); try { connection.sendStanza(message); } catch (NotConnectedException e) { } 
+3
source

Do not do this, it is not recommended for any reason. Probably, some servers will deprive the attribute or even completely refuse to process the packet. Instead, we recommend adding a custom element.

In fact, such an extension already exists, XEP-0172 :

 <message from='*' to='*' id='123' type='chat'> <nick xmlns='http://jabber.org/protocol/nick'>KASHIF</nick> <body>hello</body> </message> 

This may work already with other clients or libraries, so this is a much better solution.

+4
source

All Articles