Skip to main content

Developing an XML-based Lotus Sametime bot as a startup bean on WebSphere Application Server V7.0

Ahmed Alsum (ALSUM@eg.ibm.com), Staff Software Engineer, IBM
Ahmed Alsum is a staff software engineer in the Cairo Technology Development Center, IBM Egypt. He has four years of experience in developing, deploying, and administering J2EE and WebSphere Portal solutions. He has BSc. and MSc. degrees in computer science and many professional certifications from Microsoft, Sun, and IBM. You can reach him at ALSUM@eg.ibm.com.

Summary:  Improving the representation for back-end content and system services using an IBM® Lotus® Sametime® bot is an easy way to attract users who are already familiar with the tool and want quick results without going to yet another Web site. This article provides a step-by-step guide to developing an XML-based Lotus Sametime bot as a startup bean on IBM WebSphere® Application Server V7.0.

Date:  29 Jun 2009 (Published 23 Jun 2009)
Level:  Intermediate
Activity:  5274 views

Editor's note: Know a lot about this topic? Want to share your expertise? Participate in the IBM Lotus software wiki program today.

Lotus Sametime wiki

Introduction

First, this article describes how to implement a Lotus Sametime bot that interacts with data-centric systems based on an XML data service provider such as SOA, Web services, or even a servlet that manipulates XML data. XSLT controls the rendering of the XML response. Next, the access to the Lotus Sametime bot is limited to a specific authenticated group. Finally, the article delves into how to manage the Lotus Sametime bot login and logout operations using a start-up Enterprise JavaBean (EJB) deployed on WebSphere Application Server V7.0.


XML-based Lotus Sametime bot

XML becomes the mainstream technology for transferring and manipulating data. The Lotus Sametime Java™ toolkit allows you to access core Lotus Sametime services, such as presence awareness, instant messaging, and screen sharing by means of the Java programming language. In this article, an extension of the Lotus Sametime bot is shown to work as an XML data consumer that fits in the SOA picture. Figure 1 shows the relationship between the XML data service provider and the XML Lotus Sametime bot extension.


Figure 1. Lotus Sametime bot and XML data service provider architecture
Lotus Sametime bot and XML data service provider architecture

In the following sections, we discuss the two main parts of connecting the Lotus Sametime bot and the XML data provider:

  • Establishing a connection between Lotus Sametime Java and the external data source using a URL, including wrapping the response into an XML-doc object.
  • Transforming the XML-doc object into readable text.

The Lotus Sametime bot connects to the XML data provider

The XML data provider usually is accessible using the string url, which contains the server name, the required service, and the supported parameters. In the Lotus Sametime bot environment, you might need to customize the string url based on the user command (for example, you might need to add parameters based on the command). The URLConnection class can be used to connect to an external Web server. Initially, the url text for the external data source is wrapped in the URL object, which is used to open the connection. Then, the URLConnection class is used to establish the connection. While most sensitive data providers expose their data through the SSL connection, the URLConnection class can support passing usernames and passwords to the external data source. Note that if the Web site uses an SSL certificate that is not trusted, the certificate should be imported into the application server keystore certificate. Lines 2-8 in listing 1 show a sample of code to connect to the external secure data source using string url.


The Lotus Sametime bot receives a response from the XML data provider

The Lotus Sametime bot receives the response as an inputStream of data; it should be wrapped into the XML document object. Lines 9-11 in listing 1 explain the steps required to transform the inputStream into an XML document object. An instance of DocumentBuilderFactory is obtained, which defines a factory API that enables applications to obtain a parser that produces DOM object trees from an XML document. This object is used to create a new instance of the DocumentBuilder class. After an instance of this class is obtained, XML can be parsed from a variety of input sources. Here we parsed the XML from the inputStream.


Listing 1. The Lotus Sametime bot connects to the XML data provider
1.	Public Document connect(String urlStr){
2.	URL url;
3.	    try {
4.	      url = new URL(urlStr.toString());
5.	     URLConnection conn = url.openConnection();
6.	      String userPassword = “myUser:myPassword”;
7.	      String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
8.     conn.setRequestProperty  ("Authorization", "Basic " + encoding);
9.	      conn.connect();
10.      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
11.	     DocumentBuilder db = dbf.newDocumentBuilder();
12.	     Document doc = db.parse(conn.getInputStream());
13.	   } catch (MalformedURLException e) {
14.	      e.printStackTrace();
15.	    } catch (IOException e) {
16.	     e.printStackTrace();
17.	    } catch (ParserConfigurationException e) {
18.	      e.printStackTrace();
19.	    } catch (SAXException e) {
20.	     e.printStackTrace();
21.	   }
22.	   return doc;
23.	}


The Lotus Sametime bot transforms a response using XSLT

Although the XML document object is easy to parse and easy to understand on the coding level, it fails in user readability. The XML response cannot be sent directly to the user; it needs to be parsed in a way that the user can read. A lot of techniques support XML parsing and preparing of readable, well-formatted text for the user.

XSL Transformation (XSLT) is used to transform an XML document into another XML document, or into another type of document that is recognized by a browser, such as HTML and XHTML or even plain text. The Java library contains a formatter that combines XML documents with the related XSLT files and transforms them to the required output format. Listing 2 shows the sample code used to transfer an XML document to a text, based on the XSL file saved on a specific path.


Listing 2. A sample function to transform the XML-doc object to text using an XSLT file
1.	public String format(Document dom, String xlsFilePath) {
2.	 DOMSource src = null; 
3.	 StreamResult res = null;
4.	 StringWriter sw = new StringWriter();
5.	 File file=new File(xlsFilePath);
6.	  
7.	  if(file.exists()){
8.	    try {
9.	      TransformerFactory factory = TransformerFactory.newInstance();
10.	      Transformer transformer = factory.newTransformer(new StreamSource(file));
11.	      src = new DOMSource(dom);
12.	      res = new StreamResult(sw);
13.	      transformer.transform(src, res);
14.	    } catch (TransformerException e) {
15.	      e.printStackTrace();
16.	    }
17.	  }
18.	  return sw.toString();
19.	}

ImListener.textReceived can combine both functions to prepare a string url based on the command (for example, the string url might contain different parameters based on the user command). Additionally, you can create different XSLT response files for each command. Listing 3 contains a sample of code of ImListener.textReceived that calls both the connect and format methods. Figures 2 and 3 show samples of the XML response and the related XSLT file, and figure 4 shows the text response as it appears to the user.


Listing 3. Overriden method ImListener.textReceived
1.	public class MyImListener implements ImListener {
2..
3.
4.	  public void textReceived(ImEvent e) {
5.	    String urlStr = prepareURLForCommand(e);
6.	   Document responseDoc = connect(urlStr);
7.	    String answer =format(responseDoc, "c://response.xsl");
8.	     e.getIm().sendText(true, answer);
9. 
10.	.
11.	.
12.	}


Figure 2. Received XML response
Received XML response

Figure 3. XSLT file
XSLT file

Figure 4. Lotus Sametime bot behavior
Lotus Sametime bot behavior

This technique is sufficiently dynamic to reflect to any updates in the XML data provider response; the only required step is uploading a new XSLT file without any code update. Also, the code can be updated to let the Lotus Sametime bot connect to different data sources.


Secure Lotus Sametime bot

The Lotus Sametime client does not limit adding user IDs to the contacts list; this fact means that the Lotus Sametime bot is accessible to a wide range of users who might not have authorized access to the system. Controlling access to confidential information is the responsibility of the Lotus Sametime bot itself. When users open a chat window with the bot, ImServiceListener.imReceived(ImEvent e) is invoked. The ImEvent object contains the essential information about the user ID ImEvent.getIm().getPartner().getId(). The Lotus Sametime bot can use this value to check the user ID in its access list. Listing 4 shows an example of how to secure the confidential information from unauthorized access using bluegroups. You need to implement the authenticate(String userID) method to validate the user ID based on the access group.


Listing 4. ImServiceListener.imReceived authenticates user ID
1.	public void imReceived(ImEvent e) {
2.	  ImListener imListener =null;
3.	  if(authenticate(e.getIm().getPartner().getId())){
4.	   imListener = AuthorizedListener.getListener(e);
5.	   e.getIm().sendText(true, WELCOME_TEXT);
6.	  } else {
7.	   imListener = UnAuthorizedListener.getUnAuthorizedListener(e);
8.	   e.getIm().sendText(true, WELCOME_UNAUTHORIZED_TEXT);
9.	 }
10.	  e.getIm().addImListener(imListener);
11.	}
 


Lotus Sametime bot deployment

The Lotus Sametime bot runs as a stand-alone application. To the Lotus Sametime server, a Lotus Sametime bot is usually considered just another person. The Lotus Sametime bot needs only to authenticate on the messaging server using a valid username and password; it doesn’t rely on how the Lotus Sametime bot was deployed. From the coding perspective, you combine the required steps that handle the login and logout activities; these methods are the controller of the status of the Lotus Sametime bot. Listings 5 and 6 show sample codes for both methods.

In this section, we provide different approaches to deploy the Lotus Sametime bot on WebSphere Application Server. The target of the different deployment approaches is to provide a controlled mechanism to call both login and logout methods.


Listing 5. logIn() method implementation
1.		public void logIn()
2.	{ 
3.	  if( stsession == null){
4.	    try {
5.	     java.util.Date initTime = new java.util.Date();
6.	     stsession = new STSession("MySametime Bot" + String.valueOf(initTime.getTime())); 
7.	   
8.	     } catch (DuplicateObjectException e) {
9.	       e.printStackTrace();
10.	       return;
11.	     }
12.	    }
13.
14.	  if(  ! stsession.isActive() ){
15.	    stsession.loadSemanticComponents();
16.	    stsession.start();
17.	   }
18.	 
19.	   commService = (CommunityService) stsession.getCompApi(CommunityService.COMP_NAME);
20.	   m_fileTransSvc = (FileTransferService) stsession.getCompApi(FileTransferService.COMP_NAME);
21.	   m_fileTransSvc.addFileTransferServiceListener(this);
22.	   commService.addLoginListener(this);
23.	   commService.setLoginType(logInType);
24.	   commService.enableAutomaticReconnect(100, 5000);
25.	   commService.loginByPassword(SERVER_NAME, USER_ID, PASSWORD);
26.	}
27.


Listing 6. logOut() method implementation
1.	public void logOut()
2.	{
3.	commService = (CommunityService) stsession.getCompApi(CommunityService.COMP_NAME);
4.	 commService.logout();
5.	 stsession.stop();
6.	 stsession.unloadSession();
7.	}


Different deployment approaches

The first deployment approach that depends on Java 2 Platform, Enterprise Edition (J2EE) technologies is the deployment of the Lotus Sametime bot as a servlet. You need to create a servlet and to modify the doGet method to accept the user actions as URL parameters. These actions are able to invoke both the login() and logout() methods. Listing 7 shows a sample code that allows you to deploy the Lotus Sametime bot as a servlet.


Listing 7. Overridden doGet method
1.	 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
2.				ServletException, IOException {
3.	      
4.	    String action = request.getParameter("action");
5.	    PrintWriter out = response.getWriter();
6.	    if("start".equalsIgnoreCase(action)){
7.	      out.println("Request to start Sametimebot");
8.	      ebb= new MySametimeBot();
9.	      ebb.logIn();
10.	      ebb.start();
11.	    } else if( "stop".equalsIgnoreCase(action)){
12.	      out.println("Request to stop Sametimebot");
13.	      ebb.logOut();
14.	    } else {
15.	      out.println("Unknown action: "+ action);
16.	    }
17.  }

Suppose the servlet has a URL mapping as sametimebotServlet.

  • To start the Lotus Sametime bot, enter this URL: http://myserver/sametimebotServlet/action=start
  • To stop the Lotus Sametime bot, enter this URL: http://myserver/sametimebotServlet/action=stop

Deploy as startup beans

In some cases, managing the Lotus Sametime bot using a servlet or a stand-alone Java application is not secure. To be secure, management needs more control of the Lotus Sametime bot status. In this section, we develop a new approach for using the EJB startup bean as a container for controlling the Lotus Sametime bot status.


What’s a startup bean?

A startup bean is a user-defined EJB 2.0 session bean. A module startup bean is a session bean that is loaded when an EJB JAR file starts. Module startup beans enable J2EE applications to run business logic automatically, whenever an EJB module starts or stops normally. The EJB can be either stateful or stateless. If it is stateful, the same instance is used for start and stop. Otherwise, two instances are created.

You must use the following home and remote interfaces:

  • The EJB home interface must be com.ibm.websphere.startupservice.AppStartUpHome, to define start() and stop() methods on the bean.
  • The EJB remote interface must be com.ibm.websphere.startupservice.AppStartUp, to define start() and stop() methods on the bean.

The startup bean start() method is called when the module or application starts and contains business logic to be run at the module or application start time. The startup bean stop() method is called when the module or application stops and contains business logic to be run at the module or application stop time. Any exception thrown by a stop() method is logged only; no other action is taken.


Deploying the Lotus Sametime bot as a startup bean

Create the Lotus Sametime bot code in a separate Java project and include it into the EJB startup bean project. After that, the Lotus Sametime bot object initialization and logIn() method are invoked in the start() method. Also, the logOut() method is invoked in the stop() method. See the code in listing 8.


Listing 8. Managing Lotus Sametime bot status using start and stop methods
1.	public class MySametimeBotStartupBean implements javax.ejb.SessionBean {
2.	 public boolean start()
3.	 {
4.	    System.out.println("MySametimebot is starting.");
5.	    ebb= new MySametimeBot();
6.	    ebb.logIn();
7.	    ebb.start();
8.	    return true; //if false is returned an exception will be thrown and the 
		application is not started
9.	  }
10.	  public void stop()
11.	 {
12.	    System.out.println ("MySametimebot is stopping.");
13.	    ebb.logOut();
14.	   }
15.}

The application is packaged as an Enterprise Application (EAR) and is deployed on WebSphere Application Server. After successful deployment of the EAR project, you can start and stop the Lotus Sametime bot instance.


Conclusion

In this article, new aspects of the Lotus Sametime bot’s development and deployment cycles are discussed. First, the Lotus Sametime bot could connect to the XML data source using Java APIs, supported with the XSLT formatter to turn the XML response into text that the user can read. Due to the sensitivity of the XML data source, an additional security level is added to the Lotus Sametime bot based on the user ID to keep the XML data source safe. Finally, different approaches of deploying the Lotus Sametime bot are listed with detailed discussions of the deployment as a startup bean.


Acknowledgment

This work was done as a part of IBM’s Corporate Client Support Portal (CCSP) in November 2008. The author would like to express gratitude to the CCSP team for their valuable comments.


Resources

About the author

Ahmed Alsum is a staff software engineer in the Cairo Technology Development Center, IBM Egypt. He has four years of experience in developing, deploying, and administering J2EE and WebSphere Portal solutions. He has BSc. and MSc. degrees in computer science and many professional certifications from Microsoft, Sun, and IBM. You can reach him at ALSUM@eg.ibm.com.

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=Lotus, WebSphere
ArticleID=398355
ArticleTitle=Developing an XML-based Lotus Sametime bot as a startup bean on WebSphere Application Server V7.0
publish-date=06292009
author1-email=ALSUM@eg.ibm.com
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).

Special offers