24
Mon, Jun
3 New Articles

TechTip: Chat with IM Clients from your i Apps

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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:

  • smack.jar
  • smackx.jar
  • smackx-debug.jar
  • smackx-jingle.jar

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";

String host="talk.google.com";

String service="gmail.com";

int port=5222;

 

 

// Configure connection

ConnectionConfiguration connConfig = new ConnectionConfiguration(host, port, service);

connConfig.setSASLAuthenticationEnabled(false);

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


String imRecipient="This email address is being protected from spambots. You need JavaScript enabled to view it.":


Message imMessage = new Message(imRecipient, Message.Type.chat);
imMessage.setBody("This is a test from the IBM i");
connection.sendPacket(imMessage);

 

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.setTo(fromName);
reply.setBody("IBM i: You said: " + message.getBody()+"\n\nYour wish is my command!");
xmppConnection.sendPacket(reply);

 

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:

 

091710Sans0Fig1

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!

Additional Resources

All you want to know about XMPP :
http://xmpp.org/


A list of XMPP libraries available for .NET, JavaScript, PHP, Java, ActiveX, Python, etc.:
http://xmpp.org/xmpp-software/libraries/


Java SMACK XMPP (Jabber) API:
http://www.igniterealtime.org/downloads/index.jsp#smack


Beginner's sample code using Smack:
http://www.andrejkoelewijn.com/wp/2008/12/30/using-google-talk-from-java-example/

as/400, os/400, iseries, system i, i5/os, ibm i, power systems, 6.1, 7.1, V7,

Michael Sansoterra is a DBA for Broadway Systems in Grand Rapids, Michigan. He can be contacted at This email address is being protected from spambots. You need JavaScript enabled to view it..


BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: