package samples.ejb;
import java.lang.reflect.*;
import java.util.*;
import javax.rmi.PortableRemoteObject;
import javax.naming.NamingException;
import javax.naming.InitialContext;
import net.sf.voruta.DbException;
/**
* Adapter / proxy.
* Adapts remote DAO view as local
* @author baliuka
*/
public class Client {
static Map instances = new Hashtable();
ServerHome home;
Server server;
Class cls;
/** Creates a new instance of Client and starts EJB session*/
private Client(Class cls) {
this.cls = cls;
try{
InitialContext initialContext = new InitialContext();
try {
java.lang.Object objRef = initialContext.lookup("voruta/Server");
home = (ServerHome)PortableRemoteObject.narrow(objRef, ServerHome.class);
server = home.create();
} finally {
initialContext.close();
}
}catch(Exception e){
throw new DbException(e);
}
}
/**
*
* @return remote DAO proxy
*
*/
public Object create(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{cls}, new InvocationHandler(){
public Object invoke(Object obj, Method method, Object[] obj2) throws java.lang.Throwable {
return server.invoke(cls,method.getName(),method.getParameterTypes(),obj2);
}
}
);
}
/**
* Ends EJB Session
*/
public void remove(){
try{
server.remove();
}catch(Exception e){
throw new DbException(e);
}
}
/**
* factory method
*
*/
public static Client getInstance(Class cls){
Client instance = (Client)instances.get(cls);
if(instance == null){
instance = new Client(cls);
instances.put( cls, instance);
}
return instance;
}
}