import java.io.Serializable;
import java.util.Hashtable;
import java.util.Map;

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

public class JndiUtil
{
  private Context ctx = null;
  private Hashtable env;
  
  public JndiUtil()
  {
    env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY,
      "weblogic.jndi.WLInitialContextFactory");
    env.put(Context.PROVIDER_URL, "t3://localhost:7001");
  }
  
  public JndiUtil(Map jndiProperties)
  {
    this();

    if(jndiProperties==null)
      return;

    String serverUrl = (String) jndiProperties.get("server.url");
    if(serverUrl!=null)
      env.put(Context.PROVIDER_URL, serverUrl);
    
    String user = (String) jndiProperties.get("user");
    String passwd = (String) jndiProperties.get("password");
    if(user!=null && passwd!=null)
    {
      env.put(Context.SECURITY_AUTHENTICATION, "simple");
      env.put(Context.SECURITY_PRINCIPAL, user);
      env.put(Context.SECURITY_CREDENTIALS, passwd);
    }
  }

  public Context getInitialContext()
  throws NamingException
  {
    if(ctx==null)
      ctx = new InitialContext(env);
    return ctx;
  }
  
  
  public void registerWithServer(String jndiName, Serializable obj)
  throws NamingException
  {
    Context serverContext = getInitialContext();
    serverContext.rebind(jndiName, obj);
    System.out.println("Registered client with server.");
  }

  
  public void unRegisterFromServer(String jndiName)
  throws NamingException
  {
    Context serverContext = getInitialContext();
    serverContext.unbind(jndiName);
    if(ctx!=null) ctx.close();
    System.out.println("Unregistered client from server.");
  }
  
  
}
