0

my addAsyncStanzaListner is being called when an ack message is received from Firebase Cloud Messaging services. I need to ack this messages according to the docs. The problem that I am having is I can't reach the "message_type" "key"/"value" pair inside the JSON object that arrives inside the message stanza that's received. Could you please help me in accessing this important value/pair. I am using Smack Library 4.1. I've been following this post answer for this setup, but somehow It doesn't work: GCM XMPP Server using Smack 4.1.0

Here's how the code is looking like:

other_connection.addAsyncStanzaListener(new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws    SmackException.NotConnectedException {
//how should i convert this stanza into a message stanza
//I have tried Message message = (Message)packet;   IT DOESNT WORK
//I have tried getting the extension with the GCM Namespace. It doesnt
//return a json string       
Community
  • 1
  • 1
i_o
  • 777
  • 9
  • 25
  • Since you are using the smack library, have a look at this sample which uses smack 4.1. https://github.com/googlesamples/friendlyping/blob/master/server/Java/src/main/java/com/gcm/samples/friendlyping/SmackCcsClient.java#L111 – Arthur Thompson Aug 04 '16 at 16:55

2 Answers2

0

In your code you just recive a Stanza as Java Object.

Stanza has a method to output an XML.

You can use this method to obtain a JSON if you need, just add some custom functionality.

Following this example

your code can looks like this:

@Override
public void processPacket(Stanza packet) throws    SmackException.NotConnectedException {
    JSONObject jsonObj = XML.toJSONObject(packet.toXML());
    String json = jsonObj.toString();
//foo
Community
  • 1
  • 1
MrPk
  • 2,862
  • 2
  • 20
  • 26
0

Note: This answer is for the general problem of extracting JSON from a message. In the case of FCM, it's possible that there's another method that's more appropriate.

Suppose your have a Stanza object that corresponds to the following XML:

<message from='a@example.com' to='b@example.com' type='normal'>
    <json xmlns='urn:xmpp:json:0'>{ "key1" : "value1", "key2": "value2" }</json>
    <body/>
</message>

To extract the JSON string, you need to do:

import org.jivesoftware.smackx.json.packet.JsonPacketExtension;
...
JsonPacketExtension jsonPacketExtension = JsonPacketExtension.from(stanza);
String contentJson = jsonPacketExtension.getJson();
Chrispher
  • 373
  • 2
  • 7