List of usage examples for javax.naming.directory Attribute getAll
NamingEnumeration<?> getAll() throws NamingException;
From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java
private Subject createSubject(Attributes attributes) { String name = ""; String subjectID = ""; String description = ""; if (attributes == null) { log.debug("ldap create subject with null attrs"); return (null); }// w w w.ja v a 2 s. c om try { Attribute attribute = attributes.get(subjectIDAttributeName); if (attribute == null) { log.error("No value for LDAP attribute \"" + subjectIDAttributeName + "\". It is Grouper attribute \"SubjectID\"."); return null; } subjectID = ((String) attribute.get()).toLowerCase(); attribute = attributes.get(nameAttributeName); if (attribute == null) { log.debug("No immedaite value for attribute \"" + nameAttributeName + "\". Will look later."); } else { name = (String) attribute.get(); } attribute = attributes.get(descriptionAttributeName); if (attribute == null) { log.debug( "No immedaite value for attribute \"" + descriptionAttributeName + "\". Will look later."); } else { description = (String) attribute.get(); } } catch (NamingException ex) { log.error("LDAP Naming Except: " + ex.getMessage(), ex); } LdapSubject subject = new LdapSubject(subjectID, name, description, this.getSubjectType().getName(), this.getId()); // add the attributes Map myAttributes = new HashMap(); try { for (NamingEnumeration e = attributes.getAll(); e.hasMore();) { Attribute attr = (Attribute) e.next(); String attrName = attr.getID(); // skip the basic ones if (attrName.equals(nameAttributeName)) continue; if (attrName.equals(subjectIDAttributeName)) continue; if (attrName.equals(descriptionAttributeName)) continue; Set values = new HashSet(); for (NamingEnumeration en = attr.getAll(); en.hasMore();) { Object value = en.next(); values.add(value.toString()); } myAttributes.put(attrName, values); } subject.setAttributes(myAttributes); } catch (NamingException e) { log.error("Naming error: " + e); } return subject; }
From source file:org.talend.dataquality.email.checkerImpl.CallbackMailServerCheckerImpl.java
private List<String> getMX(String hostName) throws NamingException { // Perform a DNS lookup for MX records in the domain Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" }); //$NON-NLS-1$ Attribute attr = attrs.get("MX"); //$NON-NLS-1$ List<String> res = new ArrayList<String>(); // if we don't have an MX record, try the machine itself if ((attr == null) || (attr.size() == 0)) { attrs = ictx.getAttributes(hostName, new String[] { "A" }); //$NON-NLS-1$ attr = attrs.get("A"); //$NON-NLS-1$ if (attr == null) { if (LOG.isInfoEnabled()) { LOG.info(HEADER + "No match for hostname '" + hostName + "'"); //$NON-NLS-1$ //$NON-NLS-2$ }/*from w w w . j a v a 2 s . com*/ return res; } } // we have machines to try. Return them as an array list NamingEnumeration<?> en = attr.getAll(); Map<Integer, String> map = new TreeMap<Integer, String>(); while (en.hasMore()) { String mailhost; String x = (String) en.next(); String f[] = x.split(" "); //$NON-NLS-1$ Integer key = 0; if (f.length == 1) { mailhost = f[0]; } else if (f[1].endsWith(".")) { //$NON-NLS-1$ mailhost = f[1].substring(0, f[1].length() - 1); key = Integer.valueOf(f[0]); } else { mailhost = f[1]; key = Integer.valueOf(f[0]); } map.put(key, mailhost); } // NOTE: We SHOULD take the preference into account to be absolutely // correct. Iterator<Integer> keyInterator = map.keySet().iterator(); while (keyInterator.hasNext()) { res.add(map.get(keyInterator.next())); } return res; }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
private boolean isPagedResultControlSupported(final LdapContext ctx) { try {// ww w . j a va 2 s . c o m final SearchControls ctl = new SearchControls(); ctl.setReturningAttributes(new String[] { "supportedControl" }); ctl.setSearchScope(SearchControls.OBJECT_SCOPE); /* search for the rootDSE object */ final NamingEnumeration<SearchResult> results = ctx.search("", "(objectClass=*)", ctl); while (results.hasMore()) { final SearchResult entry = results.next(); final NamingEnumeration<? extends Attribute> attrs = entry.getAttributes().getAll(); while (attrs.hasMore()) { final Attribute attr = attrs.next(); final NamingEnumeration<?> vals = attr.getAll(); while (vals.hasMore()) { final String value = (String) vals.next(); if (value.equals(PAGED_RESULT_CONTROL_OID)) { return true; } } } } return false; } catch (final Exception e) { logError("Exception when trying to know if the server support paged results.", e); return false; } }
From source file:com.surevine.ldap2alfresco.ProfileFieldTextConverter.java
/** * Encode some attributes as JSON./* w ww . ja v a2s . 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 { json.put(jsonLabel, ""); } } 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(); if (value != null && value.length() > MAX_STRING_LENGTH) { value = value.substring(0, MAX_STRING_LENGTH - 1); } values.put(value); } 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(); if (value != null && value.length() > MAX_STRING_LENGTH) { value = value.substring(0, MAX_STRING_LENGTH - 1); } json.put(jsonLabel, value); } } catch (NamingException e) { logException(Level.ERROR, e); return; } catch (JSONException e) { logException(Level.ERROR, e); return; } }
From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java
/** * Try to get more attributes for the argument subject. (from name) *//*from w ww .j av a2 s .c o m*/ protected Map getAllAttributes(LdapSubject subject) { Map attributes = new HashMap(); log.debug("getAllAttributes for " + subject.getName()); Search search = getSearch("searchSubjectAttributes"); if (search == null) { log.error("searchType: \"searchSubjectAttributes\" not defined."); return attributes; } try { Attributes ldapAttributes = getLdapUnique(search, subject.getName(), allAttributeNames); for (NamingEnumeration e = ldapAttributes.getAll(); e.hasMore();) { Attribute attr = (Attribute) e.next(); String attrName = attr.getID(); // special case the basic ones if (attrName.equals(subjectIDAttributeName)) continue; // already have if (attrName.equals(nameAttributeName)) continue; // already have if (attrName.equals(descriptionAttributeName)) { subject.setDescription((String) attr.get()); continue; } Set values = new HashSet(); for (NamingEnumeration en = attr.getAll(); en.hasMore();) { Object value = en.next(); values.add(value.toString()); } attributes.put(attrName, values); } subject.setAttributes(attributes); } 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 attributes; }
From source file:net.officefloor.plugin.web.http.security.store.JndiLdapCredentialStoreTest.java
/** * Ensure correct credentials./*from w w w .j ava 2 s . c o m*/ */ @SuppressWarnings("unchecked") public void testCredentials() throws Exception { // Create the expected credentials final String expectedRaw = "daniel:officefloor:password"; MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(expectedRaw.getBytes(US_ASCII)); final byte[] expectedCredentials = digest.digest(); // Obtain the encoded credentials final String encodedCredentials = Base64.encodeBase64String(expectedCredentials).trim(); assertEquals("Incorrect encoded credentials", "msu723GSLovbwuaPnaLcnQ==", encodedCredentials); // Mocks final NamingEnumeration<SearchResult> searchResults = this.createMock(NamingEnumeration.class); final Attributes attributes = this.createMock(Attributes.class); final Attribute attribute = this.createMock(Attribute.class); final NamingEnumeration<?> userPasswords = this.createMock(NamingEnumeration.class); // Objects final SearchResult searchResult = new SearchResult("uid=daniel", null, attributes); searchResult.setNameInNamespace("uid=daniel,ou=People,dc=officefloor,dc=net"); // Record this.recordReturn(this.context, this.context.search("ou=People,dc=officefloor,dc=net", "(&(objectClass=inetOrgPerson)(uid=daniel))", null), searchResults); this.recordReturn(searchResults, searchResults.hasMore(), true); this.recordReturn(searchResults, searchResults.next(), searchResult); this.recordReturn(this.context, this.context.getAttributes("uid=daniel,ou=People,dc=officefloor,dc=net"), attributes); this.recordReturn(attributes, attributes.get("userPassword"), attribute); this.recordReturn(attribute, attribute.getAll(), userPasswords); this.recordReturn(userPasswords, userPasswords.hasMore(), true); this.recordReturn(userPasswords, userPasswords.next(), "Plain Text Password".getBytes(US_ASCII)); this.recordReturn(userPasswords, userPasswords.hasMore(), true); this.recordReturn(userPasswords, userPasswords.next(), ("{MD5}" + encodedCredentials).getBytes(US_ASCII)); // Test this.replayMockObjects(); CredentialEntry entry = this.store.retrieveCredentialEntry("daniel", "REALM"); byte[] actualCredentials = entry.retrieveCredentials(); this.verifyMockObjects(); // Validate correct value assertEquals("Incorrect credential byte length", expectedCredentials.length, actualCredentials.length); for (int i = 0; i < expectedCredentials.length; i++) { assertEquals("Incorrect credential byte " + i, expectedCredentials[i], actualCredentials[i]); } }
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; }/* www .ja v a 2 s .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.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. ja v a 2 s . c om*/ 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.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
private Attribute getChangePasswordAttribute(Attribute oldPasswordAttribute, Object oldCredential, Object newPassword) throws DirectoryServerManagerException { String passwordHashMethod = null; // when admin changes other user passwords he do not have to provide // the old password. if (oldCredential != null) { // here it is only possible to have one password, if there are more // every one should match with the given old password try {// w w w.java 2 s . com NamingEnumeration passwords = oldPasswordAttribute.getAll(); if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray, StandardCharsets.UTF_8); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}")); } if (!password.equals(getPasswordToStore((String) oldCredential, passwordHashMethod))) { throw new DirectoryServerManagerException("Old password does not match"); } } } catch (NamingException e) { log.error("Unable to retrieve old password details.", e); throw new DirectoryServerManagerException("Could not find old password details"); } } Attribute passwordAttribute = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD); passwordAttribute.add(getPasswordToStore((String) newPassword, passwordHashMethod)); return passwordAttribute; }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
@SuppressWarnings("unchecked") private List getUserRolesByDn(DirContext dirContext, String userDn, String username) throws LoginException, NamingException { List<String> roleList = new ArrayList<String>(); if (dirContext == null || _roleBaseDn == null || (_roleMemberAttribute == null && _roleUsernameMemberAttribute == null) || _roleObjectClass == null) { LOG.warn(//from ww w . j av a 2 s . c om "JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified."); addSupplementalRoles(roleList); return roleList; } String[] attrIDs = { _roleNameAttribute }; SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(attrIDs); ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = OBJECT_CLASS_FILTER; final NamingEnumeration results; if (null != _roleUsernameMemberAttribute) { Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username }; results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls); } else { Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn }; results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls); } while (results.hasMoreElements()) { SearchResult result = (SearchResult) results.nextElement(); Attributes attributes = result.getAttributes(); if (attributes == null) { continue; } Attribute roleAttribute = attributes.get(_roleNameAttribute); if (roleAttribute == null) { continue; } NamingEnumeration roles = roleAttribute.getAll(); while (roles.hasMore()) { if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) { String role = (String) roles.next(); roleList.add(role.replace(_rolePrefix, "")); } else { roleList.add((String) roles.next()); } } } addSupplementalRoles(roleList); if (_nestedGroups) { roleList = getNestedRoles(dirContext, roleList); } if (roleList.size() < 1) { LOG.warn("JettyCachingLdapLoginModule: User '" + username + "' has no role membership; role query configuration may be incorrect"); } else { debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList); } return roleList; }