Wednesday, October 17, 2012

Connect to Websphere JDBC datasource from standalone Client:

We may hit a situation to connect to configured Websphere JDBC datasource from standalone java client and need appropriate drivers for target database we are connecting to.

There are no additional jars need to be downloaded from IBM website except database driver jar and we will be using IBM command(setupCmdLine.sh) to setup environment and connect to Oracle database.

Script to setup WAS environment and call Java Client:

# Use IBM script to initialize common WebSphere runtime settings
REPLACE_WAS_HOME=${WAS_HOME}
. $WAS_HOME/bin/setupCmdLine.sh

# Add oracle drivers to classpath
CLASSPATH="$WAS_CLASSPATH:/tmp/JDBC/ojdbc5.jar:."

# Specify JVM
JAVA="$JAVA_HOME/bin/java"

# Specify JVM command line options
JAVA_OPTS="-Djava.ext.dirs=$JAVA_HOME/jre/lib/ext:$WAS_EXT_DIRS:$WAS_HOME/plugins"
JAVA_OPTS="$JAVA_OPTS  -cp $CLASSPATH"
$JAVA $JAVA_OPTS ConnectJDBC

Java Client:

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.Serializable;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.io.*;

public class ConnectJDBC {

public static void connect() {
final Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
env.put(Context.PROVIDER_URL, "corbaloc:iiop::,::,::");

final Context jndiContext;
try {
jndiContext = new InitialContext(env);
} catch (NamingException e) {
System.err.println("Could not create JNDI API context: "+ e.toString());
System.exit(1);
return;
}

try {
javax.sql.DataSource ds =  ((javax.sql.DataSource)jndiContext.lookup(""));
Connection conn =ds.getConnection(,);
String SQL = "{call . }";
} catch (Exception e) {
System.err.println("Could not perfrom JDBC Procedure Call: "+ e.toString());
System.exit(2);
}
}

public static void main(String[] args) {
connect();
}
}

Note: Please make sure the script #setupCmdLine.sh has appropriate permissions to avoid any failures. Note that standalone client will not be able use component-managed authentication for database and it's responsibility of client to provide authentication details during database connection..

Dependency Jars:

The standalone client need the following jars to connect to JDBC datasource configured in websphere when we are unable to use #setupCmdLine.sh script to setup the environment.

com.ibm.ws.runtime_6.1.0.jar
ojdbc14.jar
rsadbutils.jar
rsahelpers.jar
sibc.jndi.jar
sibc.jms.jar
sibc_install-o0902.06.jar
com.ibm.jaxws.thinclient_6.1.0.jar

Note: I performed all these tests using eclipse editor and Websphere 6.1 server.

No comments:

Enter your Comments