List of usage examples for javax.naming.directory SearchControls SUBTREE_SCOPE
int SUBTREE_SCOPE
To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.
Click Source Link
From source file:it.webappcommon.lib.LDAPHelper.java
/** * @param args/* ww w.ja v a2 s. 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: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 ww . j av a 2 s .c om 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: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); }//from ww w . j ava2s. c om 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:es.udl.asic.user.OpenLdapDirectoryProvider.java
private boolean getUserInf(UserEdit edit, String filter) { String id = null;//from w ww.jav a 2 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; }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public boolean isExistingServicePrinciple(String servicePrinciple) throws DirectoryServerManagerException { DirContext dirContext;/* ww w. ja v a2 s. c o m*/ try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { log.error("Unable to retrieve directory context.", e); throw new DirectoryServerManagerException("Unable to retrieve directory context.", e); } //first search the existing user entry. String searchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String filter = getServicePrincipleFilter(servicePrinciple); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_UID }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, filter, searchControls); return namingEnumeration.hasMore(); } catch (NamingException e) { String message = "Unable to search entry with search base " + searchBase + ", filter -" + filter; log.error(message, e); throw new DirectoryServerManagerException("Can not access the directory service", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } }
From source file:edu.internet2.middleware.psp.util.PSPUtil.java
/** * Return <code>SearchControls</code> search scope from an SPML <code>Scope</code>. * //from w w w .ja v a 2 s .c o m * @param scope the SPML scope * @return the javax.naming.directory search scope as an int */ public static int getScope(Scope scope) { if (scope.equals(Scope.ONELEVEL)) { return SearchControls.OBJECT_SCOPE; } else if (scope.equals(Scope.SUBTREE)) { return SearchControls.SUBTREE_SCOPE; } else if (scope.equals(Scope.PSO)) { return SearchControls.OBJECT_SCOPE; } throw new IllegalArgumentException("Unknow scope " + scope); }
From source file:alpine.auth.LdapConnectionWrapper.java
/** * Performs a search for the specified username. Internally, this method queries on * the attribute defined by {@link Config.AlpineKey#LDAP_ATTRIBUTE_NAME}. * @param ctx the DirContext to use/* w ww. ja va 2 s . co m*/ * @param username the username to query on * @return a list of SearchResult objects. If the username is found, the list should typically only contain one result. * @throws NamingException if an exception is thrown * @since 1.4.0 */ public List<SearchResult> searchForUsername(DirContext ctx, String username) throws NamingException { final String[] attributeFilter = {}; final SearchControls sc = new SearchControls(); sc.setReturningAttributes(attributeFilter); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); final String searchFor = LdapConnectionWrapper.ATTRIBUTE_NAME + "=" + LdapStringSanitizer.sanitize(formatPrincipal(username)); return Collections.list(ctx.search(LdapConnectionWrapper.BASE_DN, searchFor, sc)); }
From source file:org.lsc.jndi.FullDNJndiDstService.java
/** * Returns a list of all the objects' identifiers. * //from w ww. java2 s. com * @return Map of all entries DNs (this is not for display only!) * that are returned by the directory with an associated map of attribute names and values (never null) * @throws LscServiceException * @throws NamingException */ @SuppressWarnings("unchecked") public Map<String, LscDatasets> getListPivots() throws LscServiceException { List<String> idList = null; try { // get list of DNs idList = jndiServices.getDnList(getBaseDn(), getFilterAll(), SearchControls.SUBTREE_SCOPE); // sort the list by shortest first - this makes sure clean operations delete leaf elements first Collections.sort(idList, new StringLengthComparator()); } catch (ClassCastException e) { // ignore errors, just leave list unsorted } catch (UnsupportedOperationException e) { // ignore errors, just leave list unsorted } catch (NamingException e) { throw new LscServiceException(e.toString(), e); } // convert to correct return format /* TODO: This is a bit of a hack - we use ListOrderedMap to keep order of the list returned, * since it may be important when cleaning by full DN (for different levels). * This is really an API bug, getListPivots() should return a List, not a Map. */ Map<String, LscDatasets> ids = new ListOrderedMap(); for (String dn : idList) { String completedDn = jndiServices.completeDn(dn); LscDatasets attrs = new LscDatasets(); attrs.put("dn", completedDn); ids.put(completedDn, attrs); } return ids; }
From source file:org.apache.cxf.sts.ldap.LDAPClaimsTest.java
@org.junit.Test @org.junit.Ignore//from w w w. j a v a2 s. com public void testLdapTemplate() throws Exception { try { LdapTemplate ldap = (LdapTemplate) appContext.getBean("ldapTemplate"); String user = props.getProperty("claimUser"); Assert.notNull(user, "Property 'claimUser' not configured"); String dn = null; AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("cn", user)); //find DN of user AttributesMapper mapper = new AttributesMapper() { public Object mapFromAttributes(Attributes attrs) throws NamingException { return attrs.get("distinguishedName").get(); } }; @SuppressWarnings("rawtypes") List users = ldap.search("OU=users,DC=emea,DC=mycompany,DC=com", filter.toString(), SearchControls.SUBTREE_SCOPE, mapper); Assert.isTrue(users.size() == 1, "Only one user expected"); dn = (String) users.get(0); // get attributes AttributesMapper mapper2 = new AttributesMapper() { public Object mapFromAttributes(Attributes attrs) throws NamingException { Map<String, String> map = new HashMap<String, String>(); NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll(); while (attrEnum.hasMore()) { Attribute att = attrEnum.next(); System.out.println(att.toString()); } map.put("cn", (String) attrs.get("cn").get()); map.put("mail", (String) attrs.get("mail").get()); map.put("sn", (String) attrs.get("sn").get()); map.put("givenName", (String) attrs.get("givenName").get()); return map; } }; ldap.lookup(dn, new String[] { "cn", "mail", "sn", "givenName", "c" }, mapper2); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java
public List<String> searchForUserName(String containString, LdapContext ldapContext) throws NamingException { List<String> userNameList = new ArrayList<>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))"; Object[] searchArguments = new Object[] { containString }; NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (log.isDebugEnabled()) { log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]"); }//from ww w . j ava2 s. c o m Attributes attrs = sr.getAttributes(); if (attrs != null) { NamingEnumeration ae = attrs.getAll(); while (ae.hasMore()) { Attribute attr = (Attribute) ae.next(); if (attr.getID().toLowerCase().equals("cn")) { userNameList.addAll(LdapUtils.getAllAttributeValues(attr)); } } } } return userNameList; }