Skip to Content

In the below article we will see how to generate a automatic email alerts to a customer/SAP PI admins with the list of communication channels in error and which requires attention.

Please find below the JAVA coding which helps in acheiving this objective. (Make sure to import the relevant external JARS to your library 🙂 )

JAVA Coding – What it does :

1.) The http url

http://<host>:<port>/AdapterFramework/ChannelAdminServlet?action=status&party=*&service=*&channel=*

will provide the information regarding the list of channel names, status and other information(like Sender/Receiver, etc..).

We are interested in the field ChannelStatus (This provides the state of each communication channel which is our interest here).

2.) When we hit the url, window pop ups for authentication to server(we have to provide valid user credentials to log in to pi server).

3.) We use SAX parsing to store the list of channel names which is in error status from the HTTP response .

4.) Generate a email to the list of customers specified in the code incase if any error channels are found.(sendEmail() function is created for the same)

The below JAVA code when run from your SAP PI server or any server/PC which has direct connectivity(firewall should be opened) to PI system will generate a email alert incase if any channels are in error.

import java.net.*;
import java.util.ArrayList;
import java.util.Properties;
import java.io.*;
import javax.mail.*;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
class ExternalChannelControlXIPI
{
     public static void main(String[] args)
     {
      ExternalChannelControlXIPI channel1 = new ExternalChannelControlXIPI();
      try
          {
               //specify the host and port number for connecting to the PI server in your landscape
           URL server = new URL("http://<host>:<port>/AdapterFramework/ChannelAdminServlet?action=status&party=*&service=*&channel=*");
               //I have hardcoded UserName & Password here but your logic may vary based on your needs
               String userPassword ="username" + ":" + "password";
               String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
               URLConnection uc=server.openConnection();
               uc.setRequestProperty ("Authorization", "Basic " + encoding);
               BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
               String inputLine = "";
               String output = "";  
//Constructing a XML from the http response of URL desribed above     
                while (( inputLine = br.readLine()) != null)
                    output+=inputLine;
                output=output.replaceFirst("<!DOCTYPE", "<!--<!DOCTYPE");
               String abc = "-->";
               output=output.replaceFirst("dtd" + "\">",abc);
               br.close();
               Handling2 handler= new Handling2();
            SAXParserFactory factory = SAXParserFactory.newInstance();
               SAXParser saxpr = factory.newSAXParser();
             InputSource is = new InputSource(new StringReader(output));
//Parse the xml content to filter channels with error
      saxpr.parse(is, handler);
     //Based on the result trigger email
        channel1.sendEmail();
       
                }
          catch (Exception e)
          {
               e.printStackTrace();
          }         
     }
    
      public void sendEmail ()
     {
      // Recipient's email ID needs to be mentioned.
       String to = "email id of receiver";
       // Sender's email ID needs to be mentioned
       String from = "email id of sender";
       // Assuming you are sending email from localhost
       String host = "localhost";
     
       // Get system properties
       Properties properties = System.getProperties();
       // Setup mail server
       properties.setProperty("mail.smtp.host", host);      
       // Get the default Session object.
       Session session = Session.getDefaultInstance(properties);
       try{
          // Create a default MimeMessage object.
          MimeMessage message = new MimeMessage(session);
          // Set From: header field of the header.
          message.setFrom(new InternetAddress(from));
          // Set To: header field of the header.
          message.addRecipient(Message.RecipientType.TO,
                                   new InternetAddress(to));
          // Set Subject: header field
          message.setSubject("SAP PI system communication channels are in error");
          // Now set the actual message
          message.setText(" The below channels are in error " + Handling2.message);
          // Send message
          Transport.send(message);
                 }
 catch (MessagingException mex) {
          mex.printStackTrace();
       }
     }
    
   
}
class Handling2 extends DefaultHandler
{
 static int flagX=0;
 static int flagY=0;
 static String message = "";
 ArrayList<String> ChannelName = new ArrayList<String>();
 ArrayList<String> ChannelStatus = new ArrayList<String>();
 ArrayList<String> ErrorChannels = new ArrayList<String>();
  
 public void startElement(String namespaceURI, String localName,String qName, Attributes atts) throws SAXException
 {
// Find the <ChannelName> tag from the source XML
 
  if (qName.contains("ChannelName"))
  flagX=1;
 // Find the <ChannelState> tag from the source XML
  if (qName.contains("ChannelState"))
  flagY=1;  
  
  }


 public void characters(char characters[], int start, int length) {
 
     String characterData =
         (new String(characters,start,length)).trim(); // get the text
    
     if(flagX==1) {        // indicate this text is for <ChannelName> element
//add all list of channel names to ChannelName arraylist
        ChannelName.add(characterData);
        flagX=0;
     }
     if(flagY==1) {        // indicate this text is for <ChannelState> element
//add all list Channel status to ChannelStatus arrarylist
         ChannelStatus.add(characterData);
         flagY=0;
      }   
   
    }
 public void endDocument() {
 
    for(int i=0;i<ChannelStatus.size();i++)
  {
//Get the corresponding the channel name whose status is in error to ErrorChannels ararylist
  if(ChannelStatus.get(i).equals("ERROR"))
   ErrorChannels.add(ChannelName.get(i));
  }
   System.out.println("out of " +ChannelName.size()+ " Channels,The below " +ErrorChannels.size() + " channels are in error");
   for(int j=0;j<ErrorChannels.size();j++)
   {
        message = message + "\n" + ErrorChannels.get(j);
   }
 } 
}

Note : This JAVA coding can also be scheduled to run for a regular interval (This is not dealt in this blog but you are free to try 🙂 )

This is just a starting point for using customized JAVA coding in SAP PI and certainly much more can be achieved with the help of JAVA.

The above code is just my point of view on how to generate email alerts listing channels in error,

This can however be altered based on your needs and the varioust approaches you would like to follow.

Not to forget the references, here it is the starting point to my custom code above.

http://scn.sap.com/community/pi-and-soa-middleware/blog/2012/09/27/simple-approach-for-ccms-monitoring-of-communication-channels

http://scn.sap.com/thread/2001008

To report this post you need to login first.

2 Comments

You must be Logged on to comment or reply to a post.

  1. Former Member

    Hi Kumaresh,

    Nice one. Very useful blog.

    The API is handy . But there are 2 items that I feel should be handled.

    1) If the channel is in error for some time then starts to function. what does the API retrun as status. I feel it might return as Error and say Error in Last 10 (x) minutes or something?

    2) If there are multiple servers and due to some reason the processing fails in a particular app server the whole status is deemed error.

    The API retruns the comments field (Not sure of the exact field name) which states if the channel is functioning on a particular server at the particular time. I think we might need to look at that as well apart from Channel Status to determine if the channel is functioning at this time instance on a particular server.

    Thanks.

    Best Regards,

    Sudharshan N A

    (0) 
    1. Former Member Post author

      Hi Sudharashan ,

      Good to know you found this API useful 🙂

      1.) The state of the channel is actually picked from HTTP response of

      http://<host&gt;:<port>/AdapterFramework/ChannelAdminServlet?action=status&party=*&service=*&channel=*

      So to make sure the link returns you the recent status of the channel you can schedule it accordingly (Say btw 5 – 15 minutes)

      2.) As said earlier we make use of above http link to get the channel status here.The response reveal only the channel state and not the name of server nodes which is in error.

      So basically we might have to dig deeper to acheive what you have mentioned above. (I am not pretty sure if that’s possible either 🙂 ).

      Thanks,

      Kumaresh

      (0) 

Leave a Reply