Java/JNDI LDAP/Context

Материал из Java эксперт
Перейти к: навигация, поиск

A JNDI context wrapper implementation that delegates read-only methods to its delegate Context, and throws OperationNotSupportedException for any method with a side-effect

  
 
/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.OperationNotSupportedException;
/**
 * A JNDI context wrapper implementation that delegates read-only methods to its
 * delegate Context, and throws OperationNotSupportedException for any method
 * with a side-effect.
 * 
 * @author Scott.Stark@jboss.org
 * @version $Revision: 2787 $
 */
@SuppressWarnings("unchecked")
public class ReadOnlyContext implements Context {
  /** The actual context we impose the read-only behavior on */
  private Context delegate;
  public ReadOnlyContext(Context delegate) {
    this.delegate = delegate;
  }
  // Supported methods
  // -----------------------------------------------------------
  public void close() throws NamingException {
    delegate.close();
  }
  public String composeName(String name, String prefix) throws NamingException {
    return delegate.ruposeName(name, prefix);
  }
  public Name composeName(Name name, Name prefix) throws NamingException {
    return delegate.ruposeName(name, prefix);
  }
  public String getNameInNamespace() throws NamingException {
    return delegate.getNameInNamespace();
  }
  public Hashtable getEnvironment() throws NamingException {
    return delegate.getEnvironment();
  }
  public Object lookup(String name) throws NamingException {
    return delegate.lookup(name);
  }
  public Object lookupLink(String name) throws NamingException {
    return delegate.lookupLink(name);
  }
  public Object lookup(Name name) throws NamingException {
    return delegate.lookup(name);
  }
  public Object lookupLink(Name name) throws NamingException {
    return delegate.lookupLink(name);
  }
  public NameParser getNameParser(String name) throws NamingException {
    return delegate.getNameParser(name);
  }
  public NameParser getNameParser(Name name) throws NamingException {
    return delegate.getNameParser(name);
  }
  public NamingEnumeration list(String name) throws NamingException {
    return delegate.list(name);
  }
  public NamingEnumeration listBindings(String name) throws NamingException {
    return delegate.listBindings(name);
  }
  public NamingEnumeration list(Name name) throws NamingException {
    return delegate.list(name);
  }
  public NamingEnumeration listBindings(Name name) throws NamingException {
    return delegate.listBindings(name);
  }
  // Unsupported methods
  // ---------------------------------------------------------
  public Object addToEnvironment(String propName, Object propVal) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public void bind(String name, Object obj) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public void bind(Name name, Object obj) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public Context createSubcontext(String name) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public Context createSubcontext(Name name) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public void destroySubcontext(String name) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public void destroySubcontext(Name name) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public Object removeFromEnvironment(String propName) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public void rebind(String name, Object obj) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public void rebind(Name name, Object obj) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public void rename(String oldName, String newName) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public void rename(Name oldName, Name newName) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public void unbind(String name) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
  public void unbind(Name name) throws NamingException {
    throw new OperationNotSupportedException("This is a read-only Context");
  }
}





A static utility class for common JNDI operations

  
/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.LinkRef;
import javax.naming.Name;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
/**
 * A static utility class for common JNDI operations.
 * 
 * @author Scott.Stark@jboss.org
 * @author adrian@jboss.ru
 * @version $Revision: 2787 $
 */
@SuppressWarnings("unchecked")
public class Util {
  /**
   * Create a subcontext including any intermediate contexts.
   * 
   * @param ctx
   *          the parent JNDI Context under which value will be bound
   * @param name
   *          the name relative to ctx of the subcontext.
   * @return The new or existing JNDI subcontext
   * @throws javax.naming.NamingException
   *           on any JNDI failure
   */
  public static Context createSubcontext(Context ctx, String name) throws NamingException {
    Name n = ctx.getNameParser("").parse(name);
    return createSubcontext(ctx, n);
  }
  /**
   * Create a subcontext including any intermediate contexts.
   * 
   * @param ctx
   *          the parent JNDI Context under which value will be bound
   * @param name
   *          the name relative to ctx of the subcontext.
   * @return The new or existing JNDI subcontext
   * @throws NamingException
   *           on any JNDI failure
   */
  public static Context createSubcontext(Context ctx, Name name) throws NamingException {
    Context subctx = ctx;
    for (int pos = 0; pos < name.size(); pos++) {
      String ctxName = name.get(pos);
      try {
        subctx = (Context) ctx.lookup(ctxName);
      } catch (NameNotFoundException e) {
        subctx = ctx.createSubcontext(ctxName);
      }
      // The current subctx will be the ctx for the next name component
      ctx = subctx;
    }
    return subctx;
  }
  /**
   * Bind val to name in ctx, and make sure that all intermediate contexts exist
   * 
   * @param ctx
   *          the parent JNDI Context under which value will be bound
   * @param name
   *          the name relative to ctx where value will be bound
   * @param value
   *          the value to bind.
   * @throws NamingException
   *           for any error
   */
  public static void bind(Context ctx, String name, Object value) throws NamingException {
    Name n = ctx.getNameParser("").parse(name);
    bind(ctx, n, value);
  }
  /**
   * Bind val to name in ctx, and make sure that all intermediate contexts exist
   * 
   * @param ctx
   *          the parent JNDI Context under which value will be bound
   * @param name
   *          the name relative to ctx where value will be bound
   * @param value
   *          the value to bind.
   * @throws NamingException
   *           for any error
   */
  public static void bind(Context ctx, Name name, Object value) throws NamingException {
    int size = name.size();
    String atom = name.get(size - 1);
    Context parentCtx = createSubcontext(ctx, name.getPrefix(size - 1));
    parentCtx.bind(atom, value);
  }
  /**
   * Rebind val to name in ctx, and make sure that all intermediate contexts
   * exist
   * 
   * @param ctx
   *          the parent JNDI Context under which value will be bound
   * @param name
   *          the name relative to ctx where value will be bound
   * @param value
   *          the value to bind.
   * @throws NamingException
   *           for any error
   */
  public static void rebind(Context ctx, String name, Object value) throws NamingException {
    Name n = ctx.getNameParser("").parse(name);
    rebind(ctx, n, value);
  }
  /**
   * Rebind val to name in ctx, and make sure that all intermediate contexts
   * exist
   * 
   * @param ctx
   *          the parent JNDI Context under which value will be bound
   * @param name
   *          the name relative to ctx where value will be bound
   * @param value
   *          the value to bind.
   * @throws NamingException
   *           for any error
   */
  public static void rebind(Context ctx, Name name, Object value) throws NamingException {
    int size = name.size();
    String atom = name.get(size - 1);
    Context parentCtx = createSubcontext(ctx, name.getPrefix(size - 1));
    parentCtx.rebind(atom, value);
  }
  /**
   * Unbinds a name from ctx, and removes parents if they are empty
   * 
   * @param ctx
   *          the parent JNDI Context under which the name will be unbound
   * @param name
   *          The name to unbind
   * @throws NamingException
   *           for any error
   */
  public static void unbind(Context ctx, String name) throws NamingException {
    unbind(ctx, ctx.getNameParser("").parse(name));
  }
  /**
   * Unbinds a name from ctx, and removes parents if they are empty
   * 
   * @param ctx
   *          the parent JNDI Context under which the name will be unbound
   * @param name
   *          The name to unbind
   * @throws NamingException
   *           for any error
   */
  public static void unbind(Context ctx, Name name) throws NamingException {
    ctx.unbind(name); // unbind the end node in the name
    int sz = name.size();
    // walk the tree backwards, stopping at the domain
    while (--sz > 0) {
      Name pname = name.getPrefix(sz);
      try {
        ctx.destroySubcontext(pname);
      } catch (NamingException e) {
        System.out.println("Unable to remove context " + pname + e);
        break;
      }
    }
  }
  /**
   * Lookup an object in the default initial context
   * 
   * @param name
   *          the name to lookup
   * @param clazz
   *          the expected type
   * @return the object
   * @throws Exception
   *           for any error
   */
  public static Object lookup(String name, Class<?> clazz) throws Exception {
    InitialContext ctx = new InitialContext();
    try {
      return lookup(ctx, name, clazz);
    } finally {
      ctx.close();
    }
  }
  /**
   * Lookup an object in the default initial context
   * 
   * @param name
   *          the name to lookup
   * @param clazz
   *          the expected type
   * @return the object
   * @throws Exception
   *           for any error
   */
  public static Object lookup(Name name, Class<?> clazz) throws Exception {
    InitialContext ctx = new InitialContext();
    try {
      return lookup(ctx, name, clazz);
    } finally {
      ctx.close();
    }
  }
  /**
   * Lookup an object in the given context
   * 
   * @param context
   *          the context
   * @param name
   *          the name to lookup
   * @param clazz
   *          the expected type
   * @return the object
   * @throws Exception
   *           for any error
   */
  public static Object lookup(Context context, String name, Class clazz) throws Exception {
    Object result = context.lookup(name);
    checkObject(context, name, result, clazz);
    return result;
  }
  /**
   * Lookup an object in the given context
   * 
   * @param context
   *          the context
   * @param name
   *          the name to lookup
   * @param clazz
   *          the expected type
   * @return the object
   * @throws Exception
   *           for any error
   */
  public static Object lookup(Context context, Name name, Class clazz) throws Exception {
    Object result = context.lookup(name);
    checkObject(context, name.toString(), result, clazz);
    return result;
  }
  /**
   * Create a link
   * 
   * @param fromName
   *          the from name
   * @param toName
   *          the to name
   * @throws NamingException
   *           for any error
   */
  public static void createLinkRef(String fromName, String toName) throws NamingException {
    InitialContext ctx = new InitialContext();
    createLinkRef(ctx, fromName, toName);
  }
  /**
   * Create a link
   * 
   * @param ctx
   *          the context
   * @param fromName
   *          the from name
   * @param toName
   *          the to name
   * @throws NamingException
   *           for any error
   */
  public static void createLinkRef(Context ctx, String fromName, String toName)
      throws NamingException {
    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);
      }
    }
    System.out.println("atom: " + atom);
    System.out.println("link: " + link);
    fromCtx.rebind(atom, link);
    System.out.println("Bound link " + fromName + " to " + toName);
  }
  /**
   * Remove the link ref
   * 
   * @param name
   *          the name of the link binding
   * @throws NamingException
   *           for any error
   */
  public static void removeLinkRef(String name) throws NamingException {
    InitialContext ctx = new InitialContext();
    removeLinkRef(ctx, name);
  }
  /**
   * Remove the link ref
   * 
   * @param ctx
   *          the context
   * @param name
   *          the name of the link binding
   * @throws NamingException
   *           for any error
   */
  public static void removeLinkRef(Context ctx, String name) throws NamingException {
    System.out.println("Unbinding link " + name);
    ctx.unbind(name);
  }
  /**
   * Checks an object implements the given class
   * 
   * @param context
   *          the context
   * @param name
   *          the name to lookup
   * @param object
   *          the object
   * @param clazz
   *          the expected type
   * @throws Exception
   *           for any error
   */
  protected static void checkObject(Context context, String name, Object object, Class clazz)
      throws Exception {
    Class objectClass = object.getClass();
    if (clazz.isAssignableFrom(objectClass) == false) {
      StringBuffer buffer = new StringBuffer(100);
      buffer.append("Object at "").append(name);
      buffer.append("" in context ").append(context.getEnvironment());
      buffer.append(" is not an instance of ");
      appendClassInfo(buffer, clazz);
      buffer.append(" object class is ");
      appendClassInfo(buffer, object.getClass());
      throw new ClassCastException(buffer.toString());
    }
  }
  /**
   * Append Class Info
   * 
   * @param buffer
   *          the buffer to append to
   * @param clazz
   *          the class to describe
   */
  protected static void appendClassInfo(StringBuffer buffer, Class clazz) {
    buffer.append("[class=").append(clazz.getName());
    buffer.append(" classloader=").append(clazz.getClassLoader());
    buffer.append(" interfaces={");
    Class[] interfaces = clazz.getInterfaces();
    for (int i = 0; i < interfaces.length; ++i) {
      if (i > 0)
        buffer.append(", ");
      buffer.append("interface=").append(interfaces[i].getName());
      buffer.append(" classloader=").append(interfaces[i].getClassLoader());
    }
    buffer.append("}]");
  }
}





Create a context path recursively.

  
/*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
import java.util.StringTokenizer;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
 * @author 
 * @version <tt>$Revision: 2868 $</tt>
 *
 * $Id: JNDIUtil.java 2868 2007-07-10 20:22:16Z timfox $
 */
public class JNDIUtil
{
   /**
    * Create a context path recursively.
    */
   public static Context createContext(Context c, String path) throws NamingException
   {
      Context crtContext = c;
      for(StringTokenizer st = new StringTokenizer(path, "/"); st.hasMoreTokens(); )
      {
         String tok = st.nextToken();
         try
         {
            Object o = crtContext.lookup(tok);
            if (!(o instanceof Context))
            {
               throw new NamingException("Path " + path + " overwrites and already bound object");
            }
            crtContext = (Context)o;
            continue;
         }
         catch(NameNotFoundException e)
         {
            // OK
         }
         crtContext = crtContext.createSubcontext(tok);
      }
      return crtContext;
   }
}





Creating and Destroying a Subcontext in the Naming Service

   
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
public class Main {
  public static void main(String[] argv) throws Exception {
    String url = "iiop://localhost/";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    Context ctx = new InitialContext(env);
    // Create a subcontext.
    Context childCtx = ctx.createSubcontext("child");
    // Destroy the subcontext.
    ctx.destroySubcontext("child");
  }
}





Deleting an entry

   
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class Main {
  public static String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory";
  public static String MY_HOST = "ldap://localhost:389";
  public static String MGR_DN = "uid=yourid, ou=People, o=Java.ru";
  public static String MGR_PW = "password";
  public static String MY_SEARCHBASE = "o=Java.ru";
  public static String MY_ENTRY = "uid=mewilcox, ou=People, o=airius.ru";
  public static void main(String args[]) throws Exception {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, INITCTX);
    env.put(Context.PROVIDER_URL, MY_HOST);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, MGR_DN);
    env.put(Context.SECURITY_CREDENTIALS, MGR_PW);
    DirContext ctx = new InitialDirContext(env);
    ctx.destroySubcontext(MY_ENTRY);
  }
}





how to create a new subcontext called "ou=NewOu" with some attributes

   
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
 * Demonstrates how to create a new subcontext called "ou=NewOu" with some
 * attributes. (Run Destroy after this to remove the subcontext).
 * 
 * usage: java Create
 */
class Create {
  public static void main(String[] args) {
    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env
        .put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");
    try {
      // Create the initial context
      DirContext ctx = new InitialDirContext(env);
      // Create attributes to be associated with the new context
      Attributes attrs = new BasicAttributes(true); // case-ignore
      Attribute objclass = new BasicAttribute("objectclass");
      objclass.add("top");
      objclass.add("organizationalUnit");
      attrs.put(objclass);
      // Create the context
      Context result = ctx.createSubcontext("ou=NewOu", attrs);
      // Check that it was created by listing its parent
      NamingEnumeration list = ctx.list("");
      // Go through each item in list
      while (list.hasMore()) {
        NameClassPair nc = (NameClassPair) list.next();
        System.out.println(nc);
      }
      // Close the contexts when we"re done
      result.close();
      ctx.close();
    } catch (NamingException e) {
      System.out.println("Create failed: " + e);
    }
  }
}





how to destroy a subcontext called "ou=NewOu"

   
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
 * Demonstrates how to destroy a subcontext called "ou=NewOu". (Run this after
 * running Create)
 * 
 * usage: java Destroy
 */
class Destroy {
  public static void main(String[] args) {
    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env
        .put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");
    try {
      // Create the initial context
      Context ctx = new InitialContext(env);
      // Destroy the context
      ctx.destroySubcontext("ou=NewOu");
      // Check that it has been destroyed by listing its parent
      NamingEnumeration list = ctx.list("");
      // Go through each item in list
      while (list.hasMore()) {
        NameClassPair nc = (NameClassPair) list.next();
        System.out.println(nc);
      }
      // Close the context when we"re done
      ctx.close();
    } catch (NamingException e) {
      System.out.println("destroy failed: " + e);
    }
  }
}





how to list the name and class of objects in a context

   
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
 * Demonstrates how to list the name and class of objects in a context.
 * 
 * usage: java List
 */
class List {
  public static void main(String[] args) {
    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env
        .put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");
    try {
      // Create the initial context
      Context ctx = new InitialContext(env);
      // Get listing of context
      NamingEnumeration list = ctx.list("ou=People");
      // Go through each item in list
      while (list.hasMore()) {
        NameClassPair nc = (NameClassPair) list.next();
        System.out.println(nc);
      }
      // Close the context when we"re done
      ctx.close();
    } catch (NamingException e) {
      System.out.println("List failed: " + e);
    }
  }
}





JNDI utilities

 
/*
  Milyn - Copyright (C) 2006
  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License (version 2.1) as published by the Free Software
  Foundation.
  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the GNU Lesser General Public License for more details:
  http://www.gnu.org/licenses/lgpl.txt
*/

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.InitialContext;
import java.util.Properties;
import java.io.InputStream;
/**
 * JNDI utilities.
 *
 * @author 
 */
public class JNDIUtil {

    /**
     * Private default constructor.
     */
    private JNDIUtil() {
    }
    /**
     * Get the JNDI Context.
     * <p/>
     * Don"t forget to close it when done!
     *
     * @param jndiProperties JNDI properties.
     * @return The context.
     * @throws javax.naming.NamingException Error getting context.
     */
    public static Context getNamingContext(final Properties jndiProperties) throws NamingException {
        Context context;
        try {
            context = jndiProperties.isEmpty() ? new InitialContext() : new InitialContext(jndiProperties);
        }
        catch (NamingException e) {
            System.out.println("NamingException while try to create initialContext. jndiProperties are " + jndiProperties + e);
            throw ((NamingException) new NamingException("Failed to load InitialContext: " + jndiProperties).initCause(e));
        }
        if (context == null) {
            throw new NamingException("Failed to create JNDI context.  Check that "" + Context.PROVIDER_URL + "", "" + Context.INITIAL_CONTEXT_FACTORY + "", "" + Context.URL_PKG_PREFIXES + "" are correctly configured in the supplied JNDI properties.");
        }
        return context;
    }
    /**
     * Lookup an object through the JNDI context.
     *
     * @param objectName     The name of the object to be looked up.
     * @param jndiProperties JNDI properties.
     * @return The object.
     * @throws NamingException Error getting object.
     */
    public static Object lookup(final String objectName, final Properties jndiProperties) throws NamingException {
        Object object = null;
        Context context;
        context = JNDIUtil.getNamingContext(jndiProperties);
        try {
            object = context.lookup(objectName);
        }
        finally {
            try {
                context.close();
            }
            catch (NamingException ne) {
                System.out.println("Failed to close Naming Context."+ ne);
            }
        }
        return object;
    }
    /**
     * Lookup an object through the JNDI context.
     *
     * @param objectName     The name of the object to be looked up.
     * @param jndiProperties JNDI properties.
     * @param classLoaders   The {@link ClassLoader ClassLoaders) to be used during the lookup.
     * @return The object.
     * @throws NamingException Error getting object.
     */
    public static Object lookup(final String objectName, final Properties jndiProperties, final ClassLoader[] classLoaders) throws NamingException {
        ClassLoader tcClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            for (ClassLoader classLoader : classLoaders) {
                Thread.currentThread().setContextClassLoader(classLoader);
                try {
                    return JNDIUtil.lookup(objectName, jndiProperties);
                }
                catch (NamingException e) {
                    System.out.println("NamingException while trying to lookup "" + objectName + "" using JNDI Properties "" + jndiProperties + "", classloader used "" + classLoader + """ + e);
                    // Try the other ClassLoaders...
                }
            }
        }
        finally {
            Thread.currentThread().setContextClassLoader(tcClassLoader);
        }
        throw new NamingException("JNDI lookup of Object [" + objectName + "] failed.");
    }
    public static Properties getDefaultProperties() {
        Properties defaultProperties = new Properties();
        try {
            InitialContext context = new InitialContext();
            defaultProperties.putAll(context.getEnvironment());
        } catch (Exception e) {
            System.out.println("Unexpected exception when trying to retrieve default naming context." + e);
        }
        return defaultProperties;
    }
}





Listing a Context in the Naming Service

   
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
public class Main {
  public static void main(String[] argv) throws Exception {
    String url = "iiop://localhost/";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    Context ctx = new InitialContext(env);
    NamingEnumeration e = ctx.list("child");
    while (e.hasMore()) {
      NameClassPair entry = (NameClassPair) e.next();
      System.out.println(entry.getName());
    }
  }
}





rebind Context

  
/*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
import java.util.StringTokenizer;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
 * @author 
 * @version <tt>$Revision: 2868 $</tt>
 *
 * $Id: JNDIUtil.java 2868 2007-07-10 20:22:16Z timfox $
 */
public class JNDIUtil
{
  /**
   * Context.rebind() requires that all intermediate contexts and the target context (that named by
   * all but terminal atomic component of the name) must already exist, otherwise
   * NameNotFoundException is thrown. This method behaves similar to Context.rebind(), but creates
   * intermediate contexts, if necessary.
   */
  public static void rebind(Context c, String jndiName, Object o) throws NamingException
  {
     Context context = c;
     String name = jndiName;
     int idx = jndiName.lastIndexOf("/");
     if (idx != -1)
     {
        context = createContext(c, jndiName.substring(0, idx));
        name = jndiName.substring(idx + 1);
     }
     boolean failed=false;
     try
     {
        context.rebind(name,o);
     }
     catch (Exception ignored)
     {
        failed=true;
     }
     if (failed)
     {
        context.bind(name, o);
     }
  }
   /**
    * Create a context path recursively.
    */
   public static Context createContext(Context c, String path) throws NamingException
   {
      Context crtContext = c;
      for(StringTokenizer st = new StringTokenizer(path, "/"); st.hasMoreTokens(); )
      {
         String tok = st.nextToken();
         try
         {
            Object o = crtContext.lookup(tok);
            if (!(o instanceof Context))
            {
               throw new NamingException("Path " + path + " overwrites and already bound object");
            }
            crtContext = (Context)o;
            continue;
         }
         catch(NameNotFoundException e)
         {
            // OK
         }
         crtContext = crtContext.createSubcontext(tok);
      }
      return crtContext;
   }
}





tearDown Context Recursively

  
/*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
import java.util.StringTokenizer;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
 * @author 
 * @version <tt>$Revision: 2868 $</tt>
 *
 * $Id: JNDIUtil.java 2868 2007-07-10 20:22:16Z timfox $
 */
public class JNDIUtil
{
  public static void tearDownRecursively(Context c) throws Exception
  {
     for(NamingEnumeration ne = c.listBindings(""); ne.hasMore(); )
     {
        Binding b = (Binding)ne.next();
        String name = b.getName();
        Object object = b.getObject();
        if (object instanceof Context)
        {
           tearDownRecursively((Context)object);
        }
        c.unbind(name);
     }
  }
}