Example: Test a connection to a data source

This resource adapter test program ensures that the MBean interfaces work. The following interfaces are tested:

See the Code example disclaimer for legal information about these code examples.

//
// This program may be used, executed, copied, modified and distributed without royalty for the 
// purpose of developing, using, marketing, or distributing.
//
// Product 5630-A36,  (C) COPYRIGHT International Business Machines Corp., 2001, 2002
// All Rights Reserved * Licensed Materials - Property of IBM
//

import java.util.*;
import javax.sql.DataSource;
import javax.transaction.*;
import javax.management.*;

import com.ibm.websphere.management.*;
import com.ibm.websphere.management.configservice.*;
import com.ibm.ws.exception.WsException;
import com.ibm.websphere.rsadapter.DSPropertyEntry;

/**
 * Resource adapter test program to make sure that the MBean interfaces work.
 * Following interfaces are tested
 * 
 *  -getPropertiesForDataSource()
 *  -reload()
 *  -testConnectionToDataSource()
 * 
 * 
 * We need following to run
 *
 *      From an iSeries command line:
 *
 *   -> QSHELL   
 *   (Start the QSHELL environment)
 *
 *   -> cd (yourDirectory)   
 *  (change current directory to the directory that holds the java source)    
 *
 *   -> . /QIBM/ProdData/WebASE51/ASE/base/bin/setupClient
 *  (produce the $JAVA_FLAGS_EXT environment variable)
 *
 *   -> javac -extdirs  /QIBM/ProdData/WebASE51/ASE/base/lib -d . testDS.java
 *   (compile the testDS class)
 *
 *   -> java $JAVA_FLAGS_EXT testDS
 *   (call the program)             
 * 
 */
public class testDS {

 String port = "8880";
  String host = "localhost";
  final static boolean verbose = true;

/**
 * Main method.
 * 
 * @param args   - Not used 
 */
public static void main(String[] args) {
 testDS cds = new testDS();
 try {
  cds.run(args);
  } catch (com.ibm.ws.exception.WsException ex) {
  System.out.println("Caught this " + ex   );
  ex.printStackTrace();
  //ex.getCause().printStackTrace();
  } catch (Exception ex) {
  System.out.println("Caught this " + ex );
  ex.printStackTrace();
  }
}

 /**
  * This method tests the DataSourceCfgHelper Mbean.
  * 
  * @param args  - Not used
  * @exception Exception
  */
public void run(String[] args) throws Exception {

 try {
 System.out.println("Connecting to the application server.......");

 /*************************************************************************/
 /**    Initialize the AdminClient                                        */
 /*************************************************************************/
Properties adminProps = new Properties();
 adminProps.setProperty(AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP);
 adminProps.setProperty(AdminClient.CONNECTOR_HOST, host);
 adminProps.setProperty(AdminClient.CONNECTOR_PORT, port);
 AdminClient adminClient = null;
 try { 
    /* Port 8880 must be listening when this program is called or the SOAP connection will fail */
    adminClient = AdminClientFactory.createAdminClient(adminProps);
 } catch (com.ibm.websphere.management.exception.ConnectorException ce) {
    System.out.println("Cannot make a connection to the application server\n"+ce);
    System.exit(1);
 }

 /*************************************************************************/
 /**    Locate the Mbean                                                  */
 /*************************************************************************/
 ObjectName handle = null;
 try {
    ObjectName queryName = new ObjectName("WebSphere:type=DataSourceCfgHelper,*");
    Set s = adminClient.queryNames(queryName, null);
    Iterator iter = s.iterator();
    if (iter.hasNext()) handle = (ObjectName)iter.next();
 } catch (MalformedObjectNameException mone) {
    System.out.println("Check the program variable queryName" + mone);
 } catch (com.ibm.websphere.management.exception.ConnectorException ce) {
    System.out.println("Cannot connect to the application server" + ce);
 }

 //System.out.println("Connected to the application server" + handle);

 /*************************************************************************/
 /**    Call the Mbean to get the data source properties                  */
 /*************************************************************************/
 String dsClassName = "com.ibm.db2.jdbc.app.DB2StdXADataSource";
 String providerLibPath = "/QIBM/ProdData/Java400/ext/db2_classes.jar";
 String[] signature = { "java.lang.String", "java.lang.String"};
 Object[] params = { dsClassName, providerLibPath};
 Object result = null;

 if (verbose) {
    System.out.println("Calling getPropertiesForDataSource() for " + dsClassName + "\n");
 }
 try {
    // get the properties
    result = adminClient.invoke(handle, "getPropertiesForDataSource", params, signature);
 } catch (MBeanException mbe) {
    if (verbose) {
       System.out.println("\tMbean Exception " + dsClassName);
    }
 } catch (InstanceNotFoundException infe) {
    System.out.println("Cannot find " + dsClassName);
 } catch (Exception ex) {
    System.out.println("Exception occurred calling getPropertiesForDataSource() for " + dsClassName + ex);
 }

 // Pretty print what we found
 Iterator propIterator = ((List)result).iterator();
 System.out.println(format("Name",21)+ "|" + format("Default Value",34) + "|" + 
      format("Type",17) +"|Reqd");
 String line = "_______________________________________________________________________________";
 System.out.println(line);
  while (propIterator.hasNext()) {
    DSPropertyEntry dspe = (DSPropertyEntry)propIterator.next();
    System.out.print(format(dspe.getPropertyName(),21)+"|"+ format(dspe.getDefaultValue(),34) + "|");
System.out.println(format(dspe.getPropertyType(),17) +"|"+ ((dspe.isRequired())? " Y" : " N"));
 }
 System.out.println(line);


/*************************************************************************/
/** Invoke the reload function from the AdminClient to pickup the        */
/*  data source from the naming space.                                   */
/*************************************************************************/

 if (verbose) {
    System.out.println("Calling reload()");
 }
 try {
    result = adminClient.invoke(handle, "reload", new Object[] {}, new String[] {});
 } catch (MBeanException mbe) {
   if (verbose) {
       System.out.println("\tMbean Exception calling reload" + mbe);
    }
 } catch (InstanceNotFoundException infe) {
   System.out.println("Cannot find reload ");
 } catch (Exception ex) {
    System.out.println("Exception occurred calling reload()"  + ex);
 }
 if (result==null && verbose) {
    System.out.println("OK reload()");
 }

 /*************************************************************************/
 /**  Start to test the connection to the database                        */
 /*************************************************************************/

 if (verbose) {
    System.out.println("\nTesting connection to the database using " + dsClassName);
 }


 String user = "db2admin";
 String password = "db2admin";
 Properties props = new Properties();
 props.setProperty("databaseName", "section");
        
 // There are two ways to pass the locale: In WS 5.0, you can only pass in the 
 // language and the country in a String format. In WS 5.0.1 release, you can also pass
 // in a Locale object.
 // String[] signature2 = { "java.lang.String", "java.lang.String", "java.lang.String",           
 //   "java.util.Properties", "java.lang.String","java.util.Locale"};
 // Object[] params2 = { dsClassName, user, password,props ,providerLibPath, Locale.US};

  Object result2 = null;
     
 String[] signature2 = { "java.lang.String", "java.lang.String", 
 "java.lang.String", "java.util.Properties", "java.lang.String
 "java.lang.String","java.lang.String");
Object[] params2 = { dsClassName, user, password,props ,providerLibPath, "EN", "US"};
       
 
try {
   
    result2 = adminClient.invoke(handle, "testConnectionToDataSource", params2, signature2);
 } catch (MBeanException mbe) {
    if (verbose) {
       System.out.println("\tMbean Exception " + dsClassName);
    }
 } catch (InstanceNotFoundException infe) {
    System.out.println("Cannot find " + dsClassName);
 } catch (RuntimeMBeanException rme) {
    Exception ex = rme.getTargetException();
    ex.printStackTrace(System.out);
    throw ex;
 } catch (Exception ex) {
    System.out.println("Exception occurred calling testConnectionToDataSource() 
	for " + dsClassName + ex);
    ex.printStackTrace();
 }

 if (result2 != null) {
    System.out.println("ERROR Result= " + result2);
} else if (verbose) {
    System.out.println("OK testConnectionToDataSource()");
 }
 
 } catch (RuntimeOperationsException roe) {
     Exception ex = roe.getTargetException();
     ex.printStackTrace(System.out);
      throw ex;
      } catch (Exception ex) {
         ex.printStackTrace(System.out);
         throw ex;
      }
   }

   /**
    * Format the string right justified in the space provided, 
    * or truncate the string.
    * 
    * @param in
    * @param length
    * @return 
    */
   public String format(Object in, int length) {
      if (in ==null) {
         in = "-null-";
      }

      String ins = in.toString();
      int insLength = ins.length();
      if ( insLength > length) {
         return ins.substring(0,length);
      } else {
         StringBuffer sb = new StringBuffer(length);
         while (length - insLength > 0) {
            sb.append(" ");
            length--;
         }
         sb.append(ins);
         return sb.toString();
      }
   }
}

Note: Example may be wrapped for display purposes.