Java by API/javax.naming/Context — различия между версиями

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

Текущая версия на 14:43, 31 мая 2010

Context: addToEnvironment(String propName, Object propVal)

   

/*
 * 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.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
 * Demonstrates how to use different authentication information for one context.
 * 
 * usage: java UseDiff
 */
class UseDiff {
  public static void main(String[] args) {
    // Set up environment for creating 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");
    // Authenticate as S. User and password "mysecret"
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL,
        "cn=S. User, ou=NewHires, o=JNDITutorial");
    env.put(Context.SECURITY_CREDENTIALS, "mysecret");
    try {
      // Create initial context
      DirContext ctx = new InitialDirContext(env);
      // do something useful with ctx
      System.out.println(ctx.lookup("ou=NewHires"));
      // Change to using no authentication
      ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "none");
      System.out.println(ctx.lookup("ou=NewHires"));
      // do something useful with ctx
      // Close the context when we"re done
      ctx.close();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
}





Context: close()

   
/*
 * 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.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
 * Demonstrates how to enable connection pooling. Use debug option to observe
 * connection usage.
 * 
 * usage: java -Dcom.sun.jndi.ldap.connect.pool.debug=fine UsePool
 */
class UsePool {
  public static void main(String[] args) {
    // Set up environment for creating 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");
    // Enable connection pooling
    env.put("com.sun.jndi.ldap.connect.pool", "true");
    try {
      // Create one initial context (Get connection from pool)
      DirContext ctx = new InitialDirContext(env);
      System.out.println(ctx.getAttributes("ou=NewHires"));
      // do something useful with ctx
      // Close the context when we"re done
      ctx.close(); // Return connection to pool
      // Create another initial context (Get connection from pool)
      DirContext ctx2 = new InitialDirContext(env);
      System.out.println(ctx2.getAttributes("ou=People"));
      // do something useful with ctx2
      // Close the context when we"re done
      ctx2.close(); // Return connection to pool
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
}





Context: createSubcontext(String name)

   
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");
    Context obj = (Context) childCtx.lookup("grandChild");
    String fullname = obj.getNameInNamespace();
  }
}





Context: destroySubcontext(String name)

   
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");
    Context obj = (Context) childCtx.lookup("grandChild");
    String fullname = obj.getNameInNamespace();
  }
}





Context: getNameInNamespace()

   
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");
    Context obj = (Context) childCtx.lookup("grandChild");
    String fullname = obj.getNameInNamespace();
  }
}





Context: getNameParser(String name)

   
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NameParser;
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);
    NameParser parser = ctx.getNameParser("");
    Name dn = parser.parse("cn=John, ou=People, o=JNDITutorial");
    dn.remove(1); 
    dn.add(0, "c=us"); 
    dn.add("cn=fs"); 
  }
}





Context.INITIAL_CONTEXT_FACTORY

   
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
public class PooledConnectionExample {
  public static void main(String[] args) {
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    try {
      connection = getConnection();
      statement = connection.createStatement();
      String selectEmployeesSQL = "SELECT * FROM employees";
      resultSet = statement.executeQuery(selectEmployeesSQL);
      while (resultSet.next()) {
        printEmployee(resultSet);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      closeAll(resultSet, statement, connection);
    }
  }
//Obtain connection from pool
  private static Connection getConnection() throws NamingException, SQLException {
    InitialContext initCtx = createContext();
    String jndiName = "HrDS";
    ConnectionPoolDataSource dataSource = (ConnectionPoolDataSource) initCtx.lookup(jndiName);
    PooledConnection pooledConnection = dataSource.getPooledConnection();
    return pooledConnection.getConnection(); 
  }
  private static InitialContext createContext() throws NamingException {
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    env.put(Context.PROVIDER_URL, "rmi://localhost:1099");
    InitialContext context = new InitialContext(env);
    return context;
  }
  private static void printEmployee(ResultSet resultSet) throws SQLException {
    System.out.print(resultSet.getInt("employee_id"));
    System.out.print(", ");
    System.out.print(resultSet.getString("last_name"));
    System.out.print(", ");
    System.out.print(resultSet.getString("first_name"));
    System.out.print(", ");
    System.out.println(resultSet.getString("email"));
  }
  private static void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
    if (resultSet != null) {
      try {
        resultSet.close();
      } catch (SQLException e) {
      } // nothing we can do
    }
    if (statement != null) {
      try {
        statement.close();
      } catch (SQLException e) {
      } // nothing we can do
    }
    if (connection != null) {
      try {
        connection.close();
      } catch (SQLException e) {
      } // nothing we can do
    }
  }
}





Context: listBindings(String name)

   
import java.io.IOException;
import java.io.PrintWriter;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EnvEntry extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    try {
      Context initCtx = new InitialContext();
      NamingEnumeration e = initCtx.listBindings("java:comp/env");
      while (e.hasMore()) {
        Binding binding = (Binding) e.next();
        out.println("Name: " + binding.getName());
        out.println("Type: " + binding.getClassName());
        out.println("Value: " + binding.getObject());
        out.println();
      }
    } catch (NamingException e) {
      e.printStackTrace(out);
    }
  }
}





Context: lookup(String name)

   
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");
    Context obj = (Context) childCtx.lookup("grandChild");
    String fullname = obj.getNameInNamespace();
  }
}





Context.PROVIDER_URL

   
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
public class PooledConnectionExample {
  public static void main(String[] args) {
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    try {
      connection = getConnection();
      statement = connection.createStatement();
      String selectEmployeesSQL = "SELECT * FROM employees";
      resultSet = statement.executeQuery(selectEmployeesSQL);
      while (resultSet.next()) {
        printEmployee(resultSet);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      closeAll(resultSet, statement, connection);
    }
  }
//Obtain connection from pool
  private static Connection getConnection() throws NamingException, SQLException {
    InitialContext initCtx = createContext();
    String jndiName = "HrDS";
    ConnectionPoolDataSource dataSource = (ConnectionPoolDataSource) initCtx.lookup(jndiName);
    PooledConnection pooledConnection = dataSource.getPooledConnection();
    return pooledConnection.getConnection(); 
  }
  private static InitialContext createContext() throws NamingException {
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    env.put(Context.PROVIDER_URL, "rmi://localhost:1099");
    InitialContext context = new InitialContext(env);
    return context;
  }
  private static void printEmployee(ResultSet resultSet) throws SQLException {
    System.out.print(resultSet.getInt("employee_id"));
    System.out.print(", ");
    System.out.print(resultSet.getString("last_name"));
    System.out.print(", ");
    System.out.print(resultSet.getString("first_name"));
    System.out.print(", ");
    System.out.println(resultSet.getString("email"));
  }
  private static void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
    if (resultSet != null) {
      try {
        resultSet.close();
      } catch (SQLException e) {
      } // nothing we can do
    }
    if (statement != null) {
      try {
        statement.close();
      } catch (SQLException e) {
      } // nothing we can do
    }
    if (connection != null) {
      try {
        connection.close();
      } catch (SQLException e) {
      } // nothing we can do
    }
  }
}





Context: rename(String oldName, String newName)

   
/*
 * 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.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
 * Demonstrates how to rename an entry to another part of the namespace.
 * 
 * usage: java RenameDiffParent
 */
class RenameDiffParent {
  public static void main(String[] args) {
    // Set up environment for creating 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 initial context
      DirContext ctx = new InitialDirContext(env);
      // Perform rename
      ctx.rename("cn=C. User, ou=NewHires", "cn=C. User, ou=People");
      // Check that it worked
      System.out.println(ctx.lookup("cn=C. User, ou=People"));
      // Revert change
      ctx.rename("cn=C. User, ou=People", "cn=C. User, ou=NewHires");
      // Check that we are back at our original setup
      System.out.println(ctx.lookup("cn=C. User, ou=NewHires"));
      // Close the context when we"re done
      ctx.close();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
}





Context.SECURITY_AUTHENTICATION

   
/*
 * 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.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
 * Demonstrates how failure to supply correct authentication information fails.
 * 
 * usage: java BadPasswd
 */
class BadPasswd {
  public static void main(String[] args) {
    // Set up environment for creating 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");
    // Authenticate as S. User and give incorrect password
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL,
        "cn=S. User, ou=NewHires, o=JNDITutorial");
    env.put(Context.SECURITY_CREDENTIALS, "notmysecret");
    try {
      // Create initial context
      DirContext ctx = new InitialDirContext(env);
      System.out.println(ctx.lookup("ou=NewHires"));
      // do something useful with ctx
      // Close the context when we"re done
      ctx.close();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
}





Context.SECURITY_CREDENTIALS

   
/*
 * 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.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
 * Demonstrates how failure to supply correct authentication information fails.
 * 
 * usage: java BadPasswd
 */
class BadPasswd {
  public static void main(String[] args) {
    // Set up environment for creating 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");
    // Authenticate as S. User and give incorrect password
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL,
        "cn=S. User, ou=NewHires, o=JNDITutorial");
    env.put(Context.SECURITY_CREDENTIALS, "notmysecret");
    try {
      // Create initial context
      DirContext ctx = new InitialDirContext(env);
      System.out.println(ctx.lookup("ou=NewHires"));
      // do something useful with ctx
      // Close the context when we"re done
      ctx.close();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
}





Context.SECURITY_PRINCIPAL

   
/*
 * 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.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
 * Demonstrates how failure to supply correct authentication information fails.
 * 
 * usage: java BadPasswd
 */
class BadPasswd {
  public static void main(String[] args) {
    // Set up environment for creating 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");
    // Authenticate as S. User and give incorrect password
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL,
        "cn=S. User, ou=NewHires, o=JNDITutorial");
    env.put(Context.SECURITY_CREDENTIALS, "notmysecret");
    try {
      // Create initial context
      DirContext ctx = new InitialDirContext(env);
      System.out.println(ctx.lookup("ou=NewHires"));
      // do something useful with ctx
      // Close the context when we"re done
      ctx.close();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
}





Context: unbind(String name)

   
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);
    // Add a binding.
    ctx.bind("Name", null);
    // Replace a binding.
    ctx.rebind("Name", null);
    // Remove a binding.
    ctx.unbind("Name");
    // Rename a binding.
    ctx.rename("Name", "NewSample");
  }
}