Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Connecting WebSphere MQ with social networks: Twitter notifications for queue managers and MQ applications

Rich Cumbers (rich.cumbers@uk.ibm.com), Software Developer, WebSphere MQ File Transfer Edition, IBM
Photo of Rich Cumbers
Rich Cumbers is a Software Developer on the WebSphere MQ File Transfer Edition (FTE) team at the IBM Hursley Software Lab in the UK. He has worked at IBM for four years on both WebSphere MQ and WebSphere MQ FTE. His career to date has spanned most software development disciplines including development, test, and performance. You can contact Rich at rich.cumbers@uk.ibm.com.

Summary:  Social networking is everywhere these days -- for connecting with friends, or for staying updated and keeping others updated on topics of mutual interest. Social networks are also proving useful in the enterprise. This article shows you how to quickly and easily enable your WebSphere MQ applications to use social networking software such as Twitter to send status and problem information to a wide audience of system administrators and end users, and even to other applications and middleware. The examples in this article use WebSphere MQ and the Twitter API with JEE technology (simple message-driven beans) targeted at the WebSphere Application Server Community Edition runtime.

Date:  31 Mar 2010
Level:  Intermediate
Also available in:   Chinese  Portuguese

Activity:  14474 views
Comments:  

Introduction

Social networking has seen explosive growth, as exemplified by networking sites such as Facebook, LinkedIn, and Twitter. Companies are beginning to set up internal social networking applications, and the IBM® Lotus® Connections product makes it easy to set up enterprise-scale social networks.

This article shows you how to use social networking software with an enterprise messaging product such as WebSphere® MQ. The three examples in this article use Twitter, but any social networking site with an API can be used. The three MQ-Twitter examples are:

  • A simple queue, from which text messages are retrieved and published direct to Twitter
  • Queue manager events, such as creating or deleting a queue
  • A publish/subscribe example using WebSphere MQ File Transfer Edition (hereafter called WebSphere MQ FTE)

The examples in this article were developed using message-driven beans (MDBs) deployed to WebSphere Application Server Community Edition. Another approach is to use a standalone Java™ application with a message listener. The code listings below are snippets from a zip file that contains all the source files needed to run the sample. You can download the zip file at the bottom of the article.

Twitter API

Many Java libraries provide an interface to the Twitter API. The examples in this article use the Apache Commons HTTP libraries to communicate with it. The Twitter API is a well documented specification -- for more information, see the Twitter API wiki..

Listing 1 shows the Java method used to tweet a given message. See the downloadable zip file for the complete Java class.


Listing 1. TwitterPlugin.java: sendNotification() method

public void sendNotification(String message) {

   if(message.length() > 140) {
      System.err.println("Message will be truncated from: "
         + message + " to: " + message.substring(0, 140));
   }

   PostMethod post = null;
   try {
      HttpClient client = new HttpClient();
      client.getParams().setAuthenticationPreemptive(true);
      client.getState().setCredentials(new AuthScope("twitter.com", 80, "realm"),
         new UsernamePasswordCredentials(getUsername(), getPassword())); 
      post = new PostMethod("http://twitter.com/statuses/update.xml");
      post.setQueryString(URIUtil.encodeQuery("status="+message));
      post.setDoAuthentication( true );
   
   // execute the GET
   int status = client.executeMethod( post );
   // print the status and response
   System.out.println("Status: " + status);

      } catch (URIException e ) {
         System.err.println(e.getMessage());
      } catch (HttpException e) {
         System.err.println(e.getMessage());
      } catch (IOException e) {
         System.err.println(e.getMessage());
      } finally {
   // release any connection resources used by the method
         if(post != null) {
            post.releaseConnection();
         }
   }
}	

Simple text message MDB

Using simple text messages, you can quickly turn MQ messages into Tweets. This example uses a standard MQ queue. To drive the sample, you can use any application that puts a text message onto the queue, such as the amqsput sample included with WebSphere MQ. Here is the MDB code:


Listing 2. SimpleMQEJB.java: onMessage() method

public void onMessage(Message message) {
 
   if(message instanceof TextMessage) {
      try {
   /* Put your twitter username and password here */
      TwitterPlugin tp = new TwitterPlugin("YOUR_TWITTER_USERNAME",
         "YOUR_TWITTER_PASSWORD");
      String output = ((TextMessage) message).getText();
      tp.sendNotification(output);
      } catch(JMSException e) {
         e.printStackTrace();
      } 
   } else {
      System.err.println("This application requires" +
         " a message in TextMessage format");
   }
}	

The code is simple: It takes the payload of the MQ Message, truncates it to 140 characters, and then posts it using the TwitterPlugin.java code. Figure 1 shows the example output on my mq_tweet twitter account:


Figure 1. Simple text message as a tweet
Simple text message tweet

MQ event message MDB

WebSphere MQ provides information about errors, warnings, and other significant actions in a queue manager through MQ Events Messaging. When configured to do so, WebSphere MQ puts a message to a specific queue, from which an application can then consume the message and perform actions based on the message contents. For more information on the types of events that WebSphere MQ see the topic Event monitoring in the WebSphere MQ information center. To enable event messages for an MQ queue manager, follow the instructions under Controlling configuration, command, and logger events in the WebSphere MQ information center.

Listing 3 shows another MDB, but this time it is configured to read from the SYSTEM.ADMIN.CONFIG.EVENT queue. This MDB takes in the message, and using simple logic, decides what message to send to Twitter:


Listing 3. MQEventMDB.java: onMessage() method

public void onMessage(Message msg) {

   if(msg == null)return;
   if (msg instanceof TextMessage) {
      TextMessage txtMsg = (TextMessage) msg;
   try {
            System.out.println("Received TextMessage: " + txtMsg.getText());
         } catch (JMSException e) {
            e.printStackTrace();
         }
      }

   if (msg instanceof BytesMessage) {
      JMSBytesMessage bytesMsg = (JMSBytesMessage) msg;
      int bodySize;
      try {
         bodySize = (int) bytesMsg.getBodyLength();
         byte[] data = new byte[bodySize];
      bytesMsg.readBytes(data);
      ByteArrayInputStream bais = new ByteArrayInputStream(data);
      DataInput dataInput = new DataInputStream(bais);
      PCFMessage response = new PCFMessage(dataInput);
      int reason = response.getReason();
      int type = response.getIntParameterValue(MQConstants.MQIACF_OBJECT_TYPE);
      if(type == MQConstants.MQOT_Q) {
         publishQueueEvent(response, null);
      } else {
         System.out.println("Object Type received: " + reason);
      }
      } catch (Exception e) {
         e.printStackTrace(); 
      }
   }
}

Because the MQ Event messages are published in PCF format, you must convert the JMSBytesMessage object into a PCFMessage object. You do this conversion by reading the bytes of the incoming message and creating a DataInput object to pass to the PCFMessage's constructor. Figure 2 is a sample of the output that is generated when a queue is created:


Figure 2. Queue creation event message as a tweet
Create queue event as a tweet

WebSphere MQ FTE Transfer Message MDB

WebSphere MQ FTE is a new edition of WebSphere MQ that manages secure and reliable file transfers, and publishes messages that provide an audit log of the transfers. For information on the XML schema for these audit messages, see the topic Message formats in the WebSphere MQ FTE information center. Using a combination of an MDB and some JAXB code, you can enable Twittering about the start and end of file transfers, and even include some hash tags defined inside the metadata of a transfer.

Listing 4 is the WebSphere MQ FTE-specific MDB. Instead of connecting to a queue, you are connecting to an FTE topic. Metadata associated with the file transfer is appended to the status message if the metadata name starts with the keyword Twitter. For example, Twitter.tag=SimpleTweet results in #SimpleTweet being appended to the message that is sent:


Listing 4. MQEventMDB.java: onMessage() method

public void onMessage(Message message) {
   
   if(message instanceof TextMessage) { 
      try {
         TwitterPlugin tp = new TwitterPlugin("YOUR_USERNAME", "YOUR_PASSWORD");
      String output = ((TextMessage) message).getText();
      String notification = null;   
      if(output.contains("TransferLog.xsd")) {

         if(output.contains("started")) {
            Transaction transaction = generateTransaction(output);
            String transferName = getJobName(transaction);
            String twitterTags = getTwitterTags(transaction);
            notification = "Transfer started: " + transferName;
            if(notification.length() "<" (140 - twitterTags.length())) {
               notification = notification + " #ftetweet" + " " + twitterTags;
            }
         } else if(output.contains("completed")) {
            Transaction transaction = generateTransaction(output);
            String transferName = getJobName(transaction);
            String twitterTags = getTwitterTags(transaction);
            String transferFailed = "";
            if(transaction.getStatus().getResultCode() != 0) {
               transferFailed = " Transfer Failed (RC=" + 
                  transaction.getStatus().getResultCode()+")";
            }

            notification = "Transfer complete: " + transferName + transferFailed;
            if(notification.length() "<" (140 - twitterTags.length())) {
               notification = notification + " #ftetweet" +
               " " + twitterTags;
            }
         }
      }
         if(notification != null) {
            tp.sendNotification(notification);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   } else {
         System.err.println("This application requires a message in TextMessage format");
   }
}

Figures 3 and 4 below show the tweets generated by a file transfer starting and completing:


Figure 3. WebSphere MQ FTE file transfer starting
WebSphere MQ FTE file transfer starting

Figure 4. WebSphere MQ FTE file transfer completing
WebSphere MQ FTE file transfer completing

Conclusion

This article has shown you how connecting WebSphere MQ queue managers or WebSphere MQ applications with Twitter is both simple to do and very effective for broadcasting status messages to interested parties. An open-source Twitter-style implementation called StatusNet (formerly called Laconica) can be deployed inside the enterprise, and uses exactly the same API as Twitter, enabling companies to quickly set up and deploy a social networking infrastructure. You can easily substitute Twitter for Status.net and start publishing information about your company's work, without the worry of confidential or sensitive information being published into the public domain.



Download

DescriptionNameSizeDownload method
Code sampleTwitterMQ.zip90 KBHTTP

Information about download methods


Resources

About the author

Photo of Rich Cumbers

Rich Cumbers is a Software Developer on the WebSphere MQ File Transfer Edition (FTE) team at the IBM Hursley Software Lab in the UK. He has worked at IBM for four years on both WebSphere MQ and WebSphere MQ FTE. His career to date has spanned most software development disciplines including development, test, and performance. You can contact Rich at rich.cumbers@uk.ibm.com.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

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=WebSphere
ArticleID=478317
ArticleTitle=Connecting WebSphere MQ with social networks: Twitter notifications for queue managers and MQ applications
publish-date=03312010
author1-email=rich.cumbers@uk.ibm.com
author1-email-cc=

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.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

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).

Try IBM PureSystems. No charge.

Special offers