/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ldap;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;
import org.apache.directory.api.ldap.model.password.PasswordUtil;
import org.apache.directory.api.util.Strings;

/**
 *
 * @author micha
 */
public class LDAP {

    PasswordUtil pu;

    LDAP() {

        try {
            DirContext dctxt = connect();
            LdapContext lc = (LdapContext) dctxt.lookup("dc=wara-rocks,dc=org");
//            System.out.println("obj" + lc);

//            NamingEnumeration list = dctxt.list("dc=wara,dc=de");
//
//            while (list.hasMore()) {
//                NameClassPair nc = (NameClassPair) list.next();
//                System.out.println(nc);
//            }
            System.out.println("------------------");

            //suchfilter
            //String filter = "(userPassword=e1NTSEF9YmxSVzJrcnpFWUJjMFJLbHgyVkJhQlhrcHFNdGVPQVg=)";
            String filter = "(uidNumber=5000)";

            //auszugebende attrs festlegen
            // Specify the ids of the attributes to return
            String[] attrIDs = {"cn", "uid", "userPassword"};
            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(attrIDs);
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            ctls.setReturningObjFlag(true);

            //mit suche
            //Attributes matchAttrs = new BasicAttributes(true);
            //    matchAttrs.put(new BasicAttribute("sn", "Neumann"));
            //           matchAttrs.put(new BasicAttribute("cn"));
            // Search for objects that have those matching attributes
            NamingEnumeration answer = dctxt.search("dc=wara-rocks,dc=org", filter, ctls);

            // Print the answer
            while (answer.hasMore()) {
                SearchResult sr = (SearchResult) answer.next();

                Attributes attrs = sr.getAttributes();

                System.out.println(sr.getName());
                System.out.println("Anzahl attr: " + attrs.size());

                byte[] userCredentials = "mad".getBytes();
                
                for (NamingEnumeration e = attrs.getAll(); e.hasMore();) {
                    Attribute attr = (Attribute) e.next();
                    if (attr.getID().equals("userPassword")) {
                        //alfred=mad: {SSHA}blRW2krzEYBc0RKlx2VBaBXkpqMteOAX
                        //kilroy=dam: {SSHA}mylZGoDIHiYZgr7N348ZmNdWwK7+l7uc
                        for (NamingEnumeration ne = attr.getAll();
                                ne.hasMore();) {
                            byte[] storedCredentials = (byte[])ne.next();                        
                            System.out.println(new String(storedCredentials));
                            System.out.println(pu.compareCredentials(userCredentials, storedCredentials));
                        }
                    } else {
                        System.out.println(attr);
                    }
                }

            }

            // Close the context when we're done
            dctxt.close();

            // System.out.println("anser-obj"+answer.toString());
//            while (answer.hasMore()) {
//                NameClassPair nc = (NameClassPair) list.next();
//                System.out.println(nc);
//            }
        } catch (NamingException ne) {
            ne.printStackTrace();
        }

    }

    DirContext connect() throws NamingException {
        // Set up the environment for creating the initial context
        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://localhost:389");

// Authenticate as S. User and password "mysecret"
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL,
                "cn=admin,dc=wara-rocks,dc=org");
        env.put(Context.SECURITY_CREDENTIALS, "ljwml!");

// Create the initial context
        return new InitialDirContext(env);
    }

    void printAttrs(Attributes answer) throws NamingException {
        for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) {
            Attribute attr = (Attribute) ae.next();
            System.out.println("attribute: " + attr.getID());
            /* Print each value */
            for (NamingEnumeration e = attr.getAll(); e.hasMore();
                    System.out.println("value: " + e.next()))
        ;
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new LDAP();
    }

}
