Skip Headers

Oracle® Internet Directory Application Developer's Guide
10g (9.0.4)

Part Number B10461-01
Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Go to previous page Go to next page

B
Sample Usage

This appendix provides sample code.

This section contains these topics

DBMS_LDAP Sample Code

This section contains these topics:

Using DBMS_LDAP from a Database Trigger

The DBMS_LDAP API can be invoked from database triggers to synchronize any changes to a database table with an enterprise-wide LDAP server. The following example illustrates how changes to a table called 'EMP' are synchronized with the data in an LDAP server using triggers for insert, update, and delete. There are two files associated with this sample:

These files can be found in the plsql directory under $ORACLE_HOME/ldap/demo

The trigger.sql File

This SQL file creates a database table called 'EMP' and creates a trigger on it called LDAP_EMP which will synchronize all changes happening to the table with an LDAP server. The changes to the database table are reflected/replicated to the LDAP directory using the DBMS_LDAP package.

This script assumes the following:

The aforementioned variables could be customized for different environments by changing the appropriate variables in the code below.

Table Definition

Employee Details(Columns) in Database Table(EMP):

LDAP Schema Definition & Mapping to Relational Schema EMP

Corresponding Data representation in LDAP directory:

Using DBMS_LDAP for a Search

The following example illustrates using the DBMS_LDAP API to perform an LDAP search in a PL/SQL program. This example searches for the entries created using the trigger example described previously. It assumes a base of o=acme,dc=com and performs a subtree search to retrieve all entries that are subordinates of the base entry. The code shown below is contained in a file called search.sql which can be found in the $ORACLE_HOME/ldap/demo/plsql directory.

The search.sql File

This SQL file contains the PL/SQL code required to perform a typical search against an LDAP server.

This script assumes the following:

DBMS_LDAP_UTL Sample Code

This section contains these topics:

Example: User-Related Functions

This is a sample usage of user-related functions in the DBMS_LDAP_UTL package. You can create a user handle using DN, GUID or a simple name representing the user.

This sample program demonstrates the following user-related functions:

set serveroutput on size 30000

DECLARE

 ldap_host      VARCHAR2(256);
 ldap_port      PLS_INTEGER;
 ldap_user      VARCHAR2(256);
 ldap_passwd    VARCHAR2(256);
 ldap_base      VARCHAR2(256);

 retval              PLS_INTEGER;
 my_session          DBMS_LDAP.session;

 subscriber_handle   DBMS_LDAP_UTL.HANDLE;
 sub_type            PLS_INTEGER;
 subscriber_id       VARCHAR2(2000);

 my_pset_coll        DBMS_LDAP_UTL.PROPERTY_SET_COLLECTION;
 my_property_names   DBMS_LDAP.STRING_COLLECTION;
 my_property_values  DBMS_LDAP.STRING_COLLECTION;

 user_handle         DBMS_LDAP_UTL.HANDLE;
 user_id             VARCHAR2(2000);
 user_type           PLS_INTEGER;
 user_password       VARCHAR2(2000);

 my_mod_pset         DBMS_LDAP_UTL.MOD_PROPERTY_SET;


 my_attrs            DBMS_LDAP.STRING_COLLECTION;

BEGIN


 -- Please customize the following variables as needed

 ldap_host     :=   NULL ;
 ldap_port     :=   389;
 ldap_user     :=   'cn=orcladmin';
 ldap_passwd   :=   'welcome';

 sub_type      :=   DBMS_LDAP_UTL.TYPE_DN;
 subscriber_id :=   'o=acme,dc=com';
 user_type     :=   DBMS_LDAP_UTL.TYPE_DN;
 user_id       :=   'cn=user1,cn=users,o=acme,dc=com';
 user_password :=   'welcome';


 -- Choosing exceptions to be raised by DBMS_LDAP library.
 DBMS_LDAP.USE_EXCEPTION := TRUE;

 -----------------------------------------------
 -- Connect to the LDAP server 
 -- and obtain and ld session.
 -----------------------------------------------

 my_session := DBMS_LDAP.init(ldap_host,ldap_port);

 -----------------------------------------------
 -- Bind to the directory
 -- 
 -----------------------------------------------

 retval := DBMS_LDAP.simple_bind_s(my_session,
                                ldap_user, 
                                ldap_passwd);
 
 ---------------------------------------------------------------------
 -- Create Subscriber Handle
 -- 
 ---------------------------------------------------------------------

 retval := DBMS_LDAP_UTL.create_subscriber_handle(subscriber_handle,
                                            sub_type,
                                            subscriber_id);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('create_subscriber_handle returns : ' || to_
char(retval));
 END IF;

 ---------------------------------------------------------------------
 -- Create User Handle
 -- 
 ---------------------------------------------------------------------

 retval := DBMS_LDAP_UTL.create_user_handle(user_handle,user_type,user_id);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('create_user_handle returns : ' || to_char(retval));
 END IF;

 ---------------------------------------------------------------------
 -- Set user handle properties
 -- (link subscriber to user )
 ---------------------------------------------------------------------

 retval := DBMS_LDAP_UTL.set_user_handle_properties(user_handle,
                                          DBMS_LDAP_UTL.SUBSCRIBER_HANDLE,
                                          subscriber_handle);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('set_user_handle_properties returns : ' || to_
char(retval));
 END IF;

 ---------------------------------------------------------------------
 -- Authenticate User
 -- 
 ---------------------------------------------------------------------

 retval := DBMS_LDAP_UTL.authenticate_user(my_session,
                                           user_handle,
                                           DBMS_LDAP_UTL.AUTH_SIMPLE,
                                           user_password,
                                           NULL);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('authenticate_user returns : ' || to_char(retval));
 END IF;

 ---------------------------------------------------------------------
 -- Retrieve User Properties
 -- 
 ---------------------------------------------------------------------
 -- like .. telephone number

 my_attrs(1) := 'telephonenumber';

 retval := DBMS_LDAP_UTL.get_user_properties(my_session,
                                        user_handle,
                                        my_attrs,
                                        DBMS_LDAP_UTL.ENTRY_PROPERTIES,
                                        my_pset_coll);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('get_user_properties returns : ' || to_char(retval));
 END IF;

 ---------------------------------------------------------------------
 -- Modifying User Properties
 -- 
 ---------------------------------------------------------------------


 retval := DBMS_LDAP_UTL.create_mod_propertyset(DBMS_LDAP_UTL.ENTRY_PROPERTIES,
                                            NULL,my_mod_pset);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('create_mod_propertyset returns : ' || to_
char(retval));
 END IF;


 my_property_values.delete;
 my_property_values(1) := '444-6789';
 retval := DBMS_LDAP_UTL.populate_mod_propertyset(my_mod_pset,
                                            DBMS_LDAP_UTL.REPLACE_PROPERTY,
                                            'telephonenumber',my_property_
values);
 my_property_values.delete;

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('populate_mod_propertyset returns : ' || to_
char(retval));
 END IF;


 retval := DBMS_LDAP_UTL.set_user_properties(my_session,user_handle,
                                            DBMS_LDAP_UTL.ENTRY_PROPERTIES,
                                            my_mod_pset,
                                            DBMS_LDAP_UTL.MODIFY_PROPERTY_SET);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('set_user_properties returns : ' || to_char(retval));
 END IF;


 ------------------------------------------
 -- Free Mod Propertyset
 --
 ------------------------------------------

 DBMS_LDAP_UTL.free_mod_propertyset(my_mod_pset);


 ---------------------------------------------------------------------
 -- Free handles
 -- 
 ---------------------------------------------------------------------

 DBMS_LDAP_UTL.free_handle(subscriber_handle);
 DBMS_LDAP_UTL.free_handle(user_handle);

 
  -- unbind from the directory  
 retval := DBMS_LDAP.unbind_s(my_session);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('unbind_s returns : ' || to_char(retval));
 END IF;


-- Handle Exceptions
 EXCEPTION
  WHEN OTHERS THEN
   DBMS_OUTPUT.PUT_LINE(' Error code    : ' || TO_CHAR(SQLCODE));
   DBMS_OUTPUT.PUT_LINE(' Error Message : ' || SQLERRM);
   DBMS_OUTPUT.PUT_LINE(' Exception encountered .. exiting');

  END;
/

Example: Property-Related Subprograms

This sample code demonstrates the usage of the Property related subprograms of the DBMS_LDAP_UTL package. Most of the subprograms related to user, subscriber, and group handles return DBMS_LDAP_UTL.PROPERTY_SET_COLLECTION.

A PROPERTY_SET_COLLECTION contains a set of PROPERTY_SETs. A PROPERTY_SET is analogous to an LDAP entry which is identified by the DN. Each PropertySet contains a set of zero or more Properties. A Property is analogous to a particular attribute of an LDAP entry and it may contain one or more values.

set serveroutput on size 30000

DECLARE

 ldap_host      VARCHAR2(256);
 ldap_port      PLS_INTEGER;
 ldap_user      VARCHAR2(256);
 ldap_passwd    VARCHAR2(256);
 ldap_base      VARCHAR2(256);

 retval              PLS_INTEGER;
 my_session          DBMS_LDAP.session;

 subscriber_handle   DBMS_LDAP_UTL.HANDLE;
 sub_type            PLS_INTEGER;
 subscriber_id       VARCHAR2(2000);

 my_pset_coll        DBMS_LDAP_UTL.PROPERTY_SET_COLLECTION;
 my_property_names   DBMS_LDAP.STRING_COLLECTION;
 my_property_values  DBMS_LDAP.STRING_COLLECTION;

 user_handle         DBMS_LDAP_UTL.HANDLE;
 user_id             VARCHAR2(2000);
 user_type           PLS_INTEGER;
 user_password       VARCHAR2(2000);

 my_mod_pset         DBMS_LDAP_UTL.MOD_PROPERTY_SET;


 my_attrs            DBMS_LDAP.STRING_COLLECTION;

BEGIN


 -- Please customize the following variables as needed

 ldap_host     := NULL ;
 ldap_port     := 389;
 ldap_user     := 'cn=orcladmin';
 ldap_passwd   := 'welcome';

 sub_type      := DBMS_LDAP_UTL.TYPE_DN;
 subscriber_id := 'o=acme,dc=com';
 user_type     := DBMS_LDAP_UTL.TYPE_DN;
 user_id       := 'cn=user1,cn=users,o=acme,dc=com';
 user_password := 'welcome';


 -- Choosing exceptions to be raised by DBMS_LDAP library.
 DBMS_LDAP.USE_EXCEPTION := TRUE;

 -----------------------------------------------
 -- Connect to the LDAP server 
 -- and obtain and ld session.
 -----------------------------------------------

 my_session := DBMS_LDAP.init(ldap_host,ldap_port);

 -----------------------------------------------
 -- Bind to the directory
 -- 
 -----------------------------------------------

 retval := DBMS_LDAP.simple_bind_s(my_session,
                                ldap_user, 
                                ldap_passwd);
 
 ---------------------------------------------------------------------
 -- Create Subscriber Handle
 -- 
 ---------------------------------------------------------------------

 retval := DBMS_LDAP_UTL.create_subscriber_handle(subscriber_handle,
                                            sub_type,
                                            subscriber_id);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('create_subscriber_handle returns : ' || to_
char(retval));
 END IF;

 ---------------------------------------------------------------------
 -- Create User Handle
 -- 
 ---------------------------------------------------------------------

 retval := DBMS_LDAP_UTL.create_user_handle(user_handle,user_type,user_id);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('create_user_handle returns : ' || to_char(retval));
 END IF;

 ---------------------------------------------------------------------
 -- Set user handle properties
 -- (link subscriber to user )
 ---------------------------------------------------------------------

 retval := DBMS_LDAP_UTL.set_user_handle_properties(user_handle,
                                          DBMS_LDAP_UTL.SUBSCRIBER_HANDLE,
                                          subscriber_handle);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('set_user_handle_properties returns : ' || to_
char(retval));
 END IF;

 ---------------------------------------------------------------------
 -- Retrieve User Properties
 -- 
 ---------------------------------------------------------------------
 -- like .. telephone number

 my_attrs(1) := 'telephonenumber';

 retval := DBMS_LDAP_UTL.get_user_properties(my_session,
                                        user_handle,
                                        my_attrs,
                                        DBMS_LDAP_UTL.ENTRY_PROPERTIES,
                                        my_pset_coll);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('get_user_properties returns : ' || to_char(retval));
 END IF;

 ---------------------------------------------------------------------
 -- Print properties obtained for the user.
 -- 
 ---------------------------------------------------------------------
  IF my_pset_coll.count > 0 THEN


      FOR i in my_pset_coll.first .. my_pset_coll.last LOOP

       retval := DBMS_LDAP_UTL.get_property_names(my_pset_coll(i),
                                                  my_property_names);
         IF my_property_names.count > 0 THEN
      
           FOR j in my_property_names.first .. my_property_names.last LOOP
             retval := DBMS_LDAP_UTL.get_property_values(my_pset_coll(i),
                                                         my_property_names(j),
                                                         my_property_values);
             IF my_property_values.COUNT > 0 THEN
                FOR k in my_property_values.FIRST..my_property_values.LAST LOOP

                  DBMS_OUTPUT.PUT_LINE( my_property_names(j) || ' : ' ||
                          my_property_values(k));

                END LOOP;
             END IF;

           END LOOP;

         END IF; -- IF my_property_names.count > 0

      END LOOP;  

  END IF; -- If my_pset_coll.count > 0


   -- Free my_properties
   IF my_pset_coll.count > 0 then
     DBMS_LDAP_UTL.free_propertyset_collection(my_pset_coll);
   end if;

 ---------------------------------------------------------------------
 -- Free handles
 -- 
 ---------------------------------------------------------------------

 DBMS_LDAP_UTL.free_handle(subscriber_handle);
 DBMS_LDAP_UTL.free_handle(user_handle);

 
  -- unbind from the directory  
 retval := DBMS_LDAP.unbind_s(my_session);

 IF retval != DBMS_LDAP_UTL.SUCCESS  THEN
    -- Handle Errors
    DBMS_OUTPUT.PUT_LINE('unbind_s returns : ' || to_char(retval));
 END IF;


-- Handle Exceptions
 EXCEPTION
  WHEN OTHERS THEN
   DBMS_OUTPUT.PUT_LINE(' Error code    : ' || TO_CHAR(SQLCODE));
   DBMS_OUTPUT.PUT_LINE(' Error Message : ' || SQLERRM);
   DBMS_OUTPUT.PUT_LINE(' Exception encountered .. exiting');

  END;
/

Example: Subscriber-Related Functions

This is a sample usage of Subscriber related functions in the DBMS_LDAP_UTL package. You can create a subscriber handle using DN, GUID or a simple name representing the subscriber.

This sample program demonstrates the following subscriber-related functions:

Example: Group-Related Functions

This is a sample usage of Group related functions in DBMS_LDAP_UTL package. You can create a group handle using DN, GUID or a simple name representing the group.

This sample program demonstrates the following group-related functions:

Java Sample Code

This section contains Java sample code.

This section contains these topics:

User Class Sample Code

/*
 * SampleUser.java
 *
 * This is a sample usage of the User class in oracle.ldap.util package
 * found in ldapjclnt9.jar.  You can define a user using DN, GUID, or
 * a simple name representing the user.  The following methods are exercised
 * in this sample program:
 *
 * - User.authenticateUser() - to authenticate a user with the appropriate
 *   credentials
 * - User.getProperties() - to obtain properties of the user
 * - User.setProperties() - to add, replace, or delete properties of the user 
 *
 */

import oracle.ldap.util.*;
import oracle.ldap.util.jndi.*;

import java.io.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class SampleUser {

   public static void main(String argv[])
          throws NamingException {

      // Create InitialDirContext

      InitialDirContext ctx = ConnectionUtil.getDefaultDirCtx( "sandal",
                                       "3060",
                                       "cn=orcladmin",
                                       "welcome" );

      // Create Subscriber object
 
      Subscriber mysub = null;

      try {
         // Creation using DN
         mysub = new Subscriber( ctx, Util.IDTYPE_DN, "o=oracle,dc=com", false 
);
      }
      catch (UtilException e) {
         /*
          * Exception encountered in subscriber object constructor
          */
      }

      // Create User Objects

      User myuser = null,
           myuser1 = null;
   
      try {
         // Create User using a subscriber DN and the User DN

         myuser = new User ( ctx,
                             Util.IDTYPE_DN,
                             "cn=user1,cn=users,o=oracle,dc=com",
                             Util.IDTYPE_DN,
                             "o=oracle,dc=com",
                             false );

         // Create User using a subscriber object and the User
         // simple name

         myuser1 = new User ( ctx,
                              Util.IDTYPE_SIMPLE,
                              "user1",
                              mysub,
                              false );
      }
      catch ( UtilException e ) {
         /*
          * Exception encountered in User object constructor
          */
      }

      // Authenticate User
      try {
         myuser1.authenticateUser(ctx,User.CREDTYPE_PASSWD,"welcome");
      }
      catch ( UtilException e ) {
         /*
          * Authenticate fails
          */
      }

      // Perform User operations

      try {
         PropertySetCollection result = null;

         // Get telephonenumber of user

         String[] userAttrList = {"telephonenumber"};
         result = myuser1.getProperties(ctx,userAttrList);
         
         /*
          * Do work with result
                .
                .
                .
          */ 
          Util.printResults(result);

         // Set telephonenumber of user

         // Create JNDI ModificationItem 

         ModificationItem[] mods = new ModificationItem[1]; 
         mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                           new BasicAttribute("telephonenumber", "444-6789"));

         // Perform modification using User object

         myuser.setProperties(ctx, mods);
      }
      catch ( UtilException e ) {
         /*
          * Exception encountered in User object operations
          */
      }
   }
} // End of SampleUser.java

Subscriber Class Sample Code

/*
 * SampleSubscriber.java
 *
 * This is a sample usage of the Subscriber class in oracle.ldap.util package
 * found in ldapjclnt9.jar.  You can define a group using a DN, GUID, or a 
 * simple name of the subscriber.  The following methods are exercised in 
 * this sample program:
 *
 * - Subscriber.getProperties() - to obtain properties of the group
 *
 */  

import oracle.ldap.util.*;
import oracle.ldap.util.jndi.*;

import java.io.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class SampleSubscriber {

   public static void main(String argv[])
          throws NamingException {

      // Create InitialDirContext

      InitialDirContext ctx = ConnectionUtil.getDefaultDirCtx( "sandal",
                                       "3060",
                                       "cn=orcladmin",
                                       "welcome" );

      // Create Subscriber object
 
      Subscriber mysub = null,
                 mysub1 = null,
                 mysub2 = null;
      try {
      
         // Creation using DN
         mysub = new Subscriber( ctx,
                                         Util.IDTYPE_DN,
                                         "o=oracle,dc=com",
                                         false );

         // Creation using Simple Name 
         mysub1 = new Subscriber( ctx,
                                          Util.IDTYPE_SIMPLE,
                                          "Oracle",
                                          false );
 
         // Creation using GUID
         mysub2 = new Subscriber( ctx,
                                          Util.IDTYPE_GUID,
                                          "93B37BBC3B1F46F8E034080020F73460",
                                          false );
      }
      catch (UtilException e) {
         /*
          * Exception encountered in subscriber object constructor
          */
      }

 
      // Set the attribute list for attributes returned
      String[] attrList = { "cn",
                            "orclcommonusersearchbase",
                            "orclguid" };

      // Get Subscriber Properties

      PropertySetCollection result = null;
      try {
         result = mysub.getProperties(ctx,attrList); 
      }
      catch (UtilException e) {
         /*
          * Exception encountered when searching for subscriber properties
          */
      }

      /*
       * Do work with the result
       */

      Util.printResults(result);
   }
}

Group Class Sample Code

/*
 * SampleGroup.java
 *
 * This is a sample usage of the Group class in oracle.ldap.util package
 * found in ldapjclnt9.jar.  You can define a group using DN or GUID.
 * The following methods are exercised in this sample program: 
 *
 * - Group.isMember() - to see if a particular user is 
 *   a member of this group 
 * - Util.getGroupMembership() - to obtain the list of groups which a
 *   particular user belongs to
 * - Group.getProperties() - to obtain properties of the group 
 *
 */

import oracle.ldap.util.*;
import oracle.ldap.util.jndi.*;

import java.io.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class SampleGroup {

   public static void main(String argv[])
          throws NamingException {

      // Create InitialDirContext

      InitialDirContext ctx = ConnectionUtil.getDefaultDirCtx( "sandal",
                                       "3060",
                                       "cn=orcladmin",
                                       "welcome" );

      // Create Group Object
      Group mygroup = null;
      try {
         mygroup = new Group ( Util.IDTYPE_DN,
                               "cn=group1,cn=Groups,o=oracle,dc=com" );
      }
      catch ( UtilException e ) {
         /*
          * Error encountered in Group constructor
          */
      }
  
      // Create User Object

      User myuser = null;
      try {
         // Create User using a subscriber DN and the User DN
         myuser = new User ( ctx,
                             Util.IDTYPE_DN,
                             "cn=orcladmin,cn=users,o=oracle,dc=com",
                             Util.IDTYPE_DN,
                             "o=oracle,dc=com",
                             false );
      }
      catch ( UtilException e ) {
         /*
          * Exception encountered in User object constructor
          */
      }
      
      // Perform Group Operations

      try {

         // isMember method 

         if (mygroup.isMember( ctx,
                               myuser,
                               true ) ) {
            /*
             * myuser is a member of this group 
             * Do work
             *           .
             *           .
             *           .
             */
             System.out.println("is member");
         }

         // Get all nested groups that a user belongs to

         PropertySetCollection result = Util.getGroupMembership( ctx,
                                                                 myuser,
                                                                 new String[0],
                                                                 true );
         /*
          * Do work with result
          *           .
          *           .
          *           .
          */
         Util.printResults ( result );
 
         // Get Group Properties

         result = getProperties( ctx, null );
                                
         /*
          * Do work with result
          *           .
          *           .
          *           .
          */
      }
      catch ( UtilException e ) {
         /*
          * Exception encountered in getGroupMembership
          */
      }
   }
} // End of SampleGroup.java

Print Sample Code

/*
 * SamplePrint.java
 *
 * This sample program demonstrates the usage of the PropertySetCollection 
 * class which is a key structure used in the oracle.ldap.util package for 
 * obtaining search results.  A sample printResults() method is implemented
 * that neatly prints out the values of a PropertySetCollection.  
 * A ProperSetCollection contains a set of PropertySets.  A PropertySet is 
 * analogous to an LDAP entry which is identified by the DN.  Each PropertySet
 * contains a set of zero or more Properties.  A Property is analogous to a
 * particular attribute of an LDAP entry and it may contain one or more
 * values.  The printResults() method takes in a PropertySetCollection and
 * navigates through it in a systemmatic way, printing out the results to 
 * the system output.
 *
 */
 
import oracle.ldap.util.*;
import oracle.ldap.util.jndi.*;

import java.io.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class SamplePrint {

   public static void printResults( PropertySetCollection resultSet )
   {
      // for loop to go through each PropertySet 
      for (int i = 0; i < resultSet.size(); i++ )
      {
         // Get PropertySet
         PropertySet curEntry = resultSet.getPropertySet( i );
         Object obj = null;

         // Print DN of PropertySet
         System.out.println("dn: " + curEntry.getDN());

         // Go through each Property of the PropertySet
         for (int j = 0; j < curEntry.size(); j++)
         {
            // Get Property
            Property curAttr = curEntry.getProperty( j );
  
            // Go through each value of the Property
            for (int k = 0; k < curAttr.size(); k++)
            {
              obj = curAttr.getValue(k);
              if( obj instanceof java.lang.String) {
               System.out.println( curAttr.getName() + ": "
                                + (String) obj);
              }
              else if (obj instanceof byte[]) {
               System.out.println( curAttr.getName() + ": "
                                + (new java.lang.String((byte [])obj)));
              }
            }
         }
         System.out.println();
      }
   }

} // End of SamplePrint.java

JNDI Sample Code

import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;
import oracle.ldap.util.jndi.*;
import oracle.ldap.util.*;
import java.lang.*;
import java.util.*;

/*
* JNDI SASL Digest MD5 is available in JDK 1.4 and later */
public class LdapSaslDigestMD5 {
public static void main( String[] args) throws Exception
{
System.out.println("port : " + args[1]); System.out.println("bindDN : " + args[2]); System.out.println("bindPwd: " + args[3]);
// Important note: // The bindDN must be normalized before passing it to JNDI context // For example: cn=smith,ou=oid,o=oracle,c=us // (capital and space will not be accepted as a normalized dn) // Right now we only support dn in only. // uid form will be supported in the next release. // The noralize dn call is a static method in Util.java. String normDN = Util.normalizeDN(args[2]); Hashtable hashtable = new Hashtable(); // Look through System Properties for Context Factory if available // set the CONTEXT factory only if it has not been set // in the environment - set default to com.sun.jndi.ldap.LdapCtxFactory hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); hashtable.put(Context.PROVIDER_URL, "ldap://"+args[0]+":"+args[1]); // Set security authentication context to Digest MD5 hashtable.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5"); hashtable.put(Context.SECURITY_PRINCIPAL, normDN ); hashtable.put(Context.SECURITY_CREDENTIALS, args[3] ); hashtable.put("java.naming.security.sasl.realm", ""); LdapContext ctx = new InitialLdapContext(hashtable,null); System.out.println("sasl bind successful"); // Some search after the SASL bind has been done PropertySetCollection psc = Util.ldapSearch(ctx,"","objectclass=*", SearchControls.OBJECT_SCOPE, new String[] {"supportedSASLmechanism"}); Util.printResults(psc); System.exit(0); } } /* * Sample code Using JNDI/SASL EXTERNAL to connect to OID * This code will work only with OID SSL setup in mutual authentication mode only. * JNDI client needs to provide a client certificate that can be recognized by
* server side. */ import java.util.*; import javax.naming.*; import javax.naming.directory.*; import oracle.security.jazn.spi.ldap.*; public class LdapSaslExternal { public static void main (String[] args) { try { Hashtable env = new Hashtable(); // Specify host and port to use for directory service env.put("javax.net.debug", "all"); env.put("com.sun.jndi.ldap.trace.ber", System.out); env.put("com.sun.naming.ldap.trace.ber", System.out); env.put(Context.PROVIDER_URL, "ldap://some_url:5055/"); env.put("java.naming.security.protocol", "ssl"); System.setProperty("oracle.security.jazn.ldap.walletloc","<wallet_ url>/ewallet.txt"); System.setProperty("oracle.security.jazn.ldap.walletpwd","welcome01"); // You can use any SSL Socket Factory of your implementation or toolkit env.put("java.naming.ldap.factory.socket","oracle.security.jazn.spi.ldap.JAZNSSL SocketFactoryImpl"); // specify authentication information // Note: you can also set security authentication context to "SIMPLE" to // connect to OID; however, this functionality supports for backward // compatibility with LDAP version 2. env.put(Context.SECURITY_AUTHENTICATION, "EXTERNAL"); // TO-DO: add secure hannes env.put(Context.SECURITY_PRINCIPAL, "cn=test,ou=security,o=oracle,c=us"); nv.put(Context.SECURITY_CREDENTIALS, "welcome"); // TO-DO: add SSL env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory"); // Set your own SSL Socket factory Impl class here. System.getProperties().put("SSLSocketFactoryImplClass","oracle.security.jazn.spi .ldap.JAZNSSLSocketFactoryImpl"); DirContext dirCtx = new InitialDirContext(env); System.out.println("return from InitialDirContext"); Object obj = dirCtx.lookup(""); System.out.println("Looked up obj : " + obj); } catch (Exception exp) { exp.printStackTrace(); System.exit(-1); } } }

SASL-Based Authentication Sample Code

/* $Header: LdapSasl.java 05-may-2003.15:14:22 qdinh Exp $ */

/* Copyright (c) 2003, Oracle Corporation.  All rights reserved.  */

/*
   DESCRIPTION
    <short description of component this file declares/defines>

   PRIVATE CLASSES
    <list of private classes defined - with one-line descriptions>

   NOTES
    <other useful comments, qualifications, etc.>

   MODIFIED    (MM/DD/YY)
   *****       04/23/03 - Creation
 */

/**
 *  @version $Header: LdapSasl.java 05-may-2003.15:14:22 ***** Exp $
 *  @author  *****   
 *  @since   release specific (what release of product did this appear in)
 */

package oracle.ldap.util.jndi;

import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;
import oracle.ldap.util.jndi.*;
import oracle.ldap.util.*;
import java.lang.*;
import java.util.*;   

public class LdapSasl
{
    public static void main( String[] args)
        throws Exception
    {

       
     System.out.println("port   : " + args[1]);
     System.out.println("bindDN : " + args[2]);
     System.out.println("bindPwd: " + args[3]);

     Hashtable hashtable = new Hashtable();

     // Look through System Properties for Context Factory if available
     // set the CONTEXT factory only if it has not been set
     // in the environment - set default to com.sun.jndi.ldap.LdapCtxFactory
     hashtable.put(Context.INITIAL_CONTEXT_FACTORY,
		   "com.sun.jndi.ldap.LdapCtxFactory");
     
     hashtable.put(Context.PROVIDER_URL, "ldap://"+args[0]+":"+args[1]);
     
     //hashtable.put(Context.SECURITY_AUTHENTICATION, "simple");
     hashtable.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5");
     hashtable.put(Context.SECURITY_PRINCIPAL, args[2] );
     hashtable.put(Context.SECURITY_CREDENTIALS, args[3] );
     hashtable.put("java.naming.security.sasl.realm", ""); 
     LdapContext ctx = new InitialLdapContext(hashtable,null);
     System.out.println("sasl bind successful");
     //PropertySetCollection psc = 
Util.ldapSearch(ctx,"","objectclass=*",SearchControls.OBJECT_SCOPE, 
     //						 new String[] {"supportedSASLmechanism"});
     
     //Util.printResults(psc);

     System.exit(0); 

  }                                                              
}


Go to previous page Go to next page
Oracle
Copyright © 1999, 2003 Oracle Corporation.

All Rights Reserved.
Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index