List of usage examples for javax.naming.directory Attribute size
int size();
From source file:com.emc.ecs.smart.SmartUploader.java
/** * Use JNDI to bind to DNS and resolve ALL the 'A' records for a host. * @param hostname host to resolve/*from w w w . j a va 2s .c o m*/ * @return the list of IP addresses for the host. */ public List<String> getIPAddresses(String hostname) throws NamingException { InitialDirContext idc; Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); idc = new InitialDirContext(env); List<String> ipAddresses = new ArrayList<String>(); Attributes attrs = idc.getAttributes(hostname, ADDR_ATTRIBS); Attribute attr = attrs.get(ADDR_ATTRIB); if (attr != null) { for (int i = 0; i < attr.size(); i++) { ipAddresses.add((String) attr.get(i)); } } return ipAddresses; }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Performs recursive group membership lookup. * * This was how we did the lookup traditionally until we discovered 1.2.840.113556.1.4.1941. * But various people reported that it slows down the execution tremendously to the point that it is unusable, * while others seem to report that it runs faster than recursive search (http://social.technet.microsoft.com/Forums/fr-FR/f238d2b0-a1d7-48e8-8a60-542e7ccfa2e8/recursive-retrieval-of-all-ad-group-memberships-of-a-user?forum=ITCG) * * This implementation is kept for Windows 2003 that doesn't support 1.2.840.113556.1.4.1941, but it can be also * enabled for those who are seeing the performance problem. * * See JENKINS-22830/*from w w w . j av a 2 s .c o m*/ */ private void recursiveGroupLookup(DirContext context, Attributes id, Set<GrantedAuthority> groups) throws NamingException { Stack<Attributes> q = new Stack<Attributes>(); q.push(id); while (!q.isEmpty()) { Attributes identity = q.pop(); LOGGER.finer("Looking up group of " + identity); Attribute memberOf = identity.get("memberOf"); if (memberOf == null) continue; for (int i = 0; i < memberOf.size(); i++) { try { LOGGER.log(Level.FINE, "Trying to get the CN of {0}", memberOf.get(i)); Attributes group = context.getAttributes(new LdapName(memberOf.get(i).toString()), new String[] { "CN", "memberOf" }); Attribute cn = group.get("CN"); if (cn == null) { LOGGER.fine("Failed to obtain CN of " + memberOf.get(i)); continue; } if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(cn.get() + " is a member of " + memberOf.get(i)); if (groups.add(new GrantedAuthorityImpl(cn.get().toString()))) { q.add(group); // recursively look for groups that this group is a member of. } } catch (NameNotFoundException e) { LOGGER.fine("Failed to obtain CN of " + memberOf.get(i)); } } } }
From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java
private void setMethods(T instance, Attributes attrs) throws LdapMappingException { for (Method method : getAnnotatedSetMethods()) { String attrID = method.getAnnotation(LdapAttribute.class).id(); if (!method.getAnnotation(LdapAttribute.class).oneWayEncrypted() || !ENCRYPTION_ALGORITHM.equals(method.getAnnotation(LdapAttribute.class).encrypted())) { Attribute attr = attrs.get(attrID); Class<?> type = method.getParameterTypes()[0]; Object value = null;//from ww w . j a va2 s.c o m Class valueTranslatorClass = method.getAnnotation(LdapAttribute.class).valueTranslator(); try { if (attr != null) { method.setAccessible(true); for (int i = 0; i < attr.size(); i++) { Object o = attr.get(i); // are not all attribute values Strings? value = getSingleValue(type, o); if (value != null) { LdapAttributeValueTranslator valueTranslator = getValueTranslator( valueTranslatorClass); value = valueTranslator.fromLdap(value); method.invoke(instance, value); } } } } catch (IllegalArgumentException e) { final String msg = "Expected " + type + " but was " + value; logger.error(msg); throw new LdapMappingException(msg, e); } catch (NamingException e) { throw new LdapMappingException(e); } catch (IllegalAccessException e) { throw new LdapMappingException(e); } catch (InvocationTargetException e) { final String msg = "Method threw exception: "; logger.error(msg, e); throw new LdapMappingException(msg, e); } catch (IndexOutOfBoundsException e) { final String msg = "Setter method has no argument: "; logger.error(msg, e); throw new LdapMappingException(msg, e); } catch (InstantiationException e) { final String msg = "Could not instantiate attribute value translator: "; logger.error(msg, e); throw new LdapMappingException(msg, e); } } } }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java
private String[] getParents(Attributes attributes) throws NamingException { List<String> parents = new ArrayList<String>(); Attribute memberOfAttribute = attributes.get(MEMBER_OF_ATTIBUTE); if (memberOfAttribute != null) { final PagedResultTemplate pagedResultTemplate = configuration.getPagedResultTemplate(); for (int index = 0; index < memberOfAttribute.size(); index++) { String parentDn = (String) memberOfAttribute.get(index); if (pagedResultTemplate.isDnValid(parentDn)) { parents.add(parentDn); // valid parent so record }/* w ww . java 2 s. co m*/ } } return parents.toArray(new String[parents.size()]); }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Obtains the roles for the given user. * * @param username the user name to fetch user data. * @return the list of roles to which the user is associated to. * @throws NamingException LDAP error obtaining roles fro the given user *///from ww w . jav a2s . co m protected String[] selectRolesByUsername(String username) throws NamingException, NoSuchUserException { List userRoles = new ArrayList(); InitialLdapContext ctx = createLdapInitialContext(); String rolesCtxDN = getRolesCtxDN(); // Search for any roles associated with the user if (rolesCtxDN != null) { // The attribute where user DN is stored in roles : String uidAttributeID = getUidAttributeID(); if (uidAttributeID == null) uidAttributeID = "uniquemember"; // The attribute that identifies the role name String roleAttrName = getRoleAttributeID(); if (roleAttrName == null) roleAttrName = "roles"; String userDN; if ("UID".equals(getRoleMatchingMode())) { // Use User ID to match the role userDN = username; } else if ("PRINCIPAL".equals(getRoleMatchingMode())) { // Use User ID to match the role userDN = _principalUidAttributeID + "=" + username; } else { // Default behaviour: Match the role using the User DN, not just the username : userDN = selectUserDN(username); } if (logger.isDebugEnabled()) logger.debug( "Searching Roles for user '" + userDN + "' in Uid attribute name '" + uidAttributeID + "'"); if (userDN == null) throw new NoSuchUserException(username); try { if (userDN.contains("\\")) { logger.debug("Escaping '\\' character"); userDN = userDN.replace("\\", "\\\\\\"); } NamingEnumeration answer = ctx.search(rolesCtxDN, "(&(" + uidAttributeID + "=" + userDN + "))", getSearchControls()); if (logger.isDebugEnabled()) logger.debug("Search Name: " + rolesCtxDN); if (logger.isDebugEnabled()) logger.debug("Search Filter: (&(" + uidAttributeID + "=" + userDN + "))"); if (!answer.hasMore()) logger.info("No roles found for user " + username); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute roles = attrs.get(roleAttrName); for (int r = 0; r < roles.size(); r++) { Object value = roles.get(r); String roleName = null; // The role attribute value is the role name roleName = value.toString(); if (roleName != null) { if (logger.isDebugEnabled()) logger.debug("Saving role '" + roleName + "' for user '" + username + "'"); userRoles.add(roleName); } } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate roles", e); } } // Close the context to release the connection ctx.close(); return (String[]) userRoles.toArray(new String[userRoles.size()]); }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java
private Collection<ActiveDirectoryGroup> getUsersGroups(Attributes attributes) throws NamingException { Attribute memberOfAttribute = attributes.get(MEMBER_OF_ATTIBUTE); if (memberOfAttribute == null) { return Collections.<ActiveDirectoryGroup>emptyList(); }// w w w.j a v a2 s .co m Collection<ActiveDirectoryGroup> groups = new ArrayList<ActiveDirectoryGroup>(); for (int index = 0; index < memberOfAttribute.size(); index++) { String groupDn = (String) memberOfAttribute.get(index); groups.addAll(getGroupsByDn(groupDn)); } return groups; }
From source file:com.surevine.ldap2alfresco.ProfileFieldTelephoneConverter.java
/** * Encode some attributes as JSON.// www.ja va 2 s . c o m * @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.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void goUpGroupHierarchyLdap(Set<String> groupDNs, int groupHierarchyLevels) throws Throwable { if (groupHierarchyLevels <= 0 || groupDNs.isEmpty()) { return;/*from w w w . j a v a 2 s . com*/ } 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:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
private boolean checkAttributeEnum( //List<Enum<?>> pOrgAtt, List<Enum<?>> pOldOrgAtt, String ldapAttributeName, List<ConstEnumOrgSubSector> pOrgAtt, List<ConstEnumOrgSubSector> pOldOrgAtt, String ldapAttributeName, Attributes vOrgAttributes, Attributes vOrgRemoveAttributes, boolean isUpdate) { boolean hasChanged = false; if (!isUpdate) { // is create if ((pOrgAtt != null) && (!pOrgAtt.isEmpty())) { Attribute vAttr = new BasicAttribute(ldapAttributeName); for (Enum<?> iterEnum : pOrgAtt) { if (iterEnum != null) { vAttr.add(iterEnum.name()); }/*from w w w. ja v a 2 s.co m*/ } if (vAttr.size() > 0) { vOrgAttributes.put(vAttr); } } } else { if ((pOrgAtt != null) && (!pOrgAtt.isEmpty())) { Attribute vAttr = new BasicAttribute(ldapAttributeName); if ((pOrgAtt.isEmpty()) && (pOldOrgAtt != null) && (!pOldOrgAtt.isEmpty())) { vOrgRemoveAttributes.put(vAttr); hasChanged = true; } else { for (Enum<?> iterEnum : pOrgAtt) { if (iterEnum != null) { vAttr.add(iterEnum.name()); } } if (vAttr.size() > 0) { vOrgAttributes.put(vAttr); hasChanged = true; } } } else if ((pOrgAtt == null || pOrgAtt.isEmpty()) && (pOldOrgAtt != null && !pOldOrgAtt.isEmpty())) { vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName)); hasChanged = true; } } return hasChanged; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
/** * Checks attribute-set if it has to be written to LDAP or removed from LDAP if attribute = 0, its like not set. * /*www. j av a 2s . co m*/ * @param pOrganisationAtt * @param pOldOrganisationAtt * @param ldapAttributeName * @param vOrgAttributes * @param vOrgRemoveAttributes * @param isUpdate */ private boolean checkAttribute(List<String> pOrganisationAtt, List<String> pOldOrganisationAtt, String ldapAttributeName, Attributes vOrgAttributes, Attributes vOrgRemoveAttributes, boolean isUpdate) { boolean hasChanged = false; if (!isUpdate) { // is create if ((pOrganisationAtt != null) && (!pOrganisationAtt.isEmpty())) { Attribute vAttr = new BasicAttribute(ldapAttributeName); for (String url : pOrganisationAtt) { if ((url != null) && (url.trim().length() > 0)) { vAttr.add(url); } } if (vAttr.size() > 0) { vOrgAttributes.put(vAttr); } } } else { if ((pOrganisationAtt != null) && (!pOrganisationAtt.isEmpty())) { Attribute vAttr = new BasicAttribute(ldapAttributeName); if (pOrganisationAtt.size() == 1 && pOrganisationAtt.contains("") && pOldOrganisationAtt != null && !pOldOrganisationAtt.isEmpty()) { vOrgRemoveAttributes.put(vAttr); hasChanged = true; } else { for (String url : pOrganisationAtt) { if ((url != null) && (url.trim().length() > 0)) { vAttr.add(url); } } if (vAttr.size() > 0) { vOrgAttributes.put(vAttr); hasChanged = true; } } } else if ((pOrganisationAtt == null || pOrganisationAtt.isEmpty()) && (pOldOrganisationAtt != null && !pOldOrganisationAtt.isEmpty())) { vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName)); hasChanged = true; } } return hasChanged; }