List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:com.aurel.track.util.LdapUtil.java
/** * Returns the CN (common name) for a given login name * // ww w . j a v a 2s . c o m * @param loginName * the loginName of the user * @return CN as a String(if found), or null (else) */ private static String getCn(TSiteBean siteBean, String loginName) throws NamingException { String keyDn = null; DirContext ctx = getInitialContext(siteBean.getLdapServerURL(), siteBean.getLdapBindDN(), siteBean.getLdapBindPassword()); if (ctx != null) { SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search for the user-id String searchStr = "(" + siteBean.getLdapAttributeLoginName() + "=" + loginName + ")"; NamingEnumeration<SearchResult> answer = ctx.search("", searchStr, ctls); if (answer.hasMore()) { // retrieve the CN SearchResult sr = answer.next(); keyDn = sr.getName();// + "," + ctx.getNameInNamespace(); LOGGER.debug("Name = " + keyDn); String nameInNamespace = ctx.getNameInNamespace(); LOGGER.debug("Name in namespace " + nameInNamespace); if (nameInNamespace != null && nameInNamespace.trim().length() > 0) { keyDn += "," + ctx.getNameInNamespace(); } LOGGER.debug("entry found for LDAP-search >" + searchStr + "<: dn= >" + keyDn + "<!"); answer.close(); // wo don't need more answers } else { LOGGER.debug("no entry found for LDAP-search >" + searchStr + "<!"); } ctx.close(); } return keyDn; }
From source file:org.apache.cloudstack.ldap.LdapUserManager.java
public List<LdapUser> searchUsers(final String username, final LdapContext context) throws NamingException, IOException { final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(_ldapConfiguration.getScope()); searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); String basedn = _ldapConfiguration.getBaseDn(); if (StringUtils.isBlank(basedn)) { throw new IllegalArgumentException("ldap basedn is not configured"); }/*from ww w. j a va2 s. c o m*/ byte[] cookie = null; int pageSize = _ldapConfiguration.getLdapPageSize(); context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); final List<LdapUser> users = new ArrayList<LdapUser>(); NamingEnumeration<SearchResult> results; do { results = context.search(basedn, generateSearchFilter(username), searchControls); while (results.hasMoreElements()) { final SearchResult result = results.nextElement(); users.add(createUser(result)); } Control[] contextControls = context.getResponseControls(); if (contextControls != null) { for (Control control : contextControls) { if (control instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) control; cookie = prrc.getCookie(); } } } else { s_logger.info("No controls were sent from the ldap server"); } context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); return users; }
From source file:com.healthcit.cacure.businessdelegates.LdapUserManager.java
public List<UserCredentials> getAllUsers() { List<UserCredentials> userCredentials = new ArrayList<UserCredentials>(); try {/*from w ww . ja v a2s .co m*/ SearchControls searchCtls = new SearchControls(); String returnedAtts[] = { "uid" }; searchCtls.setReturningAttributes(returnedAtts); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(&(objectClass=person))"; NamingEnumeration<SearchResult> elements = contextSource.getReadOnlyContext().search("", searchFilter, searchCtls); while (elements.hasMoreElements()) { DistinguishedName dn = new DistinguishedName(elements.nextElement().getName()); String userName = dn.getValue("uid"); userCredentials.add(getUserFromDatabase(userName)); } } catch (org.springframework.ldap.NamingException e) { e.printStackTrace(); return null; } catch (NamingException e) { e.printStackTrace(); return null; } return userCredentials; }
From source file:com.wfp.utils.LDAPUtils.java
/** * Search the LDAP based on default inputs. This method searches for <b>memberOf </b> * @return//from w ww.j ava 2 s .co m * @throws NamingException */ @SuppressWarnings("unchecked") public static NamingEnumeration getSearchResults() { // Specify the attributes to return String returnedAtts[] = { PROPERTY_MEMBER_OF }; // Specify the search scope SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); // Search for objects using the filter try { return getSearchResults(getLDAPContext(), searchCtls, SEARCH_FILTER, LDAP_BASE); } catch (NamingException e) { Logger.error("Error occured while searching results : 181: getSearchResults():[" + e.getLocalizedMessage() + "]", LDAPUtils.class); } return null; }
From source file:org.apache.archiva.redback.users.ldap.LdapUserManagerTest.java
private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException { SearchControls ctls = new SearchControls(); ctls.setDerefLinkFlag(true);//from w w w.j a v a 2s . co m ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ctls.setReturningAttributes(new String[] { "*" }); BasicAttributes matchingAttributes = new BasicAttributes(); matchingAttributes.put(attribute, value); BasicAttribute objectClass = new BasicAttribute("objectClass"); objectClass.add("inetOrgPerson"); matchingAttributes.put(objectClass); NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes); // NamingEnumeration<SearchResult> results = context.search( suffix, "(" + attribute + "=" + value + ")", ctls // ); assertTrue(results.hasMoreElements()); SearchResult result = results.nextElement(); Attributes attrs = result.getAttributes(); Attribute testAttr = attrs.get(attribute); assertEquals(value, testAttr.get()); }
From source file:it.webappcommon.lib.LDAPHelper.java
/** * @param args/*from w w w . java 2s . c o m*/ * the command line arguments */ // public static void main(String[] args) { private List<UserInfo> search(String filter) throws NamingException { DirContext ctx = null; SearchControls ctls = null; Properties env = new Properties(); List<UserInfo> res = new ArrayList<UserInfo>(); boolean trovatiRisultati = false; env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT); env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port); env.put(Context.SECURITY_AUTHENTICATION, "simple"); if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) { env.put(Context.SECURITY_PRINCIPAL, loginUserName); } else { env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName); } env.put(Context.SECURITY_CREDENTIALS, loginPassword); try { ctx = new InitialDirContext(env); ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // String filter = ""; // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))"; // filter = FILTER_USERS_ACTIVE; // Tutti i membri di un gruppo // (objectCategory=user)(memberOf=CN=QA Users,OU=Help // Desk,DC=dpetri,DC=net) // ESEMPI // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm // Account disabled // (UserAccountControl:1.2.840.113556.1.4.803:=2) NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls); UserInfo userInfo = null; while (answer.hasMoreElements()) { trovatiRisultati = true; SearchResult a = answer.nextElement(); // logger.debug(a.getNameInNamespace()); Attributes result = a.getAttributes(); if (result == null) { // System.out.print("Attributi non presenti"); } else { NamingEnumeration<? extends Attribute> attributi = result.getAll(); userInfo = new UserInfo(); while (attributi.hasMoreElements()) { Attribute att = attributi.nextElement(); // logger.debug(att.getID()); String value = ""; // for (NamingEnumeration vals = att.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())) // ; NamingEnumeration<?> vals = att.getAll(); while (vals.hasMoreElements()) { Object val = vals.nextElement(); // logger.debug("\t" + val); value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString(); } if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) { // userInfo.setFIELD_ACCOUNT_NAME(value); userInfo.setAccount(value); } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) { // userInfo.setFIELD_COGNOME(value); userInfo.setCognome(value); } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) { // userInfo.setFIELD_EMAIL(value); userInfo.setEmail(value); } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) { // userInfo.setFIELD_GROUPS(value); userInfo.setGruppi(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) { // userInfo.setFIELD_NOME(value); userInfo.setNome(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) { // userInfo.setFIELD_NOME_COMPLETO(value); userInfo.setNomeCompleto(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) { // userInfo.setFIELD_NOME_VISUALIZZATO(value); // userInfo.setNome(value); } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) { // userInfo.setFIELD_TEL(value); userInfo.setTel(value); } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) { // userInfo.setFIELD_UFFICIO(value); userInfo.setUfficio(value); } // res.put(att.getID(), value); } // Attribute attr = result.get("cn"); // if (attr != null) { // logger.debug("cn:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // attr = result.get("sn"); // if (attr != null) { // logger.debug("sn:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // attr = result.get("mail"); // if (attr != null) { // logger.debug("mail:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // // attr = result.get("uid"); // // if (attr != null) { // // logger.debug("uid:"); // // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // // } // // // // attr = result.get("userPassword"); // // if (attr != null) { // // logger.debug("userPassword:"); // // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // // } if (userInfo != null) { res.add(userInfo); } } } } catch (NamingException ne) { // ne.printStackTrace(); logger.error(ne); throw ne; } finally { try { if (ctx != null) { ctx.close(); } } catch (Exception e) { } } // Azzero l'hash map if (!trovatiRisultati) { res = null; } return res; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java
public NamingEnumeration<SearchResult> query(DirContext ctx, String pBaseDn, String filter, String[] attributeFilter, Integer pScope) throws NamingException, IllegalAccessException { NamingEnumeration<SearchResult> vResult; SearchControls sControl = new SearchControls(); if (attributeFilter != null) { sControl.setReturningAttributes(attributeFilter); }// w w w. j ava2s. co m int vScope = SearchControls.SUBTREE_SCOPE; if (pScope != null) { vScope = pScope.intValue(); } sControl.setSearchScope(vScope); vResult = ctx.search(((pBaseDn != null) && (pBaseDn.length() > 0) ? pBaseDn : LDAPConnector.getSingletonInstance().getBaseDn()), filter, sControl); return vResult; }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the field value of the specified field for the specified id. * @see IExternalStorage#getField(java.lang.String, java.lang.String) *//*from w w w. j a va 2 s. co m*/ public Object getField(String id, String field) throws UserException { DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; Object oValue = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attribute '"); sbFailed.append(field); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration oAttrEnum = oAttributes.getAll(); if (oAttrEnum.hasMore()) { Attribute oAttribute = (Attribute) oAttrEnum.next(); oValue = oAttribute.get(); } } catch (UserException e) { throw e; } catch (Exception e) { _logger.error("Could not retrieve field: " + field, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return oValue; }
From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java
private String searchUser(String login, HashMap<String, String> userAttrs, DirContext ctx) throws NamingException { String uid;//from w w w. j a va2 s .c om SearchControls ctls = new SearchControls(); ctls.setReturningObjFlag(true); ctls.setSearchScope(searchScope); String search = searchPattern.replaceAll(Pattern.quote("%LOGIN%"), escapeLDAPSearchFilter(login)); log.debug("Searching LDAP for " + search); NamingEnumeration<SearchResult> answer = ctx.search(base, search, ctls); try { if (!answer.hasMore()) throw new NoSuchElementException(); log.debug("LDAP returned >=1 record."); SearchResult result = answer.next(); uid = result.getName(); for (Map.Entry<String, String> e : attributeMap.entrySet()) { log.debug("found LDAP attribute: " + e.getKey()); Attribute a = result.getAttributes().get(e.getKey()); if (a != null) userAttrs.put(e.getValue(), a.get().toString()); } } finally { answer.close(); } return uid; }
From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java
private boolean getUserInf(UserEdit edit, String filter) { String id = null;//from w w w.j a va2 s . c o m String firstName = null; String lastName = null; String employeenumber = null; String email = null; try { DirContext ctx = new InitialDirContext(env); // Setup subtree scope to tell LDAP to recursively descend directory structure // during searches. SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); // We want the user's id, first name and last name ... searchControls.setReturningAttributes(new String[] { "uid", "givenName", "sn" }); // Execute the search, starting at the directory level of Users NamingEnumeration results = ctx.search(getBasePath(), filter, searchControls); while (results.hasMore()) { SearchResult result = (SearchResult) results.next(); String dn = result.getName().toString() + "," + getBasePath(); Attributes attrs = ctx.getAttributes(dn); id = attrs.get("uid").get().toString(); String cn = attrs.get("cn").get().toString(); firstName = cn.substring(0, cn.indexOf(" ")); lastName = cn.substring(cn.indexOf(" ")); email = attrs.get("mail").get().toString(); } results.close(); ctx.close(); } catch (Exception ex) { ex.printStackTrace(); return false; } edit.setId(id); edit.setFirstName(firstName); edit.setLastName(lastName); edit.setEmail(email); return true; }