/*
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.naming;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * A service which allows arbitrary values to be bound into JNDI.
 * 
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.1 $
 */
public class JNDIBindingService
{
   /** The JNDI bindings managed by this service */
   private JNDIBindings bindings;

   /** The root context name under which the values are bound */
   private String rootName;

   public JNDIBindings getBindings()
   {
      return bindings;
   }
   public void setBindings(JNDIBindings bindings)
   {
      this.bindings = bindings;
   }

   public String getRootName()
   {
      return rootName;
   }
   public void setRootName(String rootName)
   {
      this.rootName = rootName;
   }

   public void addBindings() throws NamingException
   {
      Context ctx = new InitialContext();
      if( rootName != null )
         ctx = (Context) ctx.lookup(rootName);

      JNDIBinding[] values = bindings.getBindings();
      for(int n = 0; n < values.length; n ++)
      {
         String name = values[n].getName();
         Object value;
         try
         {
            value = values[n].getValue();
         }
         catch(Exception e)
         {
            NamingException ne = new NamingException("Failed to obtain value from binding: "+name);
            ne.setRootCause(e);
            throw ne;
         }
         Util.bind(ctx, name, value);
      }
      ctx.close();
   }
   public void removeBindings() throws NamingException
   {
      Context ctx = new InitialContext();
      if( rootName != null )
         ctx = (Context) ctx.lookup(rootName);

      JNDIBinding[] values = bindings.getBindings();
      for(int n = 0; n < values.length; n ++)
      {
         String name = values[n].getName();
         Util.unbind(ctx, name);
      }
      ctx.close();
   }

   public void start() throws Exception
   {
      addBindings();
   }
   public void stop() throws Exception
   {
      removeBindings();
   }
}
