import java.io.*;
import java.util.*;
import javax.naming.ldap.*;
import javax.naming.directory.*;
import javax.naming.*;
import java.security.cert.*;

class Search
{
    public static void ShowListCert(NamingEnumeration ans)
    {
        try
        {
            int count_cert = 0;
            NamingEnumeration answer = ans;
            if(answer.hasMoreElements())
            {
                while(answer.hasMore())
                {
                    SearchResult sr = (SearchResult)answer.next();
                    System.out.println("==================================================================");
                    System.out.println(sr.getNameInNamespace());
                    System.out.println("------------------------------------------------------------------");

                    Attributes pp = sr.getAttributes();
                    for (Enumeration e = pp.getAll() ; e.hasMoreElements() ;)
                    {
                        Attribute attr = (Attribute) e.nextElement();
                        String attrID = attr.getID();
                        if(attrID.equals("userCertificate"))
                        {
                            count_cert += attr.size();
                            for(int i=0;i<attr.size();i++)
                            {
                                try
                                {
                                    Object csd = attr.get(i);
                                    byte[] csd_b = (byte[]) csd;
                                    ByteArrayInputStream bis1 = new ByteArrayInputStream(csd_b);
                                    CertificateFactory cf1 = CertificateFactory.getInstance("X.509");
                                    Collection c1 = cf1.generateCertificates(bis1);
                                    Iterator i1 = c1.iterator();
                                    while (i1.hasNext())
                                    {
                                        Certificate cert = (Certificate)i1.next();
                                        X509Certificate x509cert = (X509Certificate)cert;
                                        java.security.Principal principal = x509cert.getSubjectDN();
                                        System.out.println("\t" + principal.getName()+"\n\n");
                                    }
                                }
                                catch(Exception parse){System.out.println("No information!");}
                            }
                        }
                    }
                }
                System.out.println("Count:" + count_cert);
            }
        }
        catch(Exception e){System.out.println(e);}
    }
    public static String CreateFilter(String filter_str)
    {
        String filter = filter_str;
        try
        {
            String [] arr_str = filter.split(",");
            filter = "";
            for(int i=0; i<arr_str.length; i++)
            {
                filter += "("+arr_str[i]+")";
            }
            return filter;
        }
        catch(Exception e){return filter="";}
    }
    public static void main(String args[])
    {
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            String arg[] = new String[5];
            int i=0;
            while(i<arg.length)
            {
                switch(i)
                {
                    case 0: System.out.print("Enter ip store: ");break;
                    case 1: System.out.print("Enter user name: ");break;
                    case 2: System.out.print("Enter user password: ");break;
                    case 3: System.out.print("Enter DN name: ");break;
                    case 4: System.out.print("Enter filter: ");break;
                }
                arg[i] = br.readLine();
                if(arg[i].length()!=0)
                    i++;
            }
            String ldapURL = arg[0];
            String userName = "dn:t=L;cn="+arg[1];
            String userPass = arg[2];
            String dnName = arg[3];
            String filter = arg[4];

            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.SECURITY_AUTHENTICATION,"DIGEST-MD5");
            env.put(Context.PROVIDER_URL,ldapURL);
            env.put(Context.SECURITY_PRINCIPAL,userName);
            env.put(Context.SECURITY_CREDENTIALS,userPass);
            //В общем искать можно и userCertificate и userTemplate и certificateRevocationList. Пока стоит   userCertificate.
            //Если искать по другим атрибутам кроме userCertificate, то надо фунцию ShowListCert для каждого атрибута. В примерах(getCert.java, getCrl.java, getTemplate.java)  эта функция для кажкдого случая.
            env.put("java.naming.ldap.attributes.binary","userCertificate");

            LdapContext ctx = new InitialLdapContext(env, null);
            SearchControls ctls = new SearchControls();
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            //Сдесь создается фильтр для поиска. параметры филтра воодятся через запятую, например: cn=OCSP, mail=d_ermolaev@gamma.kz или есть возможность испрльзовать *,
            //например: cn=OC* ,  mail=d_* и т.д.
            filter = CreateFilter(filter);
            System.out.println(filter);

            NamingEnumeration answer = ctx.search(dnName, "(&(userCertificate=*)"+filter+")", ctls);
            ShowListCert(answer);
            ctx.close();
        }
        catch(Exception e){System.out.println("Exception: "+ e +"\n Possible, there were enter not correct data");}
    }
}