Wednesday, September 5, 2012

JNDI Lookup for Jboss Server

Usage: For production it is possible the data wil migrate from one source to another. So when It happens you dont want to recompile your app rather just change configuration file. So here it Goes

Step 1:
  • Create Appname-ds.xml file
  • Save to to path : JBOSS_HOME/server/default/deploy
  • Modify contents of Appname-ds.xml:
Filename: Appname-ds.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE datasources
    PUBLIC "-//JBoss//DTD JBOSS JCA Config 1.5//EN"
    "http://www.jboss.org/j2ee/dtd/jboss-ds_1_5.dtd">
<datasources>
    <local-tx-datasource>
       <jndi-name>appDatasource</jndi-name>
       <use-java-context>false</use-java-context>
       <connection-url>jdbc:sqlserver:SomeConnectionString
       <driver-class>com.microsoft.sqlserver.jdbc.SQL.ServerDriver
       <user-name>SomeUser</user-name>
       <password>Somepassword</password>
    </local-tx-datasource>
</datasources>

Step2:
  •  Copy the code snippet to create statements
/**
    * @name connectdb
    * @return 1 if successful , -1 if Connection is unsuccessful 
*/
    public int connectdb()
    {
    int r =-1;
  
        Properties p = new Properties();    
        p.put( Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory" );
        p.put( Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces" );
        Constant.connection = null;
        Context ctx = null;
        try
        {
            ctx = new javax.naming.InitialContext( p );
            WrapperDataSource ds = (WrapperDataSource) ctx.lookup(appDatasource);
            Constant.connection = ds.getConnection();
            r=1;
        }
        catch ( Exception ex )
        {
            r= -1;
            ex.printStackTrace();
        }
        finally
        {
            if ( ctx != null )
                try {
                    ctx.close();
                } catch (NamingException e) {
                    e.printStackTrace();
                }
            System.out.println("Context Closed");
        }
        return r;
 } 
Step 3:
Rebuils your application
Clean Server : Delete Data,temp,work folder in JBOSS_HOME
Restart server
Publish

Step 4:
You are Done! :)

1 comment: