Java Tutorial - Java Scipt : Locating Resources

Java Tutorial - Java Scipt :

Locating Resources


The ResourceLocator class provides a place to put the code that is used to look up resources in the system. Often resources only need to be looked up once and can be cached for subsequent uses. The ResourceLocator is designed so it can be used by many classes, and it caches the things that it can cache. The source code for the ResourceLocator is provided below: package com.oldfriends.utils;

import java.sql.*;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import javax.sql.DataSource;
public class ResourceLocator
{
private static Context ctx;
private static DataSource datasource;
private static final String DSNAME = “MySqlDS”;
public static Context getInitialContext()
throws NamingException, ClassCastException
{
Context myctx;
if( ResourceLocator.ctx == null )
{
myctx = new InitialContext();
ResourceLocator.ctx = myctx;
}
else
myctx = ResourceLocator.ctx;
return myctx;
}
public static EJBHome getLocalHomeInterface(String jndiName)
throws NamingException, ClassCastException
{
Context myctx = ResourceLocator.getInitialContext();
EJBHome home = (EJBHome)myctx.lookup(jndiName);
return home;
}
public static EJBHome getHomeInterface(
String jndiName, Class theHomeClass )
throws NamingException, ClassCastException
{
EJBHome home;
Context myctx = ResourceLocator.getInitialContext();
Object obj = myctx.lookup(jndiName);
home = (EJBHome)PortableRemoteObject.narrow( obj, theHomeClass );
return home;
}
public static DataSource getDataSource( String jndiName )
throws NamingException
{
DataSource ds = null;
if( ResourceLocator.ctx == null )
{
ResourceLocator.ctx = new InitialContext();
}
ds = (DataSource)ResourceLocator.ctx.lookup(jndiName);
return ds;
}
public static Connection getConnection()
throws NamingException, SQLException
{
Connection conn;
if(datasource==null)
{
datasource = ResourceLocator
.getDataSource(ResourceLocator.DSNAME);
}
conn = datasource.getConnection();
return conn;
}
}

The ResourceLocator shown here is a very simple, almost minimalist, one. It provides methods to:

·         Retrieve and cache the initial context
·         Look up and convert LocalHome interfaces
·         Look up and convert home interfaces
·         Look up and cache DataSources
·         Get DataBase connections

Using a ResourceLocator often provides for more efficient access to resources and minimizes the knowledge needed to access the resources in various classes. Use of a ResourceLocator is considered to be a J2EE best practice.