I am new to CometD and I was successfully building it which passes value with Map<String, Object>
. However, when I want to pass value with POJO(of course in JSON way), the problem occurs.
I am now publish JSONObject from Client and the Server will directly deliver the data back, so the Client will receive the data it published:
POJO to be published (Simply POJO with 2 elements and corresponding getter/setter) :
public class TestObject {
int pxid;
boolean isInService;
public TestObject() {
}
public TestObject(int pxid, boolean isInService) {
this.pxid = pxid;
this.isInService = isInService;
}
//getters and setters below...
}
In Server Side(Simply deliver the data back to the Client):
public EchoService(BayeuxServer bayeuxServer) {
super(bayeuxServer, "echo");
addService("/echo", "processEcho");
}
public void processEcho(ServerSession remote, Map<String, Object> data) {
System.out.println("in PROCESSECHO"+data.toString());
remote.deliver(getServerSession(), "/echo", data, null);
}
In Client:
public void createObjAndSend(){
TestObject newPX1 = new TestObject(5, false);
JSONObject pxJsonObj=JSONObject.fromObject(newPX1);
sendMsgInJson(pxJsonObj,NODE_CHANNEL);
}
private void sendMsgInJson(JSONObject jsonObj, String channel) {
ClientSessionChannel nodeChannel = client.getChannel(channel);
nodeChannel.publish(jsonObj, new ClientSessionChannel.MessageListener() {
@Override
public void onMessage(ClientSessionChannel csc, Message msg) {
if (!msg.isSuccessful()) {
System.out.println("not published ok.");
} else {
System.out.println("published ok");
}
}
});
}
private class NodeLsnr implements ClientSessionChannel.MessageListener {
@Override
public void onMessage(ClientSessionChannel csc, Message msg) {
String JSONstr = msg.getJSON();
System.out.println("Receive JSON:"+JSONstr);
JSONObject jsonObj = JSONObject.fromObject(JSONstr);
System.out.println("jsonObj:" +jsonObj.toString());
}
}
It works fine until the Client receive the data it passed to Server.
In the method onMessage
in the NodeLsnr
inner class,it do print the JSONstr
like:
Receive JSON:{"data":{"isInService":false,"pxid":5},"channel":"/echo"}
However, it's stuck when I want to transfer JSON string to JSONObject with this line:
JSONObject jsonObj = JSONObject.fromObject(JSONstr);
When I say "stuck", I mean there's no Exception nor the jsonObj printed(as I wanted), instead, it happens nothing.
Any thoughts? Thanks in advance.
P.S. I DID study the official site of the CometD like this, but I can't understand it well.
If my approach wan't make sense, what is the correct/suggest way?
Update
Instead of
JSONObject jsonObj = JSONObject.fromObject(JSONstr);
, I also tried
JSONObject jsonObj=(JSONObject) JSONSerializer.toJSON( JSONstr );
but still in vain...