use of javax.naming.NamingEnumeration in project zeppelin by apache.
the class ActiveDirectoryGroupRealm method searchForUserName.
public List<String> searchForUserName(String containString, LdapContext ldapContext) throws NamingException {
List<String> userNameList = new ArrayList<>();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))";
Object[] searchArguments = new Object[] { containString };
NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
if (log.isDebugEnabled()) {
log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
}
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration ae = attrs.getAll();
while (ae.hasMore()) {
Attribute attr = (Attribute) ae.next();
if (attr.getID().toLowerCase().equals("cn")) {
userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
}
}
}
}
return userNameList;
}
use of javax.naming.NamingEnumeration in project zeppelin by apache.
the class GetUserList method getUserList.
/**
* function to extract users from Zeppelin LdapRealm
*/
public List<String> getUserList(LdapRealm r, String searchText) {
List<String> userList = new ArrayList<>();
if (LOG.isDebugEnabled()) {
LOG.debug("SearchText: " + searchText);
}
String userAttribute = r.getUserSearchAttributeName();
String userSearchRealm = r.getUserSearchBase();
String userObjectClass = r.getUserObjectClass();
JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
try {
LdapContext ctx = CF.getSystemLdapContext();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = { userAttribute };
constraints.setReturningAttributes(attrIDs);
NamingEnumeration result = ctx.search(userSearchRealm, "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=" + searchText + "))", constraints);
while (result.hasMore()) {
Attributes attrs = ((SearchResult) result.next()).getAttributes();
if (attrs.get(userAttribute) != null) {
String currentUser;
if (r.getUserLowerCase()) {
LOG.debug("userLowerCase true");
currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
} else {
LOG.debug("userLowerCase false");
currentUser = (String) attrs.get(userAttribute).get();
}
if (LOG.isDebugEnabled()) {
LOG.debug("CurrentUser: " + currentUser);
}
userList.add(currentUser.trim());
}
}
} catch (Exception e) {
LOG.error("Error retrieving User list from Ldap Realm", e);
}
return userList;
}
use of javax.naming.NamingEnumeration in project Smack by igniterealtime.
the class JavaxResolver method lookupSRVRecords0.
@Override
protected List<SRVRecord> lookupSRVRecords0(String name, List<HostAddress> failedAddresses, DnssecMode dnssecMode) {
List<SRVRecord> res = null;
Attribute srvAttribute;
try {
Attributes dnsLookup = dirContext.getAttributes(name, new String[] { "SRV" });
srvAttribute = dnsLookup.get("SRV");
if (srvAttribute == null)
return null;
} catch (NameNotFoundException e) {
LOGGER.log(Level.FINEST, "No DNS SRV RR found for " + name, e);
return null;
} catch (NamingException e) {
LOGGER.log(Level.WARNING, "Exception while resolving DNS SRV RR for " + name, e);
return null;
}
try {
@SuppressWarnings("unchecked") NamingEnumeration<String> srvRecords = (NamingEnumeration<String>) srvAttribute.getAll();
res = new ArrayList<>();
while (srvRecords.hasMore()) {
String srvRecordString = srvRecords.next();
String[] srvRecordEntries = srvRecordString.split(" ");
int priority = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 4]);
int port = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 2]);
int weight = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 3]);
String host = srvRecordEntries[srvRecordEntries.length - 1];
List<InetAddress> hostAddresses = lookupHostAddress0(host, failedAddresses, dnssecMode);
if (hostAddresses == null) {
continue;
}
SRVRecord srvRecord = new SRVRecord(host, port, priority, weight, hostAddresses);
res.add(srvRecord);
}
} catch (NamingException e) {
LOGGER.log(Level.SEVERE, "Exception while resolving DNS SRV RR for" + name, e);
}
return res;
}
use of javax.naming.NamingEnumeration in project Openfire by igniterealtime.
the class LdapGroupTester method getGroups.
/**
* Returns fist N groups found in LDAP. The returned groups are only able to return their name,
* description and count of members. Count of members is considering all values that were found
* in the member field.
*
* @param maxGroups max number of groups to return.
* @return fist N groups found in the LDAP.
*/
public Collection<Group> getGroups(int maxGroups) {
Collection<Group> groups = new ArrayList<>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Sort on group name field.
Control[] searchControl = new Control[] { new SortControl(new String[] { manager.getGroupNameField() }, Control.NONCRITICAL) };
ctx.setRequestControls(searchControl);
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
// Attributes to return for each group
String[] standardAttributes = new String[3];
standardAttributes[0] = manager.getGroupNameField();
standardAttributes[1] = manager.getGroupDescriptionField();
standardAttributes[2] = manager.getGroupMemberField();
searchControls.setReturningAttributes(standardAttributes);
// Limit results to those we'll need to process
searchControls.setCountLimit(maxGroups);
String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
NamingEnumeration answer = ctx.search("", filter, searchControls);
while (answer.hasMoreElements()) {
// Get the next group.
Attributes attributes = ((SearchResult) answer.next()).getAttributes();
String groupName = (String) attributes.get(manager.getGroupNameField()).get();
String description = "";
int elements = 0;
try {
description = ((String) attributes.get(manager.getGroupDescriptionField()).get());
} catch (NullPointerException e) {
// Do nothing since the group description field was not found
} catch (Exception e) {
Log.error("Error retrieving group description", e);
}
Attribute memberField = attributes.get(manager.getGroupMemberField());
if (memberField != null) {
NamingEnumeration ne = memberField.getAll();
while (ne.hasMore()) {
ne.next();
elements = elements + 1;
}
}
// Build Group with found information
groups.add(new Group(groupName, description, elements));
}
// Close the enumeration.
answer.close();
} catch (Exception e) {
Log.error(e.getMessage(), e);
} finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
} catch (Exception ignored) {
// Ignore.
}
}
return groups;
}
use of javax.naming.NamingEnumeration in project Openfire by igniterealtime.
the class LdapGroupProvider method processGroup.
private Group processGroup(LdapContext ctx, Attributes a) throws NamingException {
XMPPServer server = XMPPServer.getInstance();
String serverName = server.getServerInfo().getXMPPDomain();
// Build `3 groups.
// group 1: uid=
// group 2: rest of the text until first comma
// group 3: rest of the text
Pattern pattern = Pattern.compile("(?i)(^" + manager.getUsernameField() + "=)([^,]+)(.+)");
// We have to process Active Directory differently.
boolean isAD = manager.getUsernameField().equals("sAMAccountName");
String[] returningAttributes = isAD ? new String[] { "distinguishedName", manager.getUsernameField() } : new String[] { manager.getUsernameField() };
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(returningAttributes);
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
String name;
String description;
try {
name = ((String) ((a.get(manager.getGroupNameField())).get()));
} catch (Exception e) {
name = "";
}
try {
description = ((String) ((a.get(manager.getGroupDescriptionField())).get()));
} catch (Exception e) {
description = "";
}
Set<JID> members = new TreeSet<>();
Attribute memberField = a.get(manager.getGroupMemberField());
if (memberField != null) {
NamingEnumeration ne = memberField.getAll();
while (ne.hasMore()) {
String username = (String) ne.next();
// If not posix mode, each group member is stored as a full DN.
if (!manager.isPosixMode()) {
try {
// Try to find the username with a regex pattern match.
Matcher matcher = pattern.matcher(username);
if (matcher.matches() && matcher.groupCount() == 3) {
// The username is in the DN, no additional search needed
username = matcher.group(2);
} else // The regex pattern match failed. This will happen if the
// the member DN's don't use the standard username field. For
// example, Active Directory has a username field of
// sAMAccountName, but stores group members as "CN=...".
{
// Create an LDAP name with the full DN.
LdapName ldapName = new LdapName(username);
// Turn the LDAP name into something we can use in a
// search by stripping off the comma.
StringBuilder userFilter = new StringBuilder();
userFilter.append("(&(");
userFilter.append(ldapName.get(ldapName.size() - 1));
userFilter.append(')');
userFilter.append(MessageFormat.format(manager.getSearchFilter(), "*"));
userFilter.append(')');
NamingEnumeration usrAnswer = ctx.search("", userFilter.toString(), searchControls);
if (usrAnswer != null && usrAnswer.hasMoreElements()) {
SearchResult searchResult = null;
// Iterate through the entire set to find a matching distinguished name.
while (usrAnswer.hasMoreElements()) {
searchResult = (SearchResult) usrAnswer.nextElement();
Attributes attrs = searchResult.getAttributes();
if (isAD) {
Attribute userdnAttr = attrs.get("distinguishedName");
if (username.equals((String) userdnAttr.get())) {
// Exact match found, use it.
username = (String) attrs.get(manager.getUsernameField()).get();
break;
}
} else {
// No iteration occurs here, which is probably a bug.
username = (String) attrs.get(manager.getUsernameField()).get();
break;
}
}
}
// Close the enumeration.
usrAnswer.close();
}
} catch (Exception e) {
// TODO: A NPE is occuring here
Log.error(e.getMessage(), e);
}
}
// it passes the filter.
try {
JID userJID;
int position = username.indexOf("@" + serverName);
// Create JID of local user if JID does not match a component's JID
if (position == -1) {
// In order to lookup a username from the manager, the username
// must be a properly escaped JID node.
String escapedUsername = JID.escapeNode(username);
if (!escapedUsername.equals(username)) {
// Check if escaped username is valid
userManager.getUser(escapedUsername);
}
// No exception, so the user must exist. Add the user as a group
// member using the escaped username.
userJID = server.createJID(escapedUsername, null);
} else {
// This is a JID of a component or node of a server's component
String node = username.substring(0, position);
String escapedUsername = JID.escapeNode(node);
userJID = new JID(escapedUsername + "@" + serverName);
}
members.add(userJID);
} catch (UserNotFoundException e) {
// So, we want to simply ignore the user as a group member.
if (manager.isDebugEnabled()) {
Log.debug("LdapGroupProvider: User not found: " + username);
}
}
}
// Close the enumeration.
ne.close();
}
if (manager.isDebugEnabled()) {
Log.debug("LdapGroupProvider: Adding group \"" + name + "\" with " + members.size() + " members.");
}
Collection<JID> admins = Collections.emptyList();
return new Group(name, description, members, admins);
}
Aggregations