Skip to main content

Jabber

Instant messaging for e-business

Gerhard Poul (gpoul@eunet.at), Freelance writer
Gerhard Poul is an IT contractor in Vienna, Austria. You can contact Gerhard at gpoul@eunet.at.

Summary:  In this article, Gerhard Poul shows how XML-based Jabber fits into today's e-business infrastructure, lighting instant messaging in a whole new way. You'll see that you can use Jabber to integrate your existing e-business into a more dynamic and personal environment. Your e-business site will be able to communicate with its users faster and integrate itself into their lives -- and you'll have fun learning and playing with what Jabber offers.

Date:  01 May 2002
Level:  Intermediate
Activity:  1482 views

Fun is very important here, so I'm going to show you one way of integrating Jabber instant messaging into a state-of-the-art e-business environment, and at the same time share some insights that will leave you ready to play with Jabber yourself after you finish reading this article.

Jabber, if you're not familiar with it, is an open, XML-based protocol for instant messaging and presence, supported by the non-profit Jabber Software Foundation. I'll outline its most basic characteristics, but the focus here is less on the architecture, and more on getting familiar with Jabber in order to get the most out of it in your application.

Here, I use a simple example of a state of the art e-business environment. We have three tiers:

  • The Internet tier, which is not part of our system, but allows users to access the system
  • The Web tier, which contains our Web servers and relays to the Internet layer
  • The Application tier, which contains our application and database servers

Advantages of using Jabber:

  • The published protocol is implemented in free software.
  • You can reach users in all instant messaging systems by using Jabber's instant messaging gateway modules. You only have to program to one interface and Jabber takes care of the distribution throughout all major messaging systems.
  • Jabber is resource-aware. The same user can connect to Jabber with multiple clients and messages will be routed accordingly.

The challenge

One of the biggest problems in e-business systems today is that the only way to communicate with customers is either fast and one-way via Web pages, or two-way and slow via e-mail. None of these ways is really interactive and most businesses rely on phones if they need to get a response instantly.

The three-tier environment I described above has one inherent problem: To be secure, the application server is hidden behind firewalls that protect it. Unfortunately, to send e-mails or instant messages, we have to work around that. It is common practice to use an SMTP relay to forward messages generated by the application server to the Internet. We don't want to reinvent the wheel, but, rather, to build on a common pattern; so let's build a Jabber relay. The instant messages from the application server will be sent to the Jabber relay in the Web tier via SOAP. The Jabber relay will then save these messages in its database and send them to the outside Jabber server.

The outside Jabber server will most likely be run by your company in a production environment instead of using a publicly available one. For testing purposes, the test server provided by jabber.org will suffice. Please note, however, that this server runs the latest Jabber test release that can be used for testing purposes, but might not be reliable enough for production use.


Connecting to Jabber

We know what our challenge is now, so let's dive in and send our first message. But before you are able to send a message via Jabber, you first have to log on to the network. This is achieved by connecting and authenticating to an outside server. First, you'll have to create a Jabber ID with this server. You can do this with a standard Jabber client. In this example, I use "gpoul" as the username, and "password" as the password. To try this out, you'll have to come up with your own username and password.

To connect to Jabber, we'll have to use the appropriate Perl module to write a Jabber client. In my examples here, I'll use the Net::Jabber::Client module written by Ryan Eatmon. For more information, refer to the README file included with this distribution (see Resources). Installation will vary from system to system. On Debian GNU/Linux you might want to use the included libnet-jabber-perl package:

use Net::Jabber qw (Client);

After loading our module, we have to connect to the Jabber server and authenticate ourselves:

my $jabconn = Net::Jabber::Client->new();
$jabconn->Connect( "hostname" => "jabber.org",
                   "port" => 5222 )
  or die "Cannot connect ($!)\n";

my @result = $jabconn->AuthSend( "username" => 'gpoul',
                                 "password" => 'password',
                                 "resource" => 'perlscript' );

What I haven't mentioned yet is what the resource "perlscript" is for. In fact, this is a very useful feature in Jabber because you can have multiple resources for one account. If you sent a message to both gpoul@jabber.org/office and gpoul@jabber.org/home, you would reach two completely different clients.

If you just send the message to gpoul@jabber.org, the message will be routed according to the user's preferences. The neat thing about this is that if the user is not at home or at the office, they would be able to get their message to gpoul@jabber.org/cell or something like gpoul@jabber.org/pda.

We're finished, now, with our first login and have accomplished everything we want so far; so at this point we have to disconnect again.

$jabconn->Disconnect();


Sending your first message

Until now, this script hasn't done anything really useful -- we log into a server and immediately disconnect again. We won't get much work done this way, so we'll now send our first test message:

  my $msg = Net::Jabber::Message->new();
  $msg->SetMessage( "to"      => "tehkahless\@jabber.org",
                    "subject" => "My test subject",
                    "body"    => "This is a body." );
  $jabconn->Send($msg);

In this snippet, we first instantiate a new message object and create a test message. After that, we hand off this new message to the Jabber connection object, which sends the message to our Jabber server, where it is distributed to the recipient.

At the recipient's side, the following message will pop up:


Figure 1. Message-store database
Figure 1. Message-store database

In the last section we just did something interesting. Unfortunately, it's not exactly fascinating to send the same message multiple times, so we'll now create a database and use it as a message store.

Note: I'll demonstrate this by using PostgreSQL to access the "jabgate" database, but you might prefer to use a different DBMS. To use a different DBMS you just have to load a different DBI driver instead of DBI:pg. To get more information about how to handle database access in Perl, refer to the DBI Perl module documentation link in the Resources section.

We'll use the following database table to save our messages:

CREATE TABLE messages (
  msgid     serial primary key,
  status    char(2),
  recipient varchar(50),
  subject   varchar(255),
  body      text,
  filed     timestamp,
  sent      timestamp,
  received  timestamp
);

msgidSerial number to uniquely identify messages
statusStatus of the message -- at the moment we only use 'I' = initialized (to be sent), and 'C' = completed (already sent)
recipientFull Jabber address; this may include a resource string
subject Subject of the message
bodyBody of the message
filedTimestamp of filing
sentTimestamp of sending
receivedTimestamp of receipt by the client. This is not implemented here, but might be useful in the future to verify if the message was received.

As you can see in jabgate.pl we are using two prepared database statements. $getlist is used to get a list of messages with an assigned status, and $completeitem is used to mark a given message as sent.

Because we run this program as a daemon, we have an endless loop that fetches new messages from the database, sends them, and updates the record. After all messages have been sent, we commit our modifications to the database.

Note: I'm using an infinite while loop because it's easier to watch and debug. In a production environment it's very likely that you'll use a scheduling mechanism like crontab to run it.

Hint: Don't forget to grant the user running the jabgate.pl and the Web server user appropriate access permissions to your database!

Granting these permissions in PostgreSQL looks like this:

jabgate=# grant all on messages to gpoul;
CHANGE
jabgate=# grant all on messages_msgid_seq to gpoul;
CHANGE
jabgate=# grant all on messages_msgid_seq to "www-data";
CHANGE
jabgate=# grant insert on messages to "www-data";
CHANGE
jabgate=# \dp
                Access permissions for database "jabgate"
      Relation      |                 Access permissions
--------------------+----------------------------------------------------
 messages           | {"=","postgres=arwR","gpoul=arwR","www-data=a"}
 messages_msgid_seq | {"=","postgres=arwR","gpoul=arwR","www-data=arwR"}
(2 rows)


Fitting SOAP in

As a final step, we will now use SOAP to send the message from the application server through the firewall into our database on the Jabber relay.

To do that, we first have to create a Perl module that handles the insertion into the database and takes exactly three parameters: recipient, subject, and body. Everything else will be done by the system, as follows.

package jabmessage;

use DBI;
use strict;

sub sendmessage {
  my ($self, $recipient, $subject, $body) = @_;

  my $dbh = DBI->connect("dbi:Pg:dbname=jabgate", undef, undef,
                          { RaiseError => 1, AutoCommit => 0 });

  my $insertitem = $dbh->prepare("INSERT INTO messages 
  (status, recipient, subject, body, filed) VALUES ('I',?,?,?,now())");

  $insertitem->execute ($recipient, $subject, $body);

  $dbh->commit;

  $dbh->disconnect;
}

1;


To make it callable via SOAP, we also have to write a CGI gateway wrapper in Perl to dispatch the SOAP messages to our module. To make this all work, you just have to place the module and CGI wrapper into your Web servers cgi-bin directory and you're finished.

CGI gateway wrapper in Perl

#!/usr/bin/perl -w

use SOAP::Transport::HTTP;
use jabmessage;

SOAP::Transport::HTTP::CGI
  -> dispatch_to('jabmessage')
  -> handle;

SOAP makes it possible for you to use a wide range of languages to insert the instant message into the database and can, therefore, be used by a wide range of application servers.

In finishing this lesson, we will now try out our entire bunch of scripts by using requestjabber.pl. This script is called with all three parameters that will be dispatched to SOAP and will then be written to the database. After that, the database will be polled by jabgate.pl every 60 seconds and the message will be distributed to the Jabber network and marked as completed in the database.

gpoul@brightstar:~$ ./requestjabber.pl -r gpoul@jabber.com -s
"how are you" -b "How are you gerhard?"
Message has been sent.


Figure 2. Voila -- you've just solved our challenge
Figure 2. You've just solved our challenge

Enhancement ideas

By using the example in this article, you can now send one-way messages instantly to users on any device. To give recipients a more personal experience, you might also want to make it possible for them to talk back. For instance, enhance your relay to also be a full-featured Jabber bot. You might want to give customers the option to ask questions about orders, get contacts from within the company, reach support, or anything else that might be valuable.

I know that it is helpful to watch someone else develop a solution in order to get comfortable with a new tool. But it's not enough, and it's no fun either! I hope you've learned some basic tasks now in using Jabber and writing applications for it. I've collected a few enhancement ideas for you to work on, but before you start to work on one of the ideas, please also browse through the Resources section below.


Resources

About the author

Gerhard Poul is an IT contractor in Vienna, Austria. You can contact Gerhard at gpoul@eunet.at.

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology, XML
ArticleID=12109
ArticleTitle=Jabber
publish-date=05012002
author1-email=gpoul@eunet.at
author1-email-cc=

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers