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

 * $Novell: Ldap2Ldif.java,v 1.7 2003/08/21 11:49:21 $

 * Copyright (c) 2003 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:         Ldap2Dsml.java

 * $description:  Ldap2Dsml.java searches an LDAP directory and write

 *                the returned search entries to an LDIF content file.

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

import com.novell.ldap.LDAPConnection;

import com.novell.ldap.LDAPException;

import com.novell.ldap.LDAPMessage;

import com.novell.ldap.LDAPResponse;

import com.novell.ldap.LDAPSearchQueue;

import com.novell.ldap.LDAPSearchResult;

import com.novell.ldap.LDAPSearchResultReference;

import com.novell.ldap.LDAPSearchConstraints;

import com.novell.ldap.util.LDIFWriter;

import com.novell.ldap.util.LDAPWriter;



import java.util.Enumeration;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.UnsupportedEncodingException;



public class Ldap2Ldif

{

    public static void main( String[] args )

    {

        if (args.length != 6) {

            usage();

        }



        int ldapPort = LDAPConnection.DEFAULT_PORT;

        int ldapVersion = LDAPConnection.LDAP_V3;

        LDAPConnection lc = new LDAPConnection();

        String ldapHost = args[0];

        String loginDN = args[1];

        String password = args[2];

        String searchBase = args[3];

        String searchFilter= args[4];

        String fileName = args[5];

        LDAPMessage msg;





        try {

            // connect to the server

            lc.connect( ldapHost, ldapPort );

            // authenticate to the server

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



            FileOutputStream fos = new FileOutputStream(fileName);

            LDAPWriter writer = new LDIFWriter(fos);



            // asynchronous search

            LDAPSearchQueue queue =

                lc.search(searchBase,      // container to search

                          LDAPConnection.SCOPE_ONE,// search container only

                          searchFilter,    // search filter

                          null,            // return all attrs

                          false,           // return attrs and values

                          (LDAPSearchQueue)null, // default search queue

                          (LDAPSearchConstraints)null); //default constraints



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

                // the message is a search result reference

                if ( msg instanceof LDAPSearchResultReference ) {

                    String urls[] =

                        ((LDAPSearchResultReference)msg).getReferrals();

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

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

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

                }

                // the message is a search result

                else if (msg instanceof LDAPSearchResult ) {

                    writer.writeMessage(msg);

                }

                // the message is a search response

                else {

                    LDAPResponse response = (LDAPResponse)msg;

                    int status = response.getResultCode();

                    // the return code is LDAP success

                    if ( status == LDAPException.SUCCESS ) {

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

                    }

                    // the reutrn code is referral exception

                    else if ( status == LDAPException.REFERRAL ) {

                        String urls[]=((LDAPResponse)msg).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.");

                        throw new LDAPException( response.getErrorMessage(),

                                                 status,

                                                 response.getMatchedDN());

                    }

                }

            }



            // close the output stream

            writer.finish();

            fos.close();

            System.out.println("An LDIF content file was generated.");



            // disconnect with the server

            lc.disconnect();

        }

        catch( UnsupportedEncodingException e ) {

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

        }

        catch (IOException fe) {

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

        }

        catch( LDAPException e ) {

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

        }

        System.exit(0);

    }



    public static void usage() {

        System.err.println("Usage:   java Ldap2Ldif <host name> <login dn>"

                + " <password> <search base> <search filter> < out file name>");

        System.err.println("Example: java Ldap2Dsml Acme.com"

                                    + " \"cn=admin,o=Acme\""

                                    + " secret \"ou=sales,o=Acme\"\n"

                                    + "         \"objectclass=*\" out.ldif");

        System.exit(1);

    }

}

