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

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

 * $Novell: EdirEventSample.java,v 1.2 2004/05/14 17:32:24 $

 * 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.

 *

 * $name:         EdirEventSample.java

 * $description:  The EdirEventSample.java example shows how to perform a

 *                extended operation for receiving the edirectory events.

 *                The EdirEventSample class performs the event registration

 *                in the Edirectory server and receives notification of events

 *                from the server.

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



import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;



import com.novell.ldap.LDAPConnection;

import com.novell.ldap.LDAPException;

import com.novell.ldap.LDAPExtendedRequest;

import com.novell.ldap.LDAPMessage;

import com.novell.ldap.LDAPResponseQueue;

import com.novell.ldap.events.edir.EdirEventConstant;

import com.novell.ldap.events.edir.EdirEventIntermediateResponse;

import com.novell.ldap.events.edir.EdirEventSpecifier;

import com.novell.ldap.events.edir.EventResponseData;

import com.novell.ldap.events.edir.MonitorEventRequest;

import com.novell.ldap.events.edir.MonitorEventResponse;

import com.novell.ldap.events.edir.eventdata.ValueEventData;



public class EdirEventSample {



    static final String QUIT_PROMPT =

        "\nMonitoring changes. Enter a 'q' to quit: ";



    /**

     * Check the queue for a response. If a response has been received,

     * print the response information.

     */

    static private boolean checkForAChange(LDAPResponseQueue queue) {

        LDAPMessage message;

        boolean result = true;



        try {

           //check if a response has been received so we don't block


           //when calling getResponse()


            if (queue.isResponseReceived()) {

                message = queue.getResponse();

                if (message != null) {

                   // is the response a search result reference?


                    if (message instanceof MonitorEventResponse) {

                        MonitorEventResponse eventerrorresponse =

                            (MonitorEventResponse) message;



                        System.out.println(

                            "\nError in Registration ResultCode="

                                + eventerrorresponse.getResultCode());

                        EdirEventSpecifier specifiers[] =

                            eventerrorresponse.getSpecifierList();

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

                            System.out.println(

                                "Specifier: EventClassification="

                                    + specifiers[i].getEventclassification()

                                    + "EventType="

                                    + specifiers[i].getEventtype());

                        }

                        System.exit(-1);



                    }

                   // is the response a event response ?


                    else if (

                        message

                            instanceof EdirEventIntermediateResponse) {

                        System.out.println("Edir Event Occured");

                        EdirEventIntermediateResponse eventresponse =

                            (EdirEventIntermediateResponse) message;



                        System.out.println(

                            "Event Type=" + eventresponse.getEventtype());

                        System.out.println(

                            "Event Result="

                                + eventresponse.getEventResult());

                       //process the eventresponse Data, depending on the


                       // type of response 


                        processEventData(

                            eventresponse.getResponsedata(),

                            eventresponse.getEventtype());



                        System.out.print(QUIT_PROMPT);

                    }

                   // the message is a Unknown response


                    else {

                        System.out.println("UnKnown Message =" + message);

                    }

                }

            }

        } catch (LDAPException e) {

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

            result = false;

        }



        return result;

    }



    public static void main(String[] args) {

        if (args.length != 3) {

            System.err.println(

                "Usage:   java EdirEventSample <host name> <login dn>"

                    + " <password> ");

            System.err.println(

                "Example: java EdirEventSample Acme.com \"cn=admin,o=Acme\""

                    + " secret ");

            System.exit(0);

        }



        int ldapPort = LDAPConnection.DEFAULT_PORT;

        int ldapVersion = LDAPConnection.LDAP_V3;

        String ldapHost = args[0];

        String loginDN = args[1];

        String password = args[2];



        LDAPResponseQueue queue = null;



        LDAPConnection lc = new LDAPConnection();



        try {

           // connect to the server


            lc.connect(ldapHost, ldapPort);

           // authenticate to the server


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



           //Create an Array of EdirEventSpecifier


            EdirEventSpecifier specifier[] = new EdirEventSpecifier[1];



           //Register for all Add Value events.


            specifier[0] =

                new EdirEventSpecifier(EdirEventConstant.EVT_ADD_VALUE,

               //Generate an Value Event of Type Add Value 


    EdirEventConstant.EVT_STATUS_ALL

               //Generate Event for all status


    );



           //Create an MonitorEventRequest using the specifiers.        


            MonitorEventRequest requestoperation =

                new MonitorEventRequest(specifier);

           //Create an LDAPExtendedRequest , with above ldapextendedoperation.


            LDAPExtendedRequest request =

                new LDAPExtendedRequest(requestoperation, null);



           //Send the request to server and get the response queue.


            queue = lc.extendedOperation(requestoperation, null, null);



           // use default search constraints


        } catch (LDAPException e) {

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

            try {

                lc.disconnect();

            } catch (LDAPException e2) {

            }

            System.exit(1);

        } catch (UnsupportedEncodingException e) {

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

        }



       // persistent search initiated without error, monitor the results


       // looping until the user quits by entering a 'q' or 'Q'




        BufferedReader in =

            new BufferedReader(new InputStreamReader(System.in));



        try {//loop until the user quits by entering 'q' or 'Q'


            System.out.print(QUIT_PROMPT);

            String input;

            while (true) {

                if (in.ready()) {

                    input = in.readLine();

                    if (input.startsWith("q") || input.startsWith("Q"))

                        break;

                    else

                        System.out.print(QUIT_PROMPT);

                }

                if (!checkForAChange(queue))

                    break;

                Thread.sleep(10);

            }

        } catch (IOException e) {

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

        } catch (InterruptedException e) {

        }



       //disconnect from the server before exiting


        try {

            lc.abandon(queue);//abandon the search


            lc.disconnect();

        } catch (LDAPException e) {

            System.out.println();

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

        }



        System.exit(0);



    }// end main


    /**

     * Processes the Event Data depending on the Type.

     * @param data EventResponseData.

     * @param type Type of Data.

     */

    static private void processEventData(

        EventResponseData data,

        int type) {

        switch (type) {

            case EdirEventConstant.EVT_ADD_VALUE :

               // Value event.


               //Output the relevant Data.


                ValueEventData valueevent = (ValueEventData) data;

                System.out.println("Entry =" + valueevent.getEntry());

                System.out.println(

                    "attribute =" + valueevent.getAttribute());

                System.out.println("Class id =" + valueevent.getClassid());

                System.out.println("Data=" + valueevent.getData());

                System.out.println(

                    "prepetratorDN=" + valueevent.getPrepetratorDN());

                System.out.println("Syntax=" + valueevent.getSyntax());

                System.out.println(

                    "timeStamp=" + valueevent.getTimeStamp());



                break;

            default :

               //Unknow Event.


                break;

        }



    }

}