//Sample code file: var/ndk/webBuildengine/tmp/viewable_samples/f91a68eb-ad37-4526-92b1-b1938f37b871/controls/AsyncSortControl.java //Warning: This code has been marked up for HTML

/* **************************************************************************

 * $Novell: AsyncSortControl.java,v 1.13 2003/08/21 11:45:37 $

 *

 * Copyright (C) 1999, 2000, 2001 Novell, Inc. All Rights Reserved.

 * 

 * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND

 * TREATIES. USE AND REDISTRIBUTION OF THIS WORK IS SUBJECT TO THE LICENSE

 * AGREEMENT ACCOMPANYING THE SOFTWARE DEVELOPMENT KIT (SDK) THAT CONTAINS

 * THIS WORK. PURSUANT TO THE SDK LICENSE AGREEMENT, NOVELL HEREBY GRANTS TO

 * DEVELOPER A ROYALTY-FREE, NON-EXCLUSIVE LICENSE TO INCLUDE NOVELL'S SAMPLE

 * CODE IN ITS PRODUCT. NOVELL GRANTS DEVELOPER WORLDWIDE DISTRIBUTION RIGHTS

 * TO MARKET, DISTRIBUTE, OR SELL NOVELL'S SAMPLE CODE AS A COMPONENT OF

 * DEVELOPER'S PRODUCTS. NOVELL SHALL HAVE NO OBLIGATIONS TO DEVELOPER OR

 * DEVELOPER'S CUSTOMERS WITH RESPECT TO THIS CODE. 

 ***************************************************************************/

import java.util.Enumeration; 

import java.util.Iterator; 

import java.io.UnsupportedEncodingException;



import com.novell.ldap.*;

import com.novell.ldap.controls.*;



/**

 *  The following sample demonstrates how to use the server

 *  server side control with Asynchronous search requests.

 * 

 *  The program is hard coded to sort based on the common name

 *  attribute, and it searches for all objects at the specified

 *  searchBase.

 *  

 *  Note that Novell eDirectory does not support multiple sort keys at this

 *  time.

 * 

 *  Usage: Usage: java AsyncSortControl <host name> <login dn> <password> <searchBase>

 *

 */

public class AsyncSortControl 

{

    public static void main( String[] args ) 

    {           

       // Verify correct number of parameters


        if (args.length != 4) {

            System.out.println("Usage:   java AsyncSortControl <host name> "

                               + "<login dn> <password> <container>");

            System.out.println("Example: java AsyncSortControl Acme.com"

                           + " \"cn=admin,o=Acme\" secret \"ou=Sales,o=Acme\"");

            System.exit(0);

        }

           

       // Read command line arguments  


        String  ldapHost    = args[0];       

        String  loginDN     = args[1];

        String  password    = args[2];

        String  searchBase  = args[3];

        int     MY_PORT = 389;

        int ldapVersion  = LDAPConnection.LDAP_V3;        



        try {

           // Create a LDAPConnection object


            LDAPConnection lc = new LDAPConnection();

            

           // Connect to server


            lc.connect( ldapHost, MY_PORT);

            lc.bind(ldapVersion, loginDN, password.getBytes("UTF8") );

            System.out.println( "Login succeeded");



           // We will be searching for all objects 


            String MY_FILTER = "(objectClass=*)";



           //  Results of the search should include givenname and cn


            String[] attrs = new String[2];

            attrs[0] = "givenname";

            attrs[1] = "cn";



           // The results should be sorted using the cn attribute


            LDAPSortKey[] keys = new LDAPSortKey[1];

            keys[0] = new LDAPSortKey( "cn" );

          

           // Create a LDAPSortControl object - Fail if cannot sort


            LDAPSortControl sort = new LDAPSortControl( keys, true );

            

           // Set the Sort control to be sent as part of search request


            LDAPSearchConstraints cons = lc.getSearchConstraints();

            cons.setControls( sort );

            lc.setConstraints(cons);



           // Perform the search - ASYNCHRONOUS SEARCH USED HERE


            System.out.println( "Calling search request");

            LDAPSearchQueue queue = lc.search( searchBase, 

                                               LDAPConnection.SCOPE_SUB, 

                                               MY_FILTER, 

                                               attrs, 

                                               false, 

                                               (LDAPSearchQueue)null,

                                               (LDAPSearchConstraints) null );

  

            LDAPMessage message; 

            while (( message = queue.getResponse()) != null ) {

        

               // OPTION 1: the message is a search result reference


                if ( message instanceof LDAPSearchResultReference ) {                    

                   // Not following referrals to keep things simple


                    String urls[]=((LDAPSearchResultReference)message).getReferrals();

                    System.out.println("Search result references:");                        

                        for ( int i = 0; i < urls.length; i++ )

                            System.out.println(urls[i]); 

                } 

                

               // OPTION 2:the message is a search result


                else if ( message instanceof LDAPSearchResult ) {

                   // Get the object name


                    LDAPEntry entry = ((LDAPSearchResult)message).getEntry();

                       

                    System.out.println("\n" + entry.getDN());

                    System.out.println("\tAttributes: ");



                   // Get the attributes and print them out


                    LDAPAttributeSet attributeSet = entry.getAttributeSet();

                    Iterator allAttributes = attributeSet.iterator();

  

                    while(allAttributes.hasNext()) {

                        LDAPAttribute attribute = (LDAPAttribute)allAttributes.next();

                        String attributeName = attribute.getName();

     

                        System.out.println("\t\t" + attributeName);



                       // Print all values of the attribute


                        Enumeration allValues = attribute.getStringValues();

                        if( allValues != null) {

                            while(allValues.hasMoreElements()) {

                               String Value = (String) allValues.nextElement();

                               System.out.println("\t\t\t" + Value);

                            }

                        }

                    }       

                }                

                

               // OPTION 3: The message is a search response


                else {

                    LDAPResponse response = (LDAPResponse)message;

                    int status = response.getResultCode();

                    

                   // the return code is LDAP success


                    if ( status == LDAPException.SUCCESS ) {

                        System.out.println("Asynchronous search succeeded.");

                    }

                    

                   // the return code is referral exception


                    else if ( status == LDAPException.REFERRAL ) {                        

                        String urls[]=((LDAPResponse)message).getReferrals();

                        System.out.println("Referrals:");                        

                        for ( int i = 0; i < urls.length; i++ )

                            System.out.println(urls[i]);                    

                    }                    

                    else {                        

                        System.out.println("Asynchronous search failed.");

                        System.out.println( response.getErrorMessage());

                    }

                    

                   // Server should send back a control irrespective of the 


                   // status of the search request


                    LDAPControl[] controls = response.getControls();

                    if ( controls != null ) {

                

                       // Theoritically we could have multiple controls returned


                        for( int i = 0; i < controls.length; i++ ) {

                        

                           // We are looking for the LDAPSortResponse Control class - the control


                           // sent back in response to LDAPSortControl


                            if ( controls[i] instanceof LDAPSortResponse ) {

                            

                                System.out.println("Received LDAP Sort Control fromserver");

                            

                               // We must have an error code and maybe a string identifying


                               // erring attribute in the response control.  Get these.


                                String bad = ((LDAPSortResponse)controls[i]).getFailedAttribute();

                                int result = ((LDAPSortResponse)controls[i]).getResultCode();

                          

                               // Print out error ccode (0 if no error) and any returned


                               // attribute


                                System.out.println( "Error code: " + result );

                                if ( bad != null )

                                    System.out.println( "Offending " + "attribute: " + bad );

                                else

                                    System.out.println( "No offending " + "attribute " + "returned" );

                            }

                        }

                    }

                    

                }                            

            }                                                                                     

        

       // All done - disconnect


        if ( lc.isConnected() )

            lc.disconnect();

        }

        

        catch( LDAPException e ) {

            System.out.println( e.toString() );

        }

        catch( UnsupportedEncodingException e ) {

            System.out.println( "Error: " + e.toString() );

        }

    }

}