Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
kumaresh_d
Explorer

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 :smile: )

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 :smile: )

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

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

2 Comments
Labels in this area