package org.jboss.ejb.plugins.local;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import javax.ejb.EJBLocalObject;
import javax.naming.InitialContext;
public abstract class LocalProxy implements Serializable
{
static final long serialVersionUID = 8387750757101826407L;
protected static final Object[] EMPTY_ARGS = {};
protected static final Method TO_STRING;
protected static final Method HASH_CODE;
protected static final Method EQUALS;
protected static final Method GET_PRIMARY_KEY;
protected static final Method GET_EJB_HOME;
protected static final Method IS_IDENTICAL;
protected static final Method REMOVE;
protected String jndiName;
protected transient BaseLocalProxyFactory factory;
static
{
try
{
final Class[] empty = {};
final Class type = EJBLocalObject.class;
GET_PRIMARY_KEY = type.getMethod("getPrimaryKey", empty);
GET_EJB_HOME = type.getMethod("getEJBLocalHome", empty);
IS_IDENTICAL = type.getMethod("isIdentical", new Class[] { type });
REMOVE = type.getMethod("remove", empty);
}
catch (Exception e)
{
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
static
{
try
{
final Class[] empty = {};
final Class type = Object.class;
TO_STRING = type.getMethod("toString", empty);
HASH_CODE = type.getMethod("hashCode", empty);
EQUALS = type.getMethod("equals", new Class[] { type });
}
catch (Exception e)
{
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
protected String getJndiName()
{
return jndiName;
}
protected abstract Object getId();
public LocalProxy(String jndiName, BaseLocalProxyFactory factory)
{
this.jndiName = jndiName;
this.factory = factory;
}
Boolean isIdentical(final Object a, final Object b)
{
final EJBLocalObject ejb = (EJBLocalObject)a;
Boolean isIdentical = Boolean.FALSE;
if( ejb != null )
{
isIdentical = new Boolean(ejb.toString().equals(b));
}
return isIdentical;
}
String toStringImpl()
{
return jndiName + ":" + getId();
}
public Object invoke(final Object proxy, final Method m, Object[] args)
throws Throwable
{
Object id = getId();
Object retValue = null;
if (m.equals(TO_STRING))
{
retValue = toStringImpl();
}
else if (m.equals(EQUALS))
{
retValue = invoke(proxy, IS_IDENTICAL, args );
}
else if (m.equals(HASH_CODE))
{
retValue = new Integer(id.hashCode());
}
else if (m.equals(GET_PRIMARY_KEY))
{
retValue = id;
}
else if (m.equals(GET_EJB_HOME))
{
InitialContext ctx = new InitialContext();
return ctx.lookup(jndiName);
}
else if (m.equals(IS_IDENTICAL))
{
retValue = isIdentical(args[0], toStringImpl());
}
return retValue;
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
factory = (BaseLocalProxyFactory) BaseLocalProxyFactory.invokerMap.get(jndiName);
}
private void writeObject(ObjectOutputStream out)
throws IOException
{
out.defaultWriteObject();
}
}