Type Ahead search from Active Directory


// Add this java class to you NSF

import javax.naming.*;
import javax.naming.directory.*;
import java.util.*;
public class LDAPQuery {

		public static String getTypeAhead(String searchQuery) {

			try {
				Hashtable env = new Hashtable();
				env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
				env.put(Context.PROVIDER_URL, "ldap://ldapserver:389");
				env.put(Context.SECURITY_PRINCIPAL, "username");
				env.put(Context.SECURITY_CREDENTIALS, "password");
				DirContext ctx = new InitialDirContext(env);
				String[] attrIDs = { "cn", "mail", "distinguishedName" };
				SearchControls ctls = new SearchControls();
				ctls.setReturningAttributes(attrIDs);
				ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

				String filter = "cn=" + searchQuery;
				NamingEnumeration<?> answer = ctx.search("OU=?,DC=?,DC=?", filter, ctls);

				try {

					String retV = "";
					String retF = "<ul>";
					while (answer.hasMore()) {
						SearchResult sr = (SearchResult) answer.next();
						Attributes attrs = sr.getAttributes();
						retV = attrs.get("distinguishedName").get().toString().replaceAll(",", "/");
						retF += "<li>" + retV + "</li>";
					}
					ctx.close();
					return retF + "</ul>";
				} catch (PartialResultException e) {
					e.printStackTrace();
					return "<li>Error</li>";
				}
			} catch (Exception e) {
				e.printStackTrace();
				return "<li>Error</li>";
			}
		}
	}

// Make the java class a managed bean in faces-config

 <managed-bean>
    <managed-bean-name>LDAPQuery</managed-bean-name>
    <managed-bean-class>com.company.LDAPQuery</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>

// Add a typeAhead input box to your xpage

<xp:inputText id="inputText3" value="#{doc.Responsible}">
	<xp:typeAhead mode="full" minChars="2" var="searchValue"
		valueMarkup="true">
		<xp:this.valueList><![CDATA[#{javascript:LDAPQuery.getTypeAhead(getComponent("inputText3").getValue()+"*")}]]></xp:this.valueList>
	</xp:typeAhead>
</xp:inputText>

All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.
No comments yetLogin first to comment...