Thursday, October 4, 2012

How to access Carbon data-source from a web-application using WSO2 Application Server 5.0.0

Applies To :

WSO2 Application Server 5.0.0


STEP 1 : Run RMI provider

Go to cammad line and run following command to run rmi provider (rmiregistry)
$ rmiregistry 2199


STEP 2 : Create carbon data-source

Go to "configure" tab and select  "Data Sources". 



Click on "Add Data Source" to add a new data source.

 

Add relevant configurations for the required fields  (Name, Driver, URL etc.)





















Expand "Expose as a JNDI Data Source" section and give a name and tick the "Use Data Source Factory" checkbox. And also add following JNDI properties 

Property 1

Name :  java.naming.factory.initial 
Value :  com.sun.jndi.rmi.registry.RegistryContextFactory

Property 2

Name :  java.naming.provider.url 
Value :  rmi://localhost:2199







Save the configurations.

STEP 3 : Refference Data Source from Web Application

Then you will be able to access the Data source as shown below.
Hashtable env = new Hashtable();  

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); //same context factory class provided when creating carbon data-source. 

env.put(Context.PROVIDER_URL, "rmi://localhost:2199"); //same provider url provided when creating carbon data-source. 

InitialContext ctx = new InitialContext(env);  

DataSource ds = (DataSource) ctx.lookup("jndiDS"); //"jndiDS" is the carbon data-source name that i have created. Please note that you may need to add commons-dbcp.jar and commons-pool.jar to web-app class path to do this cast.  

conn = ds.getConnection(); 





When we consider following line of code, 
DataSource ds = (DataSource) ctx.lookup("jndiDS"); 

 
You don't need to search JNDI data source as java:/comp/env/jdbc/jndiDS. You only need to search for jndiDS. This feature has been added for WSO2 Application Server 5.0.0 to increase the usability.