Test connection service

WebSphere® Application Server provides a test connection service for validating data source configurations. The testConnection operation instantiates the data source configuration, gets a connection, and then immediately closes the connection.

If the definition of your data source includes a WebSphere variable, you need to determine how your scope settings for both the variable and data source can affect the test connection results. Your next step is to choose which of the three ways you want to activate the test connection service: through the administrative console, the wsadmin tool, or a Java™ stand-alone program.

Verifying your scope settings

Associating WebSphere variables with your data source configurations can elicit test connection results that are incongruent with the run-time behavior of your application. In some cases, a test connection operation fails, but the physical data source functions normally during application runtime. The cause of the potential conflict is the difference between how your application server handles the scope settings of WebSphere variables at runtime, and how it handles those same scope settings for a test connection operation. Understanding the difference helps you create successful data source configurations.

At runtime, WebSphere Application Server invokes a physical data source by resolving the appropriate variable at a level where one of the following criteria exists:
  • The scope of the variable can contain the data source configuration; that is, the variable has the larger scope.
  • The variable and the data source have identical scopes.
Application Server meets these conditions by attempting to resolve the variable at each level of the scope spectrum. That is, the product tries to resolve the variable in the server scope, then the cluster scope, then the node scope, and lastly the cell scope.
However, Application Server tests connections at one scope only; it performs the test operation in the JVM of the same scope as that of the data source configuration. The product attempts to resolve the driver class path variable at that scope only.
Table 1. Correlation of data source scope with the test connection JVM . The correlation of Cell, Node, Cluster, and Server data source scope with the corresponding test connection JVM where the operation occurs.
Data source scope JVM where the test connection operation occurs
Cell manager process
Node Node agent process (of the relevant node)
Cluster Node agent for each node that contains a cluster member
Server Server; if the server is unavailable, the test connection operation is retried in the node agent for the node that contains the application server.
[z/OS]Restriction: In a network deployment implementation of the application server, you cannot test connections for the following data sources at the node level or cluster level. Therefore, when you create these data sources at the node scope or cluster scope, you might want to temporarily create the same configurations at a server scope for testing purposes. Run the test connection operation at the server level to determine if the data source settings are valid for your overall configuration.
  • IBM Data Server Driver for JDBC and SQLJ data source with driver type 2
  • DB2 Universal JDBC Driver Provider data source with driver type 2
You can create node level or cluster level configurations of the data sources for application use; these configurations should work properly in the run time environment. To successfully run the test connection on the data sources, however, you must test the data sources at the server level only. The application server will issue the following exception for a test connection at the node level:
java.sql.SQLException: Failure in loading T2 native library db2jcct2DSRA0010E:
SQL state = null, Error Code = -99,999
In some cases, though, the error might be similar to one of the following messages:
T2zOS exception: [jcc][T2zos]T2zosReusableConnection.flowConnect:initRRSAFAttach
:2528: Connection dead
Failure in loading native library db2jcct2zos4_64,                       
java.lang.UnsatisfiedLinkError: db2jcct2zos4_64 (Not found in            
java.library.path):  ERRORCODE=-4472, SQLSTATE=null DSRA0010E: SQL State 
= null, Error Code = -4,472. 
Both of these data sources are based on type 2 JDBC drivers, which need access to the T2 native libraries. The run time environment for the application server provides that access for data sources in a server process, but the test connection service does not provide access to these native files when it is run in the node agent process.

Therefore, when you create these data sources at the node scope or cluster scope, you might want to temporarily create the same configurations at a server scope for testing purposes. Run the test connection operation at the server level to determine if the data source settings are valid for your overall configuration.

If the scope of the WebSphere variable is smaller than that of the data source, the test connection operation fails. The following table shows the scenarios that produce this failure, as well as those that produce success.
Table 2. Test connection results for different data source and WebSphere variable combinations . The test results for different data source and WebSphere variable combinations are shown in the table.
Data source scope Cell level variables Node level variables Server level variables
Cell level Ok Fail Fail
Node level Ok Ok Fail
Server level Ok Ok Ok

Contrary to expectations, these test connection failures generally do not translate into run-time failures. Ensure that the location of your JDBC driver files is accessible to every client that must use the data source, and configure your WebSphere variable with the full path of that location.

Test connection success, but runtime failure

However, one of the scope combinations listed in Table 2 can produce the reverse scenario: the test connection operation succeeds, but the data source fails at runtime. This anomaly occurs in the case of a cell-scoped data source that uses a cell-scoped WebSphere variable. The connection test is successful because the operation takes place in the deployment manager process (as indicated in Table 1), where Application Server can resolve the cell-scoped variable. That data source can fail at runtime because the cell-scoped variable might be overridden with a null value.

When you create a node, Application Server creates environment variables for all supported JDBC drivers at the node scope, and initializes each variable with an empty string. Because an application server attempts to resolve variables from the low end of the scope spectrum to the high end, the node scope variable overrides the cell scope variable at runtime. The server reads the empty string and accepts it as the JDBC driver class path. The null class path elicits a classNotFound exception when the server attempts to use the data source.

Using either one of the Application Server administrative options, you can prevent the empty string from becoming the final value for the driver class path variable.

  • Using the WebSphere Application Server administrative console: The data source wizard program copies the value of the cell-scoped variable (which you specify in the JDBC provider creation wizard) to the node-scoped variable of the same name. The wizard program performs this copy operation only if the node-scoped variable has the empty string value; thus the program does not change a valid class path that you specified earlier.
    To ensure that the data source works with the node-scoped variable at runtime, follow these steps:
    1. Install the JDBC driver files on the deployment manager node, as well as every node where the data source must function.
    2. Use the driver file path on the deployment manager to define the WebSphere variable for a JDBC provider at the cell scope.
    3. Ensure that the data source is associated with the deployment manager JDBC provider, and has the same cell scope.
      Important: Ensure success by installing the driver files in locations with identical full-path names on all nodes, including the deployment manager node. Otherwise, the same scenario of test connection success, but run-time failure, is likely to reoccur.
  • Using the wsadmin scripting tool: To make the data source work for both the test connection operation and runtime, create the same driver class path configurations at the cell scope and at all relevant node scopes. Follow these steps:
    1. Install the JDBC driver files on the deployment manager node; use that path name to define the driver class path variable for a JDBC provider at the cell scope.
    2. Ensure that the data source is associated with the deployment manager JDBC provider, and has the same cell scope.
    3. On each node where the data source must function, install the JDBC driver files and use the path to define the WebSphere variable for a JDBC provider at the node scope. Each of these providers must have the same configuration.
      Important: Ensure success by installing the driver files in locations with identical full-path names on all nodes, including the deployment manager node. Otherwise, the same scenario of test connection success, but run-time failure, is likely to reoccur.

Use cell scope resources only if all nodes that need access to the data source, including the deployment manager node, run on the same platform and have the JDBC drivers installed in the same location. Otherwise, use the node scope as the largest scope setting for your data sources.

Bypassing variable lookups

You can bypass the environment variable lookups by changing the class path entries for the JDBC provider to hard-coded values. However, this strategy succeeds only if you configure the class path identically on all nodes where the data source must function.

Activating the test connection service

There are three ways to activate the test connection service: through the administrative console, the wsadmin tool, or a Java stand-alone program. Each process invokes the same methods on the same MBean.

Administrative console

WebSphere Application Server allows you to test a connection from the administrative console by simply pushing a button: the Data source collection, Data source settings, Version 4 data source collection, and Version 4 data source settings pages all have Test Connection buttons. After you define and save a data source, you can click this button to ensure that the parameters in the data source definition are correct. On the collection page, you can select several data sources and test them all at once. Note that there are certain conditions that must be met first. For more information, see the topic, Testing a connection with the administrative console.

Note: The following exception occurs when you click Test Connection to connect a Sybase data source from the administrative console.
Test connection failed for data source isagent on server server1 at node 
svtaix24Node01 with the following exception: java.lang.Exception: 
java.sql.SQLException: JZ006: Caught IOException: java.net.ConnectException: A 
remote host refused an attempted connect operation.DSRA0010E: SQL State = JZ006, 
Error Code = 0
This exception occurs when the Sybase data source port number is not matched to the port configured in Sybase server. The default port number is 5000. Check the port number of your Sybase server in the interfaces file under /<sybase install directory>.

WsAdmin tool

The wsadmin tool provides a scripting interface to a full range of WebSphere Application Server administration activities. Because the Test Connection functionality is implemented as a method on an MBean, and wsadmin can invoke MBean methods, wsadmin can be utilized to test connections to data sources. You have two options for testing a data source connection through wsadmin:

The AdminControl object of wsadmin has a testConnection operation that tests the configuration properties of a data source object. For information, see the topic, Testing a connection using wsadmin.

You can also test a connection by invoking the MBean operation. Use the example in the topic, Example: Testing data source connection using wsadmin, as a guide for this technique.

Java stand-alone program

Finally, you can test a connection by executing the testConnection method on the DataSourceCfgHelper MBean. This method allows you to pass the configuration ID of the configured data source. The Java program connects to a running Java Management Extensions (JMX) server to access the MBean. In a WebSphere Application Server Network Deployment installation of Application Server, you connect to the JMX server running in the deployment manager, usually running on port 8879.

The return value from this invocation is either 0, a positive number, or an exception. 0 indicates that the operation completed successfully, with no warnings. A positive number indicates that the operation completed successfully, with the number of warnings. An exception indicates that the test of the connection failed.

Note: Example: Testing a connection using testConnection(ConfigID).

The following sample code creates a data source instance and an associated connection instance, and tests them to ensure database connectivity.

This program uses JMX to connect to a running server and invoke the testConnection method on the DataSourceCfgHelper MBean. The acronym ND in a comment line indicates that the following code applies to WebSphere Application Server WebSphere Application Server Network Deployment. The word Base in a comment line indicates that the following code applies to WebSphere Application Server.

/**
 * Description
 * Resource adapter test program to make sure that the MBean interfaces work.
 * Following interfaces are tested
 * 
 *  ---  testConnection()
 * 
 * 
 * We need following to run
 * C:\src>java -Djava.ext.dirs=C:\WebSphere\AppServer\lib;C:\WebSphere\AppServer\java\jre\lib\ext testDSGUI
 * must include jre for log.jar and mail.jar, else get class not found exception
 * 
 * 
 */

import java.util.Iterator;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;

import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.RuntimeMBeanException;
import javax.management.RuntimeOperationsException;

import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.management.AdminClientFactory;
import com.ibm.ws.rsadapter.exceptions.DataStoreAdapterException;

public class testDSGUI {

//Use port 8880 for a Base installation or port 8879 for ND installation
String port = "8880";
// String port = "8879";
String host = "localhost";
final static boolean verbose = true;

// eg a configuration ID for DataSource declared at the node level for Base
private static final String resURI = "cells/cat/nodes/cat|resources.xml#DataSource_1";

// eg a 4.0 DataSource declared at the node level for Base
//    private static final String resURI = "cells/cat/nodes/cat|resources.xml#WAS40DataSource_1";

// eg Apache Derby DataSource declared at the server level for Base
//private static final String resURI = "cells/cat/nodes/cat/servers/server1/resources.xml#DataSource_6";

// eg node level DataSource for ND
//private static final String resURI = "cells/catNetwork/nodes/cat|resources.xml#DataSource_1";

// eg server level DataSource for ND
//private static final String resURI = "cells/catNetwork/nodes/cat/servers/server1|resources.xml#DataSource_4";

// eg cell level DataSource for ND
//private static final String resURI = "cells/catNetwork|resources.xml#DataSource_1";

 public static void main(String[] args) {
  testDSGUI cds = new testDSGUI();
  cds.run(args);
 }

/**
 * This method tests the ResourceMbean.
 * 
 * @param args
 * @exception Exception
 */
 public void run(String[] args) {

  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("NLS: Cannot make a connection to the application server\n");
	    ce.printStackTrace();
	    System.exit(1);
	}

       /*************************************************************************/
       /**    Locate the Mbean                                                  */
       /*************************************************************************/
	ObjectName handle = null;
	try {
                // Send in a locator string 
                // eg for a Base installation this is enough
                ObjectName queryName = new ObjectName("WebSphere:type=DataSourceCfgHelper,*");

                // for ND you need to specify which node/process you would like to test from
                // eg run in the server
//ND: ObjectName queryName = new OjectName
				("WebSphere:cell=catNetwork,node=cat,process=server1,type=DataSourceCfgHelper,*");
                // eg run in the node agent
//ND: ObjectName queryName = new ObjectName
				("WebSphere:cell=catNetwork,node=cat,process=nodeagent,type=DataSourceCfgHelper,*");
//ND: eg run in the   Manager
//ND: ObjectName queryName = new ObjectName
			("WebSphere:cell=catNetwork,node=catManager,process=dmgr,type=DataSourceCfgHelper,*");
	Set s = adminClient.queryNames(queryName, null);
	Iterator iter = s.iterator();
	while (iter.hasNext()) {
                // use the first MBean that is found
	 	handle = (ObjectName) iter.next();
		System.out.println("Found this ->" + handle);
		}
		if (handle == null) {
			System.out.println("NLS: Did not find this MBean>>" + queryName);
			System.exit(1);
		}
	} 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);
	}

         /*************************************************************************/
         /**           Build parameters to pass to Mbean                          */
         /*************************************************************************/
	String[] signature = { "java.lang.String" };
	Object[] params = { resURI };
	Object result = null;

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

	try {
               /*************************************************************************/
               /**  Start to test the connection to the database                        */
               /*************************************************************************/
		result = adminClient.invoke(handle, "testConnection", params, signature);
	} catch (MBeanException mbe) {
		// ****** all user exceptions come in here
		if (verbose) {
			Exception ex = mbe.getTargetException(); // this is the real exception from the Mbean
			System.out.println("\nNLS:Mbean Exception was received contains" + ex);
			ex.printStackTrace();
			System.exit(1);
		}
	} catch (InstanceNotFoundException infe) {
		System.out.println("Cannot find" + infe);
	} catch (RuntimeMBeanException rme) {
		Exception ex = rme.getTargetException();
		ex.printStackTrace(System.out);
		throw ex;
	} catch (Exception ex) {
		System.out.println("\nUnexpected Exception occurred:" + ex);
		ex.printStackTrace();
	}

         /*************************************************************************/
         /**  Process the result.  The result will be the number of warnings      */
         /**  issued.  A result of 0 indicates a successful connection with       */
         /**  no warnings.                                                        */
         /*************************************************************************/

	//A result of 0 indicates a successful connection with no warnings.
	System.out.println("Result=" + result);

  } catch (RuntimeOperationsException roe) {
	Exception ex = roe.getTargetException();
	ex.printStackTrace(System.out);
  } catch (Exception ex) {
	System.out.println("General exception occurred");
	ex.printStackTrace(System.out);
  }
 }
}
Tip: Ensure that you run the test connection service at the same level as an existing data source. For example, do not run the test connection service at the node level if your data source is configured on the server level. If the test connection service and the data source configuration do not exist on the same level, a failure to load exception might result. In this situation, source the db2profile script on the machine and ensure that the environment contains pointers to the DB2® native libraries. The db2profile script exists in the root directory of the DB2 user ID.