List of usage examples for javax.naming.directory Attribute getAll
NamingEnumeration<?> getAll() throws NamingException;
From source file:org.swordess.ldap.odm.core.SessionImpl.java
private Map<String, Object> fromAttributesToMap(Class<?> clazz, Attributes attributes) throws NamingException { try {//from w w w.j av a2 s .c o m Map<String, Object> map = new HashMap<String, Object>(); EntityMetaData metaData = EntityMetaData.get(clazz); for (NamingEnumeration<? extends Attribute> attrs = attributes.getAll(); attrs.hasMore();) { Attribute attr = attrs.next(); EntityPropertyMetaData propMetaData = metaData.getProperty(attr.getID()); if (null == propMetaData) { continue; } List<String> attrValues = new ArrayList<String>(); for (NamingEnumeration<?> all = attr.getAll(); all.hasMore();) { attrValues.add(propMetaData.getSyntaxer().ldapStringToJavaString(all.next().toString())); } if (!propMetaData.isMultiple()) { map.put(attr.getID(), attrValues.get(0)); } else { map.put(attr.getID(), attrValues); } } return map; } catch (NamingException e) { LogUtils.debug(LOG, "failed to go through attributes when fromAttributesToMap"); throw e; } }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void getUsers(UserGroupSink sink) throws Throwable { NamingEnumeration<SearchResult> userSearchResultEnum = null; NamingEnumeration<SearchResult> groupSearchResultEnum = null; try {/* ww w .j a va 2s . c o m*/ createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); extendedUserSearchFilter = "(objectclass=" + userObjectClass + ")(|(uSNChanged>=" + deltaSyncUserTime + ")(modifyTimestamp>=" + deltaSyncUserTimeStamp + "Z))"; if (userSearchFilter != null && !userSearchFilter.trim().isEmpty()) { String customFilter = userSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } extendedUserSearchFilter = "(&" + extendedUserSearchFilter + customFilter + ")"; } else { extendedUserSearchFilter = "(&" + extendedUserSearchFilter + ")"; } LOG.info("extendedUserSearchFilter = " + extendedUserSearchFilter); long highestdeltaSyncUserTime = deltaSyncUserTime; // When multiple OUs are configured, go through each OU as the user search base to search for users. for (int ou = 0; ou < userSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { int paged = 0; do { userSearchResultEnum = ldapContext.search(userSearchBase[ou], extendedUserSearchFilter, userSearchControls); while (userSearchResultEnum.hasMore()) { // searchResults contains all the user entries final SearchResult userEntry = userSearchResultEnum.next(); if (userEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("userEntry null, skipping sync for the entry"); } continue; } //System.out.println("userEntry = " + userEntry); Attributes attributes = userEntry.getAttributes(); if (attributes == null) { if (LOG.isInfoEnabled()) { LOG.info("attributes missing for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } Attribute userNameAttr = attributes.get(userNameAttribute); if (userNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(userNameAttribute + " missing for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } String userFullName = (userEntry.getNameInNamespace()).toLowerCase(); String userName = (String) userNameAttr.get(); if (userName == null || userName.trim().isEmpty()) { if (LOG.isInfoEnabled()) { LOG.info(userNameAttribute + " empty for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } Attribute timeStampAttr = attributes.get("uSNChanged"); if (timeStampAttr != null) { String uSNChangedVal = (String) timeStampAttr.get(); long currentDeltaSyncTime = Long.parseLong(uSNChangedVal); LOG.info("uSNChangedVal = " + uSNChangedVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncUserTime) { highestdeltaSyncUserTime = currentDeltaSyncTime; } } else { timeStampAttr = attributes.get("modifytimestamp"); if (timeStampAttr != null) { String timeStampVal = (String) timeStampAttr.get(); Date parseDate = dateFormat.parse(timeStampVal); long currentDeltaSyncTime = parseDate.getTime(); LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncUserTime) { highestdeltaSyncUserTime = currentDeltaSyncTime; deltaSyncUserTimeStamp = timeStampVal; } } } if (!groupSearchFirstEnabled) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } //System.out.println("Adding user fullname = " + userFullName + " username = " + transformUserName); userNameMap.put(userFullName, transformUserName); Set<String> groups = new HashSet<String>(); // Get all the groups from the group name attribute of the user only when group search is not enabled. if (!groupSearchEnabled) { for (String useGroupNameAttribute : userGroupNameAttributeSet) { Attribute userGroupfAttribute = userEntry.getAttributes() .get(useGroupNameAttribute); if (userGroupfAttribute != null) { NamingEnumeration<?> groupEnum = userGroupfAttribute.getAll(); while (groupEnum.hasMore()) { String gName = getShortGroupName((String) groupEnum.next()); String transformGroupName = groupNameTransform(gName); groups.add(transformGroupName); } } } } List<String> groupList = new ArrayList<String>(groups); try { sink.addOrUpdateUser(transformUserName, groupList); } catch (Throwable t) { LOG.error("sink.addOrUpdateUserGroups failed with exception: " + t.getMessage() + ", for user: " + transformUserName + " and groups: " + groupList); } counter++; if (counter <= 2000) { if (LOG.isInfoEnabled()) { LOG.info("Updating user count: " + counter + ", userName: " + userName + ", groupList: " + groupList); } if (counter == 2000) { LOG.info( "===> 2000 user records have been synchronized so far. From now on, only a summary progress log will be written for every 100 users. To continue to see detailed log for every user, please enable Trace level logging. <==="); } } else { if (LOG.isTraceEnabled()) { LOG.trace("Updating user count: " + counter + ", userName: " + userName + ", groupList: " + groupList); } else { if (counter % 100 == 0) { LOG.info("Synced " + counter + " users till now"); } } } } else { // If the user from the search result is present in the group user table, // then addorupdate user to ranger admin. LOG.debug("Chekcing if the user " + userFullName + " is part of the retrieved groups"); if (groupUserTable.containsColumn(userFullName) || groupUserTable.containsColumn(userName)) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } userNameMap.put(userFullName, transformUserName); //Also update the username in the groupUserTable with the one from username attribute. Map<String, String> userMap = groupUserTable.column(userFullName); for (Map.Entry<String, String> entry : userMap.entrySet()) { LOG.debug("Updating groupUserTable " + entry.getValue() + " with: " + transformUserName + " for " + entry.getKey()); groupUserTable.put(entry.getKey(), userFullName, transformUserName); } } } } // Examine the paged results control response Control[] controls = ldapContext.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) { LOG.debug("END-OF-PAGE total : " + total); } else { LOG.debug("END-OF-PAGE total : unknown"); } cookie = prrc.getCookie(); } } } else { LOG.debug("No controls were sent from the server"); } // Re-activate paged results if (pagedResultsEnabled) { LOG.debug(String.format("Fetched paged results round: %s", ++paged)); ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) }); } } while (cookie != null); LOG.info("LdapDeltaUserGroupBuilder.getUsers() completed with user count: " + counter); } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.getUsers() failed with exception: " + t); LOG.info("LdapDeltaUserGroupBuilder.getUsers() user count: " + counter); } } if (deltaSyncUserTime < highestdeltaSyncUserTime) { // Incrementing highestdeltaSyncUserTime (for AD) in order to avoid search record repetition for next sync cycle. deltaSyncUserTime = highestdeltaSyncUserTime + 1; // Incrementing the highest timestamp value (for Openldap) with 1sec in order to avoid search record repetition for next sync cycle. deltaSyncUserTimeStamp = dateFormat.format(new Date(highestdeltaSyncUserTime + 60l)); } } finally { if (userSearchResultEnum != null) { userSearchResultEnum.close(); } if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void goUpGroupHierarchyLdap(Set<String> groupDNs, int groupHierarchyLevels) throws Throwable { if (groupHierarchyLevels <= 0 || groupDNs.isEmpty()) { return;//from ww w . ja v a 2s. c o m } Set<String> nextLevelGroups = new HashSet<String>(); NamingEnumeration<SearchResult> groupSearchResultEnum = null; try { createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } String groupFilter = "(&(objectclass=" + groupObjectClass + ")"; if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) { String customFilter = groupSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } groupFilter += customFilter + "(|"; } StringBuilder filter = new StringBuilder(); for (String groupDN : groupDNs) { filter.append("(").append(groupMemberAttributeName).append("=").append(groupDN).append(")"); } filter.append("))"); groupFilter += filter; LOG.info("extendedAllGroupsSearchFilter = " + groupFilter); for (int ou = 0; ou < groupSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { do { groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], groupFilter, groupSearchControls); while (groupSearchResultEnum.hasMore()) { final SearchResult groupEntry = groupSearchResultEnum.next(); if (groupEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("groupEntry null, skipping sync for the entry"); } continue; } counter++; Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute); if (groupNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(groupNameAttribute + " empty for entry " + groupEntry.getNameInNamespace() + ", skipping sync"); } continue; } nextLevelGroups.add(groupEntry.getNameInNamespace()); String gName = (String) groupNameAttr.get(); Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName); int userCount = 0; if (groupMemberAttr == null || groupMemberAttr.size() <= 0) { LOG.info("No members available for " + gName); continue; } NamingEnumeration<?> userEnum = groupMemberAttr.getAll(); while (userEnum.hasMore()) { String originalUserFullName = (String) userEnum.next(); if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) { continue; } userCount++; originalUserFullName = originalUserFullName.toLowerCase(); if (userNameMap.get(originalUserFullName) != null) { groupUserTable.put(gName, originalUserFullName, userNameMap.get(originalUserFullName)); } else { groupUserTable.put(gName, originalUserFullName, originalUserFullName); } groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName); } LOG.info("No. of members in the group " + gName + " = " + userCount); } // Examine the paged results control response Control[] controls = ldapContext.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) { LOG.debug("END-OF-PAGE total : " + total); } else { LOG.debug("END-OF-PAGE total : unknown"); } cookie = prrc.getCookie(); } } } else { LOG.debug("No controls were sent from the server"); } // Re-activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) }); } } while (cookie != null); LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() completed with group count: " + counter); } catch (RuntimeException re) { LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with runtime exception: ", re); throw re; } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", t); LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() group count: " + counter); } } } catch (RuntimeException re) { LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", re); throw re; } finally { if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } goUpGroupHierarchyLdap(nextLevelGroups, groupHierarchyLevels - 1); }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) { Object[] filterArguments = { _roleObjectClass }; SearchControls ctls = new SearchControls(); ctls.setDerefLinkFlag(true);/*from w ww.ja v a 2s.co m*/ ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>(); try { NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls); while (results.hasMoreElements()) { SearchResult result = results.nextElement(); Attributes attributes = result.getAttributes(); if (attributes == null) { continue; } Attribute roleAttribute = attributes.get(_roleNameAttribute); Attribute memberAttribute = attributes.get(_roleMemberAttribute); if (roleAttribute == null || memberAttribute == null) { continue; } NamingEnumeration role = roleAttribute.getAll(); NamingEnumeration members = memberAttribute.getAll(); if (!role.hasMore() || !members.hasMore()) { continue; } String roleName = (String) role.next(); if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) { roleName = roleName.replace(_rolePrefix, ""); } while (members.hasMore()) { String member = (String) members.next(); Matcher roleMatcher = rolePattern.matcher(member); if (!roleMatcher.find()) { continue; } String roleMember = roleMatcher.group(1); List<String> memberOf; if (roleMemberOfMap.containsKey(roleMember)) { memberOf = roleMemberOfMap.get(roleMember); } else { memberOf = new ArrayList<String>(); } memberOf.add(roleName); roleMemberOfMap.put(roleMember, memberOf); } } } catch (NamingException e) { e.printStackTrace(); } return roleMemberOfMap; }
From source file:com.surevine.ldap2alfresco.ProfileFieldTelephoneConverter.java
/** * Encode some attributes as JSON./*from w w w . j a va2s.c om*/ * @param json The JSON object to insert into * @param attributes Collection of attributes */ public void toJson(final JSONObject json, final Attributes attributes) { Attribute attribute = attributes.get(attributeLabel); if (attribute == null) { LOGGER.debug("Missing attribute: " + attributeLabel); // just put an empty entry into the JSON try { if (allowMultiples) { json.put(jsonLabel, new JSONArray()); } else { JSONObject blank = new JSONObject(); blank.put(JSON_LABEL_NETWORK, ""); blank.put(JSON_LABEL_NUMBER, ""); blank.put(JSON_LABEL_EXTENSION, ""); json.put(jsonLabel, blank); } } catch (JSONException e) { logException(Level.ERROR, e); } return; } int numValues = attribute.size(); if (numValues == 0) { LOGGER.error("Attribute " + attributeLabel + " contains no values"); return; } try { if (allowMultiples) { JSONArray values = new JSONArray(); NamingEnumeration<?> valueEnum = attribute.getAll(); while (valueEnum.hasMore()) { String value = valueEnum.next().toString(); JSONObject entry = decodePhoneNumber(value); if (entry == null) { LOGGER.error("Failed to parse telephone number from :" + value); } else { values.put(entry); } } json.put(jsonLabel, values); } else { // expecting only one value if (numValues != 1) { LOGGER.error("Expected single value in attribute " + attributeLabel + ", found " + numValues); return; } String value = attribute.get().toString(); JSONObject entry = decodePhoneNumber(value); if (entry == null) { LOGGER.error("Failed to parse telephone fields from :" + value); } else { json.put(jsonLabel, entry); } } } catch (NamingException e) { logException(Level.ERROR, e); return; } catch (JSONException e) { logException(Level.ERROR, e); return; } }
From source file:org.lsc.jndi.JndiServices.java
/** * Retrieve a specific attribute from an object * /* ww w.j a va 2 s .c o m*/ * @param objectDn * @param attribute * @return * @throws LscServiceException */ public List<String> getAttributeValues(String objectDn, String attribute) throws LscServiceException { List<String> values = null; try { // Setup search SearchControls sc = new SearchControls(); sc.setDerefLinkFlag(false); sc.setReturningAttributes(new String[] { attribute }); sc.setSearchScope(SearchControls.OBJECT_SCOPE); sc.setReturningObjFlag(true); // Retrieve attribute values SearchResult res = getEntry(objectDn, "objectClass=*", sc, SearchControls.OBJECT_SCOPE); Attribute attr = res.getAttributes().get(attribute); if (attr != null) { values = new ArrayList<String>(); NamingEnumeration<?> enu = attr.getAll(); while (enu.hasMoreElements()) { Object val = enu.next(); values.add(val.toString()); } } } catch (NamingException e) { throw new LscServiceException(e); } return values; }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
/** * Does a case-insensitive search for the given value in an attribute. * * @param attribute// www. ja v a 2 s. c o m * the attribute * @param value * the value to search for * @return <code>true</code>, if the value was found * @throws NamingException * if there is a problem accessing the attribute values */ protected boolean hasAttributeValue(final Attribute attribute, final String value) throws NamingException { if (attribute != null) { final NamingEnumeration<?> values = attribute.getAll(); while (values.hasMore()) { final Object mappedValue = this.mapAttributeValue(attribute.getID(), values.next()); if (mappedValue instanceof String && value.equalsIgnoreCase((String) mappedValue)) { return true; } } } return false; }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void getGroups(UserGroupSink sink) throws Throwable { NamingEnumeration<SearchResult> groupSearchResultEnum = null; DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); long highestdeltaSyncGroupTime = deltaSyncGroupTime; try {// w w w . j av a 2s. com createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } extendedGroupSearchFilter = "(objectclass=" + groupObjectClass + ")"; if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) { String customFilter = groupSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } extendedGroupSearchFilter = extendedGroupSearchFilter + customFilter; } extendedAllGroupsSearchFilter = "(&" + extendedGroupSearchFilter + "(|(uSNChanged>=" + deltaSyncGroupTime + ")(modifyTimestamp>=" + deltaSyncGroupTimeStamp + "Z)))"; LOG.info("extendedAllGroupsSearchFilter = " + extendedAllGroupsSearchFilter); for (int ou = 0; ou < groupSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { int paged = 0; do { groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], extendedAllGroupsSearchFilter, groupSearchControls); while (groupSearchResultEnum.hasMore()) { final SearchResult groupEntry = groupSearchResultEnum.next(); if (groupEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("groupEntry null, skipping sync for the entry"); } continue; } counter++; Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute); if (groupNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(groupNameAttribute + " empty for entry " + groupEntry.getNameInNamespace() + ", skipping sync"); } continue; } String gName = (String) groupNameAttr.get(); String transformGroupName = groupNameTransform(gName); // If group based search is enabled, then // update the group name to ranger admin // check for group members and populate userInfo object with user's full name and group mapping if (groupSearchFirstEnabled) { LOG.debug("Update Ranger admin with " + transformGroupName); sink.addOrUpdateGroup(transformGroupName); } Attribute timeStampAttr = groupEntry.getAttributes().get("uSNChanged"); if (timeStampAttr != null) { String uSNChangedVal = (String) timeStampAttr.get(); long currentDeltaSyncTime = Long.parseLong(uSNChangedVal); if (currentDeltaSyncTime > highestdeltaSyncGroupTime) { highestdeltaSyncGroupTime = currentDeltaSyncTime; } } else { timeStampAttr = groupEntry.getAttributes().get("modifytimestamp"); if (timeStampAttr != null) { String timeStampVal = (String) timeStampAttr.get(); Date parseDate = dateFormat.parse(timeStampVal); long currentDeltaSyncTime = parseDate.getTime(); LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncGroupTime) { highestdeltaSyncGroupTime = currentDeltaSyncTime; deltaSyncGroupTimeStamp = timeStampVal; } } } Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName); int userCount = 0; if (groupMemberAttr == null || groupMemberAttr.size() <= 0) { LOG.info("No members available for " + gName); continue; } NamingEnumeration<?> userEnum = groupMemberAttr.getAll(); while (userEnum.hasMore()) { String originalUserFullName = (String) userEnum.next(); if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) { continue; } userCount++; String userName = getShortUserName(originalUserFullName); originalUserFullName = originalUserFullName.toLowerCase(); if (groupSearchFirstEnabled && !userSearchEnabled) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } userNameMap.put(originalUserFullName, transformUserName); } //System.out.println("Adding " + userNameMap.get(originalUserFullName) + " and fullname = " + originalUserFullName + " to " + gName); if (userNameMap.get(originalUserFullName) != null) { groupUserTable.put(gName, originalUserFullName, userNameMap.get(originalUserFullName)); } else { groupUserTable.put(gName, originalUserFullName, originalUserFullName); } groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName); } LOG.info("No. of members in the group " + gName + " = " + userCount); } // Examine the paged results control response Control[] controls = ldapContext.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) { LOG.debug("END-OF-PAGE total : " + total); } else { LOG.debug("END-OF-PAGE total : unknown"); } cookie = prrc.getCookie(); } } } else { LOG.debug("No controls were sent from the server"); } // Re-activate paged results if (pagedResultsEnabled) { LOG.debug(String.format("Fetched paged results round: %s", ++paged)); ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) }); } } while (cookie != null); LOG.info("LdapDeltaUserGroupBuilder.getGroups() completed with group count: " + counter); } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.getGroups() failed with exception: " + t); LOG.info("LdapDeltaUserGroupBuilder.getGroups() group count: " + counter); } } } finally { if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } if (groupHierarchyLevels > 0) { LOG.debug("deltaSyncGroupTime = " + deltaSyncGroupTime); if (deltaSyncGroupTime > 0) { LOG.info( "LdapDeltaUserGroupBuilder.getGroups(): Going through group hierarchy for nested group evaluation for deltasync"); goUpGroupHierarchyLdap(groupNameMap.keySet(), groupHierarchyLevels - 1); } } if (deltaSyncGroupTime < highestdeltaSyncGroupTime) { // Incrementing highestdeltaSyncGroupTime (for AD) in order to avoid search record repetition for next sync cycle. deltaSyncGroupTime = highestdeltaSyncGroupTime + 1; // Incrementing the highest timestamp value (for OpenLdap) with 1min in order to avoid search record repetition for next sync cycle. deltaSyncGroupTimeStamp = dateFormat.format(new Date(highestdeltaSyncGroupTime + 60000l)); } }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Resolves all the groups that the user is in. * * We now use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms680275(v=vs.85).aspx">tokenGroups</a> * attribute, which is a computed attribute that lists all the SIDs of the groups that the user is directly/indirectly in. * We then use that to retrieve all the groups in one query and resolve their canonical names. * * @param userDN// w w w . j a v a 2 s . c om * User's distinguished name. * @param context Used for making queries. */ private Set<GrantedAuthority> resolveGroups(String domainDN, String userDN, DirContext context) throws NamingException { if (userDN.contains("/")) { userDN = userDN.replace("/", "\\/"); } Set<GrantedAuthority> groups = new HashSet<GrantedAuthority>(); LOGGER.log(Level.FINER, "Looking up group of {0}", userDN); Attributes id = context.getAttributes(userDN, new String[] { "tokenGroups", "memberOf", "CN" }); Attribute tga = id.get("tokenGroups"); if (tga == null) { // tga will be null if you are not using a global catalogue // or if the user is not actually a member of any security groups. LOGGER.log(Level.FINE, "Failed to retrieve tokenGroups for {0}", userDN); // keep on trucking as we can still use memberOf for Distribution Groups. } else { // build up the query to retrieve all the groups StringBuilder query = new StringBuilder("(|"); List<byte[]> sids = new ArrayList<byte[]>(); NamingEnumeration<?> tokenGroups = tga.getAll(); while (tokenGroups.hasMore()) { byte[] gsid = (byte[]) tokenGroups.next(); query.append("(objectSid={" + sids.size() + "})"); sids.add(gsid); } tokenGroups.close(); query.append(")"); NamingEnumeration<SearchResult> renum = new LDAPSearchBuilder(context, domainDN).subTreeScope() .returns("cn").search(query.toString(), sids.toArray()); parseMembers(userDN, groups, renum); renum.close(); } {/* stage 2: use memberOf to find groups that aren't picked up by tokenGroups. This includes distribution groups */ LOGGER.fine("Stage 2: looking up via memberOf"); while (true) { switch (groupLookupStrategy) { case TOKENGROUPS: // no extra lookup - ever. return groups; case AUTO: // try the accurate one first, and if it's too slow fall back to recursive in the hope that it's faster long start = System.nanoTime(); boolean found = false; long duration = 0; try { found = chainGroupLookup(domainDN, userDN, context, groups); duration = TimeUnit2.NANOSECONDS.toSeconds(System.nanoTime() - start); } catch (TimeLimitExceededException e) { LOGGER.log(Level.WARNING, "The LDAP request did not terminate within the specified time limit. AD will fall back to recursive lookup", e); } catch (NamingException e) { if (e.getMessage().contains("LDAP response read timed out")) { LOGGER.log(Level.WARNING, "LDAP response read time out. AD will fall back to recursive lookup", e); } else { throw e; } } if (!found && duration >= 10) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension timed out after {0} seconds. Falling back to recursive group lookup strategy for this and future queries", duration); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; continue; } else if (found && duration >= 10) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension matched user's groups but took {0} seconds to run. Switching to recursive lookup for future group lookup queries", duration); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; return groups; } else if (!found) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension failed. Falling back to recursive group lookup strategy for this and future queries"); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; continue; } else { // it run fast enough, so let's stick to it groupLookupStrategy = GroupLookupStrategy.CHAIN; return groups; } case RECURSIVE: recursiveGroupLookup(context, id, groups); return groups; case CHAIN: chainGroupLookup(domainDN, userDN, context, groups); return groups; } } } }
From source file:org.lsc.jndi.JndiServices.java
/** * Return the LDAP schema.//from ww w . j a v a 2s .c o m * * @param attrsToReturn * list of attribute names to return (or null for all * 'standard' attributes) * @return the map of name => attribute * @throws NamingException * thrown if something goes wrong (bad */ @SuppressWarnings("unchecked") public Map<String, List<String>> getSchema(final String[] attrsToReturn) throws NamingException { Map<String, List<String>> attrsResult = new HashMap<String, List<String>>(); // connect to directory Hashtable<String, String> props = (Hashtable<String, String>) ctx.getEnvironment(); String baseUrl = (String) props.get(Context.PROVIDER_URL); baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/')); props.put(Context.PROVIDER_URL, baseUrl); DirContext schemaCtx = new InitialLdapContext(props, null); // find schema entry SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.OBJECT_SCOPE); sc.setReturningAttributes(new String[] { "subschemaSubentry" }); NamingEnumeration<SearchResult> schemaDnSR = schemaCtx.search("", "(objectclass=*)", sc); SearchResult sr = null; Attribute subschemaSubentry = null; String subschemaSubentryDN = null; if (schemaDnSR.hasMore()) { sr = schemaDnSR.next(); } if (sr != null) { subschemaSubentry = sr.getAttributes().get("subschemaSubentry"); } if (subschemaSubentry != null && subschemaSubentry.size() > 0) { subschemaSubentryDN = (String) subschemaSubentry.get(); } if (subschemaSubentryDN != null) { // get schema attributes from subschemaSubentryDN Attributes schemaAttrs = schemaCtx.getAttributes(subschemaSubentryDN, attrsToReturn != null ? attrsToReturn : new String[] { "*", "+" }); if (schemaAttrs != null) { for (String attr : attrsToReturn) { Attribute schemaAttr = schemaAttrs.get(attr); if (schemaAttr != null) { attrsResult.put(schemaAttr.getID(), (List<String>) Collections.list(schemaAttr.getAll())); } } } } return attrsResult; }