package org.jboss.naming;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.LinkRef;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.NameNotFoundException;
import org.jboss.system.ServiceMBean;
import org.jboss.system.ServiceMBeanSupport;
public class NamingAlias
extends ServiceMBeanSupport
implements NamingAliasMBean
{
private String fromName;
private String toName;
public NamingAlias()
{
this(null, null);
}
public NamingAlias(final String fromName, final String toName)
{
this.fromName = fromName;
this.toName = toName;
}
public String getFromName()
{
return fromName;
}
public void setFromName(String name) throws NamingException
{
removeLinkRef(fromName);
this.fromName = name;
createLinkRef();
}
public String getToName()
{
return toName;
}
public void setToName(String name) throws NamingException
{
this.toName = name;
createLinkRef();
}
protected void startService() throws Exception
{
if( fromName == null )
throw new IllegalStateException("fromName is null");
if( toName == null )
throw new IllegalStateException("toName is null");
createLinkRef();
}
protected void stopService() throws Exception
{
removeLinkRef(fromName);
}
private void createLinkRef() throws NamingException
{
if( super.getState() == ServiceMBean.STARTING || super.getState() == ServiceMBean.STARTED )
{
InitialContext ctx = new InitialContext();
LinkRef link = new LinkRef(toName);
Context fromCtx = ctx;
Name name = ctx.getNameParser("").parse(fromName);
String atom = name.get(name.size()-1);
for(int n = 0; n < name.size()-1; n ++)
{
String comp = name.get(n);
try
{
fromCtx = (Context) fromCtx.lookup(comp);
}
catch(NameNotFoundException e)
{
fromCtx = fromCtx.createSubcontext(comp);
}
}
log.debug("atom: " + atom);
log.debug("link: " + link);
fromCtx.rebind(atom, link);
log.debug("Bound link " + fromName + " to " + toName);
}
}
private void removeLinkRef(String name) throws NamingException
{
if(super.getState() == ServiceMBean.STOPPING)
{
InitialContext ctx = new InitialContext();
ctx.unbind(name);
}
}
}