Sunday, November 29, 2009

Google App Engine XMPP Services Example



Google App Engine released the XMPP Services a while ago. The service started very basic and bad, but since then, it is improving a lot and have potential to be really worthy to build XMPP Services over it.
Unfortunately currently you might only be able to write bots. Which is not that bad specially for developers that are starting with XMPP and App Engine.

The documentation is not that good so far, but it was enough to create an EchoBot Demo App, you can download the full source here.
To use it, just explode the folder, make sure you have Google App Engine SDK configured, set your application ID, and deploy.
I strongly recommend to use Eclipse AppEngine Plugin for those tasks.

Quick Tutorial

Receiving Messages are handled by your application like an HTTP Post Request:
@SuppressWarnings("serial")
public class XmppbotServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException {


Parsing Received Messages is piece of cake. AppEngine API is handy in that sense:
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
        Message message = xmpp.parseMessage(req);


Creating a Response Message is also very simple:
JID fromJid = message.getFromJid();
String body = message.getBody();

// Create an Echo Message
Message response = new MessageBuilder().withMessageType(
message.getMessageType()).withBody(body)
.withRecipientJids(fromJid).build();


Now we send it back, without any specialist XMPP Knowledge required.
boolean messageSent = false;
SendResponse status = xmpp.sendMessage(response);
messageSent = (status.getStatusMap().get(fromJid) == SendResponse.Status.SUCCESS);

if (!messageSent) {
// An Error Occurred
}


Now you can create an XMPP Bot with just a few line of simple Java code.
Remarks:

  • Your Bot will auto accept every XMPP contact add request, which is quite handy too. To test your Bot, just open your XMPP Account in your preferred Client. And add the contact: YourAppName@appspotchat.com
  • It will auto-accept your request, and if your service is running, it will be shown as available.
  • You can also use aliases like: Whatever@YourAppName.appspotchat.com

1 comment:

  1. Download link doesnt work for me :(

    ReplyDelete