Example: Test a connection to a data source

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

// "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;

/**
 * Tests a connection to a DataSource when WebSphere
 * Security is disabled.
 *
 * To run this example, the following must be done:
 *
 * 1)  Set the WAS_HOME environment variable to the location of
 *     your WebSphere Application Server for z/OS Configuration
 *     directory
 *
 *     Example:  export WAS_HOME=/WebSphereV5R1M0/AppServer
 *
 * 2)  Set the following environment variables:
 *
 *     export WAS_LIB=$WAS_HOME/lib
 *     export WAS_CLASSPATH=[DIRECTORY_CONTAINING_THIS_FILE]
 *     export WAS_CLASSPATH=$WAS_CLASSPATH:$WAS_LIB/jmxc.jar
 *     export WAS_CLASSPATH=$WAS_CLASSPATH:$WAS_LIB/wsexception.jar
 *     export WAS_CLASSPATH=$WAS_CLASSPATH:$WAS_LIB/admin.jar
 *     export WAS_CLASSPATH=$WAS_CLASSPATH:$WAS_LIB/wasjmx.jar
 *     export WAS_CLASSPATH=$WAS_CLASSPATH:$WAS_HOME/java/jre/lib/ext/mail.jar
 *     export WAS_CLASSPATH=$WAS_CLASSPATH:$WAS_LIB/ibmjlog.jar
 *     export WAS_CLASSPATH=$WAS_CLASSPATH:$WAS_LIB/utils.jar
 *
 * 3)  Execute the following commands:
 *
 *     javac -classpath $WAS_CLASSPATH TestDS.java
 *     java -classpath $WAS_CLASSPATH TestDS
 */
public class TestDS {

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

    /**
     * Main method.
     */
    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();
        } catch (Exception ex) {
            System.out.println("Caught this " + ex );
            ex.printStackTrace();
        }
    }


    /**
     * This method tests the DataSourceCfgHelper Mbean.
     */
    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 {
                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);
            }

            // First get 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);
            }

            String dsClassName = "com.ibm.db2.jcc.DB2ConnectionPoolDataSource";
            String providerClassPath = "/db2beta/db2710/classes/db2j2classes.zip";
            String[] signature = { "java.lang.String", "java.lang.String"};
            Object[] params = { dsClassName, providerClassPath};
            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);

            //---------------reload

            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()");
            }

            //---------------reload

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

            String user = "IBMUSER";
            String password = "IBMUSER";
            Properties props = new Properties();
            props.setProperty("databaseName", "LOC1");
            props.setProperty("dataStoreHelperClass", "com.ibm.websphere.rsadapter.DB2DataStoreHelper");
            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 ,providerClassPath, Locale.US};
            Object result2 = null;

            try {
                // OK lets test.
                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();
            }

            // the testConnectionToDataSource method doesn't always throw an exception if the test
            // fails; it only returns a String showing the results, so we can't really know if the
            // test was successful
            //
            // the best option here is to just print the String for the user

            System.out.println("Test Result:  " + result2);

        } 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();
        }
    }
}

Related concepts
Resource adapter
Data sources



Searchable topic ID:   testconbmp
Last updated: Jun 21, 2007 9:56:50 PM CDT    WebSphere Application Server for z/OS, Version 5.0.2
http://publib.boulder.ibm.com/infocenter/wasinfo/index.jsp?topic=/com.ibm.websphere.zseries.doc/info/zseries/ae/rdat_testconbmp.html

Library | Support | Terms of Use | Feedback