List of usage examples for javax.naming.directory Attribute getID
String getID();
From source file:org.apache.zeppelin.realm.LdapRealm.java
private void addRoleIfMember(final String userDn, final SearchResult group, final Set<String> roleNames, final Set<String> groupNames, final LdapContextFactory ldapContextFactory) throws NamingException { NamingEnumeration<? extends Attribute> attributeEnum = null; NamingEnumeration<?> ne = null; try {// ww w .java 2 s. c o m LdapName userLdapDn = new LdapName(userDn); Attribute attribute = group.getAttributes().get(getGroupIdAttribute()); String groupName = attribute.get().toString(); attributeEnum = group.getAttributes().getAll(); while (attributeEnum.hasMore()) { final Attribute attr = attributeEnum.next(); if (!memberAttribute.equalsIgnoreCase(attr.getID())) { continue; } ne = attr.getAll(); while (ne.hasMore()) { String attrValue = ne.next().toString(); if (memberAttribute.equalsIgnoreCase(MEMBER_URL)) { boolean dynamicGroupMember = isUserMemberOfDynamicGroup(userLdapDn, attrValue, ldapContextFactory); if (dynamicGroupMember) { groupNames.add(groupName); String roleName = roleNameFor(groupName); if (roleName != null) { roleNames.add(roleName); } else { roleNames.add(groupName); } } } else { // posix groups' members don' include the entire dn if (groupObjectClass.equalsIgnoreCase(POSIX_GROUP)) { attrValue = memberDn(attrValue); } if (userLdapDn.equals(new LdapName(attrValue))) { groupNames.add(groupName); String roleName = roleNameFor(groupName); if (roleName != null) { roleNames.add(roleName); } else { roleNames.add(groupName); } break; } } } } } finally { try { if (attributeEnum != null) { attributeEnum.close(); } } finally { if (ne != null) { ne.close(); } } } }
From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java
private void sortAttributes(final List<Attribute> sortedAttrs) { Collections.sort(sortedAttrs, new Comparator<Attribute>() { @Override/* w w w. j a va 2s. c om*/ public int compare(Attribute o1, Attribute o2) { String nm1 = o1.getID(); String nm2 = o2.getID(); return nm1.compareTo(nm2); } }); }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Checks if LDAP properties are different then OLAT properties of a User. If they are different a Map (OlatPropertyName,LDAPValue) is returned. * /*from w ww. j a va 2s . c o m*/ * @param attributes Set of LDAP Attribute of Identity * @param identity Identity to compare * @return Map(OlatPropertyName,LDAPValue) of properties Identity, where property has changed. NULL is returned it no attributes have to be synced */ @SuppressWarnings("unchecked") public Map<String, String> prepareUserPropertyForSync(final Attributes attributes, final Identity identity) { final Map<String, String> olatPropertyMap = new HashMap<String, String>(); final User user = identity.getUser(); final NamingEnumeration<Attribute> neAttrs = (NamingEnumeration<Attribute>) attributes.getAll(); try { while (neAttrs.hasMore()) { final Attribute attr = neAttrs.next(); final String olatProperty = mapLdapAttributeToOlatProperty(attr.getID()); if (olatProperty == null) { continue; } final String ldapValue = getAttributeValue(attr); final String olatValue = user.getProperty(olatProperty, null); if (olatValue == null) { // new property or user ID (will always be null, pseudo property) olatPropertyMap.put(olatProperty, ldapValue); } else { if (ldapValue.compareTo(olatValue) != 0) { olatPropertyMap.put(olatProperty, ldapValue); } } } if (olatPropertyMap.size() == 1 && olatPropertyMap.get(LDAPConstants.LDAP_USER_IDENTIFYER) != null) { return null; } return olatPropertyMap; } catch (final NamingException e) { logError("NamingException when trying to prepare user properties for LDAP sync", e); return null; } }
From source file:org.swordess.ldap.odm.core.SessionImpl.java
private Map<String, Object> fromAttributesToMap(Class<?> clazz, Attributes attributes) throws NamingException { try {/*from ww w . j ava2s . c om*/ 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:com.wfp.utils.LDAPUtils.java
public static Map<String, Object> parseDataAsMap(NamingEnumeration searchResults, String listValues) { //Logger.info("Formatting the data as MAP", LDAPUtils.class); Map<String, Object> resultAttrMap = null; int totalResultLogger = 0; if (searchResults == null) { return null; }//from ww w.j ava 2 s . c om // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return null; } Attributes attrs = sr.getAttributes(); if (attrs != null) { if (resultAttrMap == null) { resultAttrMap = new HashMap<String, Object>(); } try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { String attrValue = (String) e.next(); List<String> attrValuesList = null; if (listValues.indexOf(attr.getID()) >= 0) { attrValuesList = resultAttrMap.get(attr.getID()) == null ? null : (List<String>) resultAttrMap.get(attr.getID()); if (attrValuesList == null) { attrValuesList = new ArrayList<String>(); } attrValuesList.add(attrValue); resultAttrMap.put(attr.getID(), attrValuesList); } else { resultAttrMap.put(attr.getID(), attrValue); } } } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } return resultAttrMap; }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Creates User in OLAT and ads user to LDAP securityGroup Required Attributes have to be checked before this method. * //w w w . ja va 2 s .c o m * @param userAttributes Set of LDAP Attribute of User to be created */ @SuppressWarnings("unchecked") public void createAndPersistUser(final Attributes userAttributes) { // Get and Check Config final String[] reqAttrs = LDAPLoginModule.checkReqAttr(userAttributes); if (reqAttrs != null) { logWarn("Can not create and persist user, the following attributes are missing::" + ArrayUtils.toString(reqAttrs), null); return; } final String uid = getAttributeValue(userAttributes .get(LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER))); final String email = getAttributeValue( userAttributes.get(LDAPLoginModule.mapOlatPropertyToLdapAttribute(UserConstants.EMAIL))); // Lookup user if (securityManager.findIdentityByName(uid) != null) { logError("Can't create user with username='" + uid + "', does already exist in OLAT database", null); return; } if (!MailHelper.isValidEmailAddress(email)) { // needed to prevent possibly an AssertException in findIdentityByEmail breaking the sync! logError("Cannot try to lookup user " + uid + " by email with an invalid email::" + email, null); return; } if (userManager.findIdentityByEmail(email) != null) { logError("Can't create user with email='" + email + "', does already exist in OLAT database", null); return; } // Create User (first and lastname is added in next step) final User user = userManager.createUser(null, null, email); // Set User Property's (Iterates over Attributes and gets OLAT Property out // of olatexconfig.xml) final NamingEnumeration<Attribute> neAttr = (NamingEnumeration<Attribute>) userAttributes.getAll(); try { while (neAttr.hasMore()) { final Attribute attr = neAttr.next(); final String olatProperty = mapLdapAttributeToOlatProperty(attr.getID()); if (attr.get() != uid) { final String ldapValue = getAttributeValue(attr); if (olatProperty == null || ldapValue == null) { continue; } user.setProperty(olatProperty, ldapValue); } } // Add static user properties from the configuration final Map<String, String> staticProperties = LDAPLoginModule.getStaticUserProperties(); if (staticProperties != null && staticProperties.size() > 0) { for (final Entry<String, String> staticProperty : staticProperties.entrySet()) { user.setProperty(staticProperty.getKey(), staticProperty.getValue()); } } } catch (final NamingException e) { logError("NamingException when trying to create and persist LDAP user with username::" + uid, e); return; } catch (final Exception e) { // catch any exception here to properly log error logError("Unknown exception when trying to create and persist LDAP user with username::" + uid, e); return; } // Create Identity final Identity identity = securityManager.createAndPersistIdentityAndUser(uid, user, LDAPAuthenticationController.PROVIDER_LDAP, uid, null); // Add to SecurityGroup LDAP SecurityGroup secGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP); securityManager.addIdentityToSecurityGroup(identity, secGroup); // Add to SecurityGroup OLATUSERS secGroup = securityManager.findSecurityGroupByName(Constants.GROUP_OLATUSERS); securityManager.addIdentityToSecurityGroup(identity, secGroup); logInfo("Created LDAP user username::" + uid); }
From source file:org.swordess.ldap.odm.core.SessionImpl.java
private <T> T fromAttributesToEntity(Class<T> clazz, Attributes attributes) throws NamingException { try {// w w w. ja v a2s . c o m Map.Entry<Object, SetterInterceptor> pair = EntityProxyFactory.getProxiedEntity(clazz); T entity = (T) pair.getKey(); EntityMetaData metaData = EntityMetaData.get(clazz); Set<String> multipleLdapAttrNames = new HashSet<String>(); for (EntityPropertyMetaData propMetaData : metaData) { if (propMetaData.isMultiple()) { multipleLdapAttrNames.add(propMetaData.getLdapPropName()); } } for (NamingEnumeration<? extends Attribute> attrs = attributes.getAll(); attrs.hasMore();) { Attribute attr = attrs.next(); EntityPropertyMetaData propMetaData = metaData.getProperty(attr.getID()); if (null == propMetaData) { // current attribute exist in LDAP but not defined in our // POJO. continue; } if (propMetaData.isId()) { propMetaData.setter().set(entity, attr.get()); if (entity instanceof Distinguishable) { ((Distinguishable) entity) .setDN(attr.getID() + "=" + attr.get().toString() + "," + metaData.context()); } } else { List<String> attrValues = new ArrayList<String>(); for (NamingEnumeration<?> all = attr.getAll(); all.hasMore();) { attrValues.add(propMetaData.getSyntaxer().ldapStringToJavaString(all.next().toString())); } if (!propMetaData.isReference()) { if (!propMetaData.isMultiple()) { propMetaData.setter().set(entity, attrValues.get(0)); } else { propMetaData.setter().set(entity, new MoniteredList<String>(attrValues)); multipleLdapAttrNames.remove(propMetaData.getLdapPropName()); } } else { final Class<?> referenceType = propMetaData.getValueClass(); if (!propMetaData.isMultiple()) { propMetaData.setter().set(entity, EntityProxyFactory.getLazyLoadingProxiedEntity(this, referenceType, attrValues.get(0))); } else { List references = new ArrayList(); for (String dn : attrValues) { references.add( EntityProxyFactory.getLazyLoadingProxiedEntity(this, referenceType, dn)); } propMetaData.setter().set(entity, new MoniteredList(references)); multipleLdapAttrNames.remove(propMetaData.getLdapPropName()); } } } /* * The rest attribute names in multipleLdapAttrNames are those * not presented in LDAP side. In order to track what changes * occurred to these attributes, we need to use MoniteredList. */ for (String notPresentedMultipleLdapAttrName : multipleLdapAttrNames) { metaData.getProperty(notPresentedMultipleLdapAttrName).setter().set(entity, new MoniteredList()); } } /* * Once all the properties have been initialized, we should turn on * the switch of SetterInterceptor to monitor changes. */ pair.getValue().turnOn(); return entity; } catch (NamingException e) { LogUtils.debug(LOG, "failed to go through attributes when fromAttributesToEntity"); throw e; } }
From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java
/** Get the AD-derived access tokens for a user and domain */ protected List<String> getADTokens(String userPart, String domainPart, String userName) throws NameNotFoundException, NamingException, ManifoldCFException { // Now, look through the rules for the matching domain controller String domainController = null; for (DCRule rule : dCRules) { String suffix = rule.getSuffix(); if (suffix.length() == 0 || domainPart.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT)) && (suffix.length() == domainPart.length() || domainPart.charAt((domainPart.length() - suffix.length()) - 1) == '.')) { domainController = rule.getDomainControllerName(); break; }/* w ww . jav a2s. c o m*/ } if (domainController == null) // No AD user return null; // Look up connection parameters DCConnectionParameters dcParams = dCConnectionParameters.get(domainController); if (dcParams == null) // No AD user return null; // Use the complete fqn if the field is the "userPrincipalName" String userBase; String userACLsUsername = dcParams.getUserACLsUsername(); if (userACLsUsername != null && userACLsUsername.equals("userPrincipalName")) { userBase = userName; } else { userBase = userPart; } //Build the DN searchBase from domain part StringBuilder domainsb = new StringBuilder(); int j = 0; while (true) { if (j > 0) domainsb.append(","); int k = domainPart.indexOf(".", j); if (k == -1) { domainsb.append("DC=").append(ldapEscape(domainPart.substring(j))); break; } domainsb.append("DC=").append(ldapEscape(domainPart.substring(j, k))); j = k + 1; } // Establish a session with the selected domain controller LdapContext ctx = createDCSession(domainController); //Get DistinguishedName (for this method we are using DomainPart as a searchBase ie: DC=qa-ad-76,DC=metacarta,DC=com") String searchBase = getDistinguishedName(ctx, userBase, domainsb.toString(), userACLsUsername); if (searchBase == null) return null; //specify the LDAP search filter String searchFilter = "(objectClass=user)"; //Create the search controls for finding the access tokens SearchControls searchCtls = new SearchControls(); //Specify the search scope, must be base level search for tokenGroups searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE); //Specify the attributes to return String returnedAtts[] = { "tokenGroups", "objectSid" }; searchCtls.setReturningAttributes(returnedAtts); //Search for tokens. Since every user *must* have a SID, the "no user" detection should be safe. NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); List<String> theGroups = new ArrayList<String>(); String userToken = userTokenFromLoginName(domainPart + "\\" + userPart); if (userToken != null) theGroups.add(userToken); //Loop through the search results while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); //the sr.GetName should be null, as it is relative to the base object Attributes attrs = sr.getAttributes(); if (attrs != null) { try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore();) { String sid = sid2String((byte[]) e.next()); String token = attr.getID().equals("objectSid") ? userTokenFromSID(sid) : groupTokenFromSID(sid); theGroups.add(token); } } } catch (NamingException e) { throw new ManifoldCFException(e.getMessage(), e); } } } if (theGroups.size() == 0) return null; // User is in AD, so add the 'everyone' group theGroups.add(everyoneGroup()); return theGroups; }
From source file:org.springframework.ldap.core.DirContextAdapter.java
/** * Checks if an entry has a specific attribute. * //w w w . jav a 2s. co m * This method simply calls exists(String) with the attribute name. * * @param attr the attribute to check. * @return true if attribute exists in entry. */ protected final boolean exists(Attribute attr) { return exists(attr.getID()); }
From source file:org.springframework.ldap.core.DirContextAdapter.java
public String[] getNamesOfModifiedAttributes() { List tmpList = new ArrayList(); NamingEnumeration attributesEnumeration; if (isUpdateMode()) { attributesEnumeration = updatedAttrs.getAll(); } else {/* w w w. j a v a 2 s . co m*/ attributesEnumeration = originalAttrs.getAll(); } try { while (attributesEnumeration.hasMore()) { Attribute oneAttribute = (Attribute) attributesEnumeration.next(); tmpList.add(oneAttribute.getID()); } } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } finally { closeNamingEnumeration(attributesEnumeration); } return (String[]) tmpList.toArray(new String[0]); }