Network Deployment (Distributed operating systems), v8.0 > Administer applications and their environment > Administer Data access resources > Administer data access applications > Configure a JDBC provider and data source


Test connection service

The test connection service for validating data source configurations...

  1. Uses a administrative consoletestConnection operation to instantiate the data source configuration.
  2. Gets a connection
  3. Immediately closes the connection

After creating new data sources under cluster scope, restart nodes using stopNode.sh/startNode.sh.


Scope settings

Associate WebSphere variables with your data source configurations can elicit test connection results that are 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. Understanding the difference helps you create successful data source configurations.

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.

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

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.

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

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

Use cell scope resources only if all nodes that need access to the data source, including the dmgr 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

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 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, wsadmin.sh, or a Java stand-alone program. Each process invokes the same methods on the same MBean.
Administrative console

WAS allows you to test a connection from the administrative console by simply pushing a button: the Data source collection, Data source settings, v4 data source collection, and v4 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. See the topic, Testing a connection with the administrative console.

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

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, 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 WAS ND installation of Application Server, you connect to the JMX server running in the dmgr, 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) {
       .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 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();
  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();
  } catch (Exception ex) {
 System.out.println("General exception occurred");
 ex.printStackTrace();
  }
 }
}

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.
WebSphere variables
Create, edit, and delete WebSphere variables
Test a connection with the administrative console
Test a connection using wsadmin
Test data source connections using wsadmin.sh


Related


Administrative console scope settings

+

Search Tips   |   Advanced Search