I want to search a user in Active Directory with sAMaccountName,where the sAMaccountName is firstName.substring(0,1)+lastName+ending with any digit. Code Snippet:
try {
context=this.getADConnection();
String returnedAtts[]={"givenName","sn"};
String sAMAccountNameRegex=sAMAccountName+"\\d*";
//String sAMAccountNameRegex=sAMAccountName+Pattern.quote("[0-9]*");
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setReturningAttributes(returnedAtts);
searchControls.setReturningAttributes(returnedAtts);
searchControls.setReturningAttributes(returnedAtts);
//String searchFilter = "(&(objectClass=user)(givenName=" +firstInitial+"*)(sn="+lastName+"))";
String searchFilter = "(&(objectClass=user) (|(&(givenName=" +firstInitial+"*)(sn="+lastName+"))(sAMAccountName=("+sAMAccountNameRegex+"))) )";
logger.info(className + privateMethodName + " Searching User using filter : [" + searchFilter + "]");
// Search for objects using the filter
// Search for objects using the filter
NamingEnumeration<SearchResult> results = context.search(SAMAccountNamePrePop.adSearchBase, searchFilter, searchControls);
SearchResult searchResult = null;
while(results.hasMoreElements()) {
searchResult = (SearchResult) results.nextElement();
logger.info(className + privateMethodName + " Search Result : [" + searchResult + "]");
totalResults++;
}`
Search filter used is
String searchFilter = "(&(objectClass=user) (|(&(givenName=" +firstInitial+"*)(sn="+lastName+"))(sAMAccountName=("+sAMAccountNameRegex+"))) )";
I have tried with following search filters for sAMaccountName,but none worked and gives following exceptions
String sAMAccountNameRegex=sAMaccountName.Pattern.quote("\\d*");
Exception is: [invalid escape sequence: [B@755c9b9c]
after passing values searchfileter looks like:
[(&(objectClass=user) (|(&(givenName=C*)(sn=BOND3))(sAMAccountName=(CBOND3\Q\d*\E))) )]
String sAMAccountNameRegex=sAMAccountName+"([0-9]*)$";
Exception is:[[LDAP: error code 32 - 0000208D: NameErr: DSID-031001E5, problem 2001 (NO_OBJECT), data 0, best match of: '']]
after passing values searchfileter looks like:
[(&(objectClass=user) (|(&(givenName=C*)(sn=BOND3))(sAMAccountName=(CBOND3([0-9]*)$))) )]
String sAMAccountNameRegex=sAMAccountName+"\d*";
Exception:[[LDAP: error code 32 - 0000208D: NameErr: DSID-031001E5, problem 2001 (NO_OBJECT), data 0, best match of: '' ]]
after passing values searchfileter looks like:
[(&(objectClass=user) (|(&(givenName=C*)(sn=BOND3))(sAMAccountName=(CBOND3\d*))) )]
So is it possible to query Ldap where the searchfilter is combination of string and regex?