List of usage examples for javax.naming.directory Attribute getAll
NamingEnumeration<?> getAll() throws NamingException;
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups// ww w . ja v a2 s . c o m * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsPaged(String baseURL, TSiteBean siteBean, String baseDnGroup, String ldapFilterGroups, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap) throws Exception { if (ldapFilterGroups == null || "".equals(ldapFilterGroups) || "*".equals(ldapFilterGroups)) { ldapFilterGroups = "(" + groupAttributeName + "=*)"; } String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); LdapContext context = getInitialContext(baseURL + baseDnGroup, bindDN, bindPassword); HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); if (context == null) { LOGGER.warn("Context is null"); return ldapGroupsMap; } int recordCount = 0; SearchControls ctls = null; String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { groupMemberAttributName = DEFAULT_GROUP_MEMBER; } try { // Activate paged results int pageSize = 5; byte[] cookie = null; context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle // anyways do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", ldapFilterGroups, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); return null; } TPersonBean personBean = new TPersonBean(); try { Attribute groupNameAttribute = attributes.get(groupAttributeName); if (groupNameAttribute != null) { String groupName = (String) groupNameAttribute.get(); LOGGER.debug("Groupname: " + groupName); if (groupName == null || "".equals(groupName)) { LOGGER.info("No value for group name attribute " + groupAttributeName); return null; } else { personBean.setLoginName(groupName); ldapGroupsMap.put(personBean.getLoginName(), personBean); } Attribute memberAttribute = attributes.get(groupMemberAttributName); if (memberAttribute != null) { NamingEnumeration<?> members = memberAttribute.getAll(); while (members != null && members.hasMore()) { String memberSearchResult = (String) members.next(); List<String> memberDNList = groupToMemberReferencesMap.get(groupName); if (memberDNList == null) { memberDNList = new ArrayList<String>(); groupToMemberReferencesMap.put(groupName, memberDNList); } memberDNList.add(memberSearchResult); } } else { LOGGER.info("Could not find value(s) for group member attribute " + groupMemberAttributName + " for group " + groupName); } } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName() + " " + personBean.getLastName() + ")"); } catch (Exception e) { LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage()); LOGGER.warn( "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Stack trace:", e); } } ++recordCount; } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug( "***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { context.close(); } return ldapGroupsMap; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups/*from w w w .j a v a2 s. c o m*/ * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsByList(String baseURL, TSiteBean siteBean, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap, Map<String, String> groups) throws Exception { HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { LOGGER.debug( "No groupMember attribute defined in quartz-jobs.xml. Fall back to " + DEFAULT_GROUP_MEMBER); groupMemberAttributName = DEFAULT_GROUP_MEMBER; } LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword); if (baseContext == null) { LOGGER.warn("Context is null for baseURL " + baseURL); return ldapGroupsMap; } for (Map.Entry<String, String> groupEntry : groups.entrySet()) { String groupName = groupEntry.getKey(); String groupDN = groupEntry.getValue(); int index = groupDN.indexOf(","); if (index != -1) { String searchPart = groupDN.substring(0, index); String searchStr = "(" + searchPart + ")"; String parentDNPart = groupDN.substring(index + 1); LdapContext context = (LdapContext) baseContext.lookup(parentDNPart); if (context == null) { LOGGER.warn("Context is null after lookup for " + parentDNPart); continue; } int recordCount = 0; SearchControls ctls = null; try { // Activate paged results int pageSize = 5; byte[] cookie = null; context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can // handle anyways do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", searchStr, ctls); /* * for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); continue; } TPersonBean personBean = new TPersonBean(); try { personBean.setLoginName(groupName); ldapGroupsMap.put(personBean.getLoginName(), personBean); Attribute memberAttribute = attributes.get(groupMemberAttributName); if (memberAttribute != null) { NamingEnumeration<?> members = memberAttribute.getAll(); while (members != null && members.hasMore()) { String memberSearchResult = (String) members.next(); List<String> memberDNList = groupToMemberReferencesMap.get(groupName); if (memberDNList == null) { memberDNList = new ArrayList<String>(); groupToMemberReferencesMap.put(groupName, memberDNList); } LOGGER.debug("Member found: " + memberSearchResult); memberDNList.add(memberSearchResult); } } else { LOGGER.info("Could not find value(s) for group member attribute " + groupMemberAttributName + " for group " + groupName); } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed group " + groupName); } catch (Exception e) { LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage()); LOGGER.warn( "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Stack trace:", e); } } ++recordCount; } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug("***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { context.close(); } } } return ldapGroupsMap; }
From source file:ca.tnt.ldaputils.impl.LdapEntry.java
public List getAttributeValues(final String attribute) { final Attribute ldapAttribute; List values = null;/*from ww w . j a v a 2 s. com*/ ldapAttribute = attributes.get(attribute); try { if (ldapAttribute != null && ldapAttribute.size() != 0) { values = Collections.list(ldapAttribute.getAll()); } } catch (NamingException e) { throw new LdapNamingException(e); } return values; }
From source file:ddf.security.sts.SecurityAttributesClaimsHandler.java
private Claim buildClaim(ClaimsParameters parameters, Entry<String, String> claimAttr, Attribute attr) throws URISyntaxException { Claim c = new Claim(); c.setClaimType(new URI(claimAttr.getKey())); c.setPrincipal(parameters.getPrincipal()); StringBuilder claimValue = new StringBuilder(); try {/*from www . j a v a2 s . c om*/ NamingEnumeration<?> list = (NamingEnumeration<?>) attr.getAll(); while (list.hasMore()) { Object obj = list.next(); if (!(obj instanceof String)) { LOGGER.warn("LDAP attribute '{}' has an unsupported value type", claimAttr.getValue()); break; } claimValue.append((String) obj); if (list.hasMore()) { claimValue.append(ATTRIBUTE_DELIMITER); } } } catch (NamingException ex) { LOGGER.warn("Failed to read value of LDAP attribute '{}'", claimAttr.getValue()); } c.setValue(claimValue.toString()); return c; }
From source file:org.wso2.carbon.connector.ldap.SearchEntry.java
private OMElement prepareNode(SearchResult entityResult, OMFactory factory, OMNamespace ns, String returnAttributes[]) throws NamingException { Attributes attributes = entityResult.getAttributes(); Attribute attribute; OMElement entry = factory.createOMElement(LDAPConstants.ENTRY, ns); OMElement dnattr = factory.createOMElement(LDAPConstants.DN, ns); dnattr.setText(entityResult.getNameInNamespace()); entry.addChild(dnattr);/*from ww w . j a va 2 s . c o m*/ for (int i = 0; i < returnAttributes.length; i++) { attribute = attributes.get(returnAttributes[i]); if (attribute != null) { NamingEnumeration ne = null; ne = attribute.getAll(); while (ne.hasMoreElements()) { String value = (String) ne.next(); OMElement attr = factory.createOMElement(returnAttributes[i], ns); attr.setText(value); entry.addChild(attr); } } } return entry; }
From source file:com.openkm.principal.LdapPrincipalAdapter.java
@SuppressWarnings("unchecked") private List<String> ldapSearch(List<String> searchBases, String searchFilter, String attribute) { log.debug("ldapSearch({}, {}, {})", new Object[] { searchBases, searchFilter, attribute }); List<String> al = new ArrayList<String>(); DirContext ctx = null;/*from w ww . j ava2s .com*/ Hashtable<String, String> env = getEnvironment(); try { ctx = new InitialDirContext(env); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); for (String searchBase : searchBases) { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchCtls); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); if (attribute.equals("")) { StringBuilder sb = new StringBuilder(); for (NamingEnumeration<?> ne = attributes.getAll(); ne.hasMore();) { Attribute attr = (Attribute) ne.nextElement(); sb.append(attr.toString()); sb.append("\n"); } al.add(sb.toString()); } else { Attribute attrib = attributes.get(attribute); if (attrib != null) { // Handle multi-value attributes for (NamingEnumeration<?> ne = attrib.getAll(); ne.hasMore();) { String value = (String) ne.nextElement(); // If FQDN get only main part if (value.startsWith("CN=") || value.startsWith("cn=")) { String cn = value.substring(3, value.indexOf(',')); log.debug("FQDN: {}, CN: {}", value, cn); al.add(cn); } else { al.add(value); } } } } } } } catch (ReferralException e) { log.error("ReferralException: {}", e.getMessage()); log.error("ReferralInfo: {}", e.getReferralInfo()); log.error("ResolvedObj: {}", e.getResolvedObj()); try { log.error("ReferralContext: {}", e.getReferralContext()); } catch (NamingException e1) { log.error("NamingException logging context: {}", e1.getMessage()); } } catch (NamingException e) { log.error("NamingException: {} (Base: {} - Filter: {} - Attribute: {})", new Object[] { e.getMessage(), searchBases, searchFilter, attribute }); } finally { try { if (ctx != null) { ctx.close(); } } catch (NamingException e) { log.error("NamingException closing context: {}", e.getMessage()); } } log.debug("ldapSearch: {}", al); return al; }
From source file:org.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java
/** * {@inheritDoc}/*w w w. jav a 2 s . c o m*/ */ public void logSearchResultEntry(Connection connection, StudioSearchResult studioSearchResult, long requestNum, NamingException ex) { if (!isSearchResultEntryLogEnabled()) { return; } try { String formattedString; if (studioSearchResult != null) { String dn = studioSearchResult.getNameInNamespace(); Attributes attributes = studioSearchResult.getAttributes(); LdifContentRecord record = new LdifContentRecord(LdifDnLine.create(dn)); NamingEnumeration<? extends Attribute> attributeEnumeration = attributes.getAll(); while (attributeEnumeration.hasMore()) { Attribute attribute = attributeEnumeration.next(); String attributeName = attribute.getID(); NamingEnumeration<?> valueEnumeration = attribute.getAll(); while (valueEnumeration.hasMore()) { Object o = valueEnumeration.next(); if (o instanceof String) { record.addAttrVal(LdifAttrValLine.create(attributeName, (String) o)); } if (o instanceof byte[]) { record.addAttrVal(LdifAttrValLine.create(attributeName, (byte[]) o)); } } } record.finish(LdifSepLine.create()); formattedString = record.toFormattedString(LdifFormatParameters.DEFAULT); } else { formattedString = LdifFormatParameters.DEFAULT.getLineSeparator(); } log(formattedString, "SEARCH RESULT ENTRY (" + requestNum + ")", ex, connection); //$NON-NLS-1$ //$NON-NLS-2$ } catch (NamingException e) { } }
From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java
public Map<String, Collection<String>> findUsersWithRoles(DirContext dirContext) throws LdapControllerException { Map<String, Collection<String>> usersWithRoles = new HashMap<String, Collection<String>>(); NamingEnumeration<SearchResult> namingEnumeration = null; try {/*w ww . ja v a 2s.c o m*/ SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = dirContext.search(getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); String groupName = searchResult.getName(); // cn=blabla we only want bla bla groupName = StringUtils.substringAfter(groupName, "="); Attribute uniqueMemberAttr = searchResult.getAttributes().get("uniquemember"); if (uniqueMemberAttr != null) { NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr .getAll(); while (allMembersEnum.hasMore()) { String userName = allMembersEnum.next(); // uid=blabla we only want bla bla userName = StringUtils.substringAfter(userName, "="); userName = StringUtils.substringBefore(userName, ","); Collection<String> roles = usersWithRoles.get(userName); if (roles == null) { roles = new HashSet<String>(); } roles.add(groupName); usersWithRoles.put(userName, roles); } } log.debug("found groupName: '{}' with users: {}", groupName); } return usersWithRoles; } catch (NamingException e) { throw new LdapControllerException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java
/** * Loads attributes for the argument subject. * @param subject /*from www .j a v a 2 s . c o m*/ * @return the map */ protected Map loadAttributes(SubjectImpl subject) { Map<String, Set<String>> attributes1 = new HashMap<String, Set<String>>(); Search search = getSearch("searchSubject"); if (search == null) { log.error("searchType: \"search\" not defined."); return attributes1; } //setting attributeNames to null will cause all attributes for a subject to be returned String[] attributeNames = null; Set attributeNameSet = this.getAttributes(); if (attributeNameSet.size() == 0) { attributeNames = null; } else { attributeNames = new String[attributeNameSet.size()]; int i = 0; for (Iterator it = attributeNameSet.iterator(); it.hasNext(); attributeNames[i++] = (String) it.next()) ; } try { Attributes ldapAttributes = getLdapUnique(search, subject.getId(), attributeNames); for (NamingEnumeration e = ldapAttributes.getAll(); e.hasMore();) { Attribute attr = (Attribute) e.next(); String name1 = attr.getID(); Set<String> values = new HashSet<String>(); for (NamingEnumeration en = attr.getAll(); en.hasMore();) { Object value = en.next(); values.add(value.toString()); } attributes1.put(name1, values); } subject.setAttributes(attributes1); } catch (SubjectNotFoundException ex) { log.error("SubjectNotFound: " + subject.getId() + " " + ex.getMessage(), ex); } catch (SubjectNotUniqueException ex) { log.error("SubjectNotUnique: " + subject.getId() + " " + ex.getMessage(), ex); } catch (NamingException ex) { log.error("LDAP Naming Except: " + ex.getMessage(), ex); } return attributes1; }
From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java
private void execute() throws Exception { // Connecting to server and retreiving entries NamingEnumeration entries = connectToServerAndGetEntries(); // Creating destination file File destionationFile = new File(ldifFileName); // Deleting the destination file if it already exists if (destionationFile.exists()) { destionationFile.delete();/*from w ww . j a va2s . co m*/ } // Creating the writer to generate the LDIF file FileWriter fw = new FileWriter(ldifFileName, true); BufferedWriter writer = new BufferedWriter(fw); OtcLdifComposerImpl composer = new OtcLdifComposerImpl(); MultiValueMap map = new MultiValueMap(); // MultiMap map = new MultiMap() { // // FIXME Stop forking commons-collections. // private final MultiValueMap map = new MultiValueMap(); // // public Object remove(Object arg0, Object arg1) { // return map.remove(arg0, arg1); // } // // public int size() { // return map.size(); // } // // public Object get(Object arg0) { // return map.get(arg0); // } // // public boolean containsValue(Object arg0) { // return map.containsValue(arg0); // } // // public Object put(Object arg0, Object arg1) { // return map.put(arg0, arg1); // } // // public Object remove(Object arg0) { // return map.remove(arg0); // } // // public Collection values() { // return map.values(); // } // // public boolean isEmpty() { // return map.isEmpty(); // } // // public boolean containsKey(Object key) { // return map.containsKey(key); // } // // public void putAll(Map arg0) { // map.putAll(arg0); // } // // public void clear() { // map.clear(); // } // // public Set keySet() { // return map.keySet(); // } // // public Set entrySet() { // return map.entrySet(); // } // }; int entriesCounter = 1; long t0 = System.currentTimeMillis(); while (entries.hasMoreElements()) { SearchResult sr = (SearchResult) entries.nextElement(); Attributes attributes = sr.getAttributes(); NamingEnumeration attributesEnumeration = attributes.getAll(); map.clear(); while (attributesEnumeration.hasMoreElements()) { Attribute attr = (Attribute) attributesEnumeration.nextElement(); NamingEnumeration e2 = null; e2 = attr.getAll(); while (e2.hasMoreElements()) { Object value = e2.nextElement(); map.put(attr.getID(), value); } } // Writing entry in the file writer.write("dn: " + sr.getNameInNamespace() + "\n"); writer.write(composer.compose(map) + "\n"); notifyEntryWrittenListener(sr.getNameInNamespace()); entriesCounter++; if (entriesCounter % 10 == 0) { notifyOutputListener(new Character('.')); } if (entriesCounter % 500 == 0) { notifyOutputListener("" + entriesCounter); } } writer.flush(); writer.close(); fw.close(); long t1 = System.currentTimeMillis(); notifyOutputListener("Done!"); notifyOutputListener(entriesCounter + " entries exported in " + ((t1 - t0) / 1000) + " seconds"); }