+

Search Tips   |   Advanced Search

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 our data source includes a WebSphere variable, the scope settings for both the variable and data source can affect the test connection results.

We can activate the test connection service using:


Verify scope settings

Associating WebSphere variables with data source configurations can elicit test connection results incongruent with the run-time behavior of the 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 the application server handles the scope settings of WebSphere variables at runtime, and how it handles those same scope settings for a test connection operation.

At runtime, WAS invokes a physical data source by resolving the appropriate variable at a level where one of the following criteria exists:

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.


Node level and cluster-level data sources

We can create node or cluster level configurations of the data sources for applications to use. To run the test connection on the data sources, however, we 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:

In some cases the error might be similar to the following message:

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 we create these data sources at the node scope or cluster scope, we 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 our 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.

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


Cell-level data source

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 dmgr 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 we 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, we can prevent the empty string from becoming the final value for the driver class path variable.

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 our data sources.

Bypassing variable lookups

We 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 we configure the class path identically on all nodes where the data source must function.


Activate 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

WAS allows us to test a connection from the administrative console by simply pushing a Test Connection button. On the collection page, we can select several data sources and test them all at once. Note that there are certain conditions that must be met first.

The following exception occurs when you click Test Connection to connect a Sybase data source from the administrative console.

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 our Sybase server in the interfaces file under /<sybase install directory>.

WsAdmin tool

The wsadmin tool provides a scripting interface to a full range of WAS 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. We 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.

We 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, we can test a connection by executing the testConnection method on the DataSourceCfgHelper MBean. This method allows us 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 Bean. In a WAS ND 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.

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 WAS WAS ND. The word Base in a comment line indicates that the following code applies to WAS.

/**
 * 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 we need to specify which node/process we 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 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 we 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 the 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.


Related:

  • WebSphere variables
  • Create, edit, and delete WebSphere variables
  • Testing a connection with the administrative console
  • Testing a connection using wsadmin
  • Testing data source connections
  • Administrative console scope settings