public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException {
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
// receive message
Message message = xmpp.parseMessage(req);
JID from = message.getFromJid();
JID[] recipients = message.getRecipientJids();
JID to = (recipients.length > 0) ? recipients[0] : null;
String body = message.getBody();
if (body != null && body.startsWith("{") || body.trim().startsWith("{")) {
// the body contains a JSON object
ObjectNode json = null;
try {
String agentUrl = "xmpp:" + to.getId();
String agentId = xmppService != null ? xmppService.getAgentId(agentUrl) : null;
json = JOM.getInstance().readValue(body, ObjectNode.class);
if (isResponse(json)) {
// TODO: handle response
}
else if (isRequest(json)) {
// this is a request
// append the sender to the request parameters
RequestParams params = new RequestParams();
params.put(Sender.class, from.getId());
// TODO: cleanup logger info
logger.info("request agentUrl =" + agentUrl + ", agentId=" + agentId + " request=" + json + ", sender=" + from.getId());
// invoke the agent
JSONRequest request = new JSONRequest(json);
JSONResponse response = agentFactory.receive(agentId, request, params);
// reply to message
Message msg = new MessageBuilder()
.withRecipientJids(from)
.withFromJid(to)
.withBody(response.toString())
.build();
xmpp.sendMessage(msg);
}
else {
throw new Exception("Request does not contain a valid JSON-RPC request or response");
}
}
catch (Exception err) {
// generate JSON error response
JSONRPCException jsonError = new JSONRPCException(
JSONRPCException.CODE.INTERNAL_ERROR, err.getMessage());
JSONResponse response = new JSONResponse(jsonError);
// send exception as response
Message msg = new MessageBuilder()
.withRecipientJids(from)
.withFromJid(to)
.withBody(response.toString())
.build();
xmpp.sendMessage(msg);