Sunday, January 10, 2010

using xmpp in google app engine

 

 

To enable the XMPP service for a Java app, edit the appengine-web.xml file and include the following lines:

  <inbound-services>      <service>xmpp_message</service>    </inbound-services>


With the XMPP service enabled, when App Engine receives a chat message for the app, it makes an HTTP POST request to the following URL path:



/_ah/xmpp/message/chat/



To handle incoming messages, you simply create a request handler that accepts POST requests at this URL path.



package com.zpylxapp.xmpp;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

@SuppressWarnings("serial")
public class XMPPReceiverServlet extends HttpServlet {

public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException {
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
Message message = xmpp.parseMessage(req);

JID fromJid = message.getFromJid();
String body = message.getBody();

System.out.println(body + fromJid);

// Create a response
String response = "echo: " + body;
System.out.println(fromJid.getId() + " <-- JEliza: " + response);
// Send out response
message = new MessageBuilder().withRecipientJids(fromJid).withBody(
response).build();
xmpp.sendMessage(message);
}

}



To map this servlet to the XMPP URL path, put the following section in your web.xml file, inside the <web-app> element:



    <servlet>
<servlet-name>xmppreceiver</servlet-name>
<servlet-class>com.zpylxapp.xmpp.XMPPReceiverServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xmppreceiver</servlet-name>
<url-pattern>/_ah/xmpp/message/chat/</url-pattern>
</servlet-mapping>

No comments:

Post a Comment