Java and some free libraries make Instant Messaging a breeze!
Instant messaging (IM) has become a standard communication tool in many companies, sometimes surpassing even email usage. Back in the late 90's, I remember there was a push to have our i apps (oops, AS/400 apps back then!) send email notifications and reports to users. As an IBM i developer, you may now find yourself needing to communicate with an IM client of some kind. Luckily, thanks to the many freely available Java libraries, this is an easy task.
Let me start with a disclaimer: there are many competing (and even proprietary) IM protocols in use by different products and services. Hopefully, your company subscribes to one service using one protocol so that you will only have to program with one protocol in mind (although this is not always the case). The IM protocol I will be using in this tutorial is called Extensible Messaging and Presence Protocol (XMPP). XMPP is also called "Jabber" after the name of the open-source community that developed it. XMPP is feature-rich, allowing things like text "chat" messages, attachments, and even streaming video (using a family of extensions called Jingle) to be exchanged.
XMPP is used by Internet giant Google for its Google Talk (GTalk) and Google Mail (Gmail) chat features. It is also used in the popular open-source IM server Openfire and IM clients like Spark and Pidgin. As an aside, for those who want to know more about setting up an internal IM server for your company, check out MC Press' TechTip "Implementing an Internal Instant Messaging System," which demonstrates how to configure Openfire.
If your company has an IM server or service that uses another protocol—such as Yahoo Messenger (YMSG), Internet Relay Chat (IRC), or Microsoft's Mobile Status Notification Protocol (MSNP)—you can probably find a pre-written Java library to support it.
In this brief demonstration, I will show how an i app written in Java can be used to send messages to an IM client using a Gmail user account and the Gmail chat feature. You can also use the GTalk (Google Talk) client for this purpose, although, for simplicity, I chose to use Gmail's chat.
You'll need to have two Gmail accounts to follow along: one to send a message (from the i) and one to receive a message (within Gmail). For security reasons, Gmail doesn't allow just anyone to start chatting with you; you have to give permission to a user to chat with you. To grant chat permission to another user within Gmail, log in to Gmail using your second account (the "receiver"), locate the chat section on the left toolbar, type in the email address of your "sender" Gmail account in the chat text box, and click the "invite to chat" option from the context menu. (Note: some users may have differing variations of the Gmail chat options because the user interface evolves, so keep looking if you don't see the options exactly as I describe them.) For companies that already have an internal IM server that communicates using XMPP, you can substitute your own server in the example instead of using Google.
To aid with the Java programming, I used the free "Smack" XMPP client library. This API library does all the heavy work in constructing the XMPP messages and handling the communication. All I do is call a few simple methods to get my app to chat. You will need to download this library from the igniterealtime.org Web site and add these jar files to your Java environment's classpath:
The Smack version used in this demo is 3.1.0.
The code for this sample program, IM_Demo.java, can be downloaded here. This source, I must confess, was cobbled together in a few minutes based on postings I found online, mostly in the community portion of the igniterealtime.org Web site. Normally, I like to avoid plagiarism, but in the programming world, that's what the examples are posted for!
You can find plenty of documentation and examples on the Web, and the source code supplied here is commented. But here is a quick overview of the important features of the program (and yes, the sample code is more procedural than object-oriented, but that was the price of simplicity!):
Overview—This program connects to the Google Talk chat server (gtalk.google.com) on the default XMPP port of 5222 using the first Gmail user id. Substitute your own Gmail address (without the domain suffix) and password. The Smack library's ConnectionConfiguration and XMPPConnection objects are used to establish the connection.
String imUserName = "GamilAccount1";
String imPassword = "Mypassword";
// Configure connection
ConnectionConfiguration connConfig = new ConnectionConfiguration(host, port, service);
XMPPConnection connection = new XMPPConnection(connConfig);
Sending a Message—Next, the Message class is instantiated and supplied with three pieces of information: the recipient's email address, the message type (chat, in this case), and a message body. Once the message has been constructed, the Connection object's sendPacket method is used to send the instant message.
// Send a test IM message
Message imMessage = new Message(imRecipient, Message.Type.chat);
imMessage.setBody("This is a test from the IBM i");
Receiving a Message—The last thing the program does is set up a "listener" to handle processing when a message is received. This code is intended to get you started with "listening" for user feedback. If you're unfamiliar with the concept of a Java listener, it simply waits and "listens" for a particular event to happen. When the event occurs, the listener executes the specified code.
// Setup listener to "hear" incoming messages
PacketFilter chatFilter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new ChatMessaageReceiver(connection), chatFilter);
A filter is applied to the listener to instruct it to listen only for "chat" messages. When the connection object detects that a chat message is being sent from a remote user, it executes the processPacket method of the ChatMessageReceiver object (which implements PacketListener). The sender name and body is extracted from the incoming message (very easily, I might add, thanks to the Smack library), and an "echo" is sent back to the caller as an instant message to inform him that the message was received:
// Get sender info and body of chat message
String fromName = StringUtils.parseBareAddress(message.getFrom());
System.out.println("Message from " + fromName + "\n" + message.getBody() + "\n");
// Echo response back to sender
Message reply = new Message();
reply.setBody("IBM i: You said: " + message.getBody()+"\n\nYour wish is my command!");
The great thing about the listener is that the code to process an incoming message is executed automatically when a message is sent back to the i program. The main program waits indefinitely for a user to press Enter before ending. But while the main program waits for the user to press Enter, the listener will continue to listen and execute the specified code in the "background" when a message is sent.
Below is a picture of what the program's automatic "echo" response looks like in the Gmail chat window:
Figure 1: The Gmail chat window shows the program's automatic "echo" response.
You can see the following from the above image:
- The IM_Demo program sent the message "This is a test from IBM i."
- From within the Gmail chat window, I typed and sent the message "Reboot the system right away!" The sample IM_Demo program received it and then echoed the message back to my chat window along with the text "Your wish is my command!"
So now you have a basic Java template that demonstrates how to send and receive IM messages using XMPP. Once your own Java program is completed, it can be accessed by traditional high-level language (HLL) programs in one of several ways:
- Using the RUNJVA CL command
- Instantiating a Java object from within an ILE RPG program using the Java Native Interface (JNI)
- Wrapping the Java program as an SQL routine (stored procedure or user-defined function) for use in embedded SQL programs or any SQL interface
Enabling i programs to communicate with an IM server is an easy thing thanks to Java's availability on the i (good job, IBM) and the many freely available open-source libraries. IM opens many new possibilities for users to respond to things like application alerts or system error messages in a convenient and controlled manner. Endow your i apps with the gift of gab today!
All you want to know about XMPP :
Java SMACK XMPP (Jabber) API:
Beginner's sample code using Smack:
as/400, os/400, iseries, system i, i5/os, ibm i, power systems, 6.1, 7.1, V7,