Java Code Examples for javax.naming.NamingEnumeration#nextElement()

The following examples show how to use javax.naming.NamingEnumeration#nextElement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LDAPAuthenticationService.java    From proxylive with MIT License 6 votes vote down vote up
public String findGroupBySID(DirContext ctx, String ldapSearchBase, String sid) throws NamingException {

        String searchFilter = "(&(objectClass=group)(objectSid=" + sid + "))";

        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls);

        if (results.hasMoreElements()) {
            SearchResult searchResult = (SearchResult) results.nextElement();

            //make sure there is not another item available, there should be only 1 match
            if (results.hasMoreElements()) {
                logger.warn("Matched multiple groups for the group with SID: " + sid);
                return null;
            } else {
                return (String) searchResult.getAttributes().get("sAMAccountName").get();
            }
        }
        return null;
    }
 
Example 2
Source File: ADLdapUserManagerImpl.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context, Long domainId) throws NamingException {
    if (StringUtils.isBlank(groupName)) {
        throw new IllegalArgumentException("ldap group name cannot be blank");
    }

    String basedn = _ldapConfiguration.getBaseDn(domainId);
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }

    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes(domainId));

    NamingEnumeration<SearchResult> results = context.search(basedn, generateADGroupSearchFilter(groupName, domainId), searchControls);
    final List<LdapUser> users = new ArrayList<LdapUser>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result, domainId));
    }
    return users;
}
 
Example 3
Source File: LdapUtils.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * Get the value of the Rdn with the requested key in the supplied Name.
 *
 * @param name the Name in which to search for the key.
 * @param key the attribute key to search for.
 * @return the value of the rdn corresponding to the <b>first</b> occurrence of the requested key.
 * @throws NoSuchElementException if no corresponding entry is found.
 * @since 2.0
 */
public static Object getValue(Name name, String key) {
    NamingEnumeration<? extends Attribute> allAttributes = getRdn(name, key).toAttributes().getAll();
    while (allAttributes.hasMoreElements()) {
        Attribute oneAttribute = allAttributes.nextElement();
        if(key.equalsIgnoreCase(oneAttribute.getID())) {
            try {
                return oneAttribute.get();
            } catch (javax.naming.NamingException e) {
                throw convertLdapException(e);
            }
        }
    }

    // This really shouldn't happen
    throw new NoSuchElementException("No Rdn with the requested key: '" + key + "'");
}
 
Example 4
Source File: EntityService.java    From cukes with Apache License 2.0 6 votes vote down vote up
public void deleteEntityByDn(String dn) {
    try {
        LdapContext context = connectionService.getContext();
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration<SearchResult> children = context.search(dn, "(objectclass=*)", searchControls);
        TreeSet<String> dnsToDelete = new TreeSet<>(new DnComparator(true));
        while (children.hasMoreElements()) {
            SearchResult childResult = children.nextElement();
            String childDn = childResult.getNameInNamespace();
            dnsToDelete.add(childDn);
        }
        for (String s : dnsToDelete) {
            context.destroySubcontext(s);
        }
    } catch (NamingException e) {
        throw new CukesRuntimeException("Cannot delete entity by dn " + dn, e);
    } finally {
        connectionService.close();
    }
}
 
Example 5
Source File: OpenLdapUserManagerImpl.java    From cosmic with Apache License 2.0 6 votes vote down vote up
public LdapUser searchUser(final String basedn, final String searchString, final LdapContext context) throws NamingException, IOException {
    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    final NamingEnumeration<SearchResult> results = context.search(basedn, searchString, searchControls);
    final List<LdapUser> users = new ArrayList<>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));
    }

    if (users.size() == 1) {
        return users.get(0);
    } else {
        throw new NamingException("No user found for basedn " + basedn + " and searchString " + searchString);
    }
}
 
Example 6
Source File: ADLdapUserManagerImpl.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Override
public List<LdapUser> getUsersInGroup(final String groupName, final LdapContext context) throws NamingException {
    if (StringUtils.isBlank(groupName)) {
        throw new IllegalArgumentException("ldap group name cannot be blank");
    }

    final String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }

    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    final NamingEnumeration<SearchResult> results = context.search(basedn, generateADGroupSearchFilter(groupName), searchControls);
    final List<LdapUser> users = new ArrayList<>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));
    }
    return users;
}
 
Example 7
Source File: LdapRepository.java    From library with Apache License 2.0 6 votes vote down vote up
/**
 * Simple version of {@link #listBy(LdapSearchOption, String, Object...)}  but this one will not map the return
 * attributes and let you do that and will not take an {@link LdapSearchOption} as template for search
 *
 * @param filter to be applied
 * @param parameters to be applied to the filter
 * @return a {@link List} of {@link Attributes} found
 */
public List<Attributes> listBy(String filter, Object... parameters) {

    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    final List<Attributes> attributes = new ArrayList<>();

    try {
        final LdapContext context = this.factory.getSystemLdapContext();

        final NamingEnumeration<SearchResult> answer = context.search(this.baseDN, filter, parameters, searchControls);

        while (answer.hasMoreElements()) {
            final SearchResult searchResult = answer.nextElement();
            attributes.add(searchResult.getAttributes());
        }
    } catch (NamingException ex) {
        throw new BusinessLogicException("error.ldap.cant-search-for-users", ex);
    }
    return attributes;
}
 
Example 8
Source File: JndiTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void assertBindings(NamingEnumeration<Binding> namingEnumeration) {
    assertNotNull("namingEnumeration", namingEnumeration);

    Map<String, Object> map = new HashMap<String, Object>();
    while (namingEnumeration.hasMoreElements()) {
        Binding pair = namingEnumeration.nextElement();
        map.put(pair.getName(), pair.getObject());
    }

    assertTrue("OrangeRemote", map.containsKey("OrangeRemote"));
    assertTrue("OrangeRemote is FruitRemote", map.get("OrangeRemote") instanceof FruitRemote);

    assertTrue("AppleRemote", map.containsKey("AppleRemote"));
    assertTrue("AppleRemote is FruitRemote", map.get("AppleRemote") instanceof FruitRemote);

    assertTrue("PeachRemote", map.containsKey("PeachRemote"));
    assertTrue("PeachRemote is FruitRemote", map.get("PeachRemote") instanceof FruitRemote);

    assertTrue("PearRemote", map.containsKey("PearRemote"));
    assertTrue("PearRemote is FruitRemote", map.get("PearRemote") instanceof FruitRemote);

    assertTrue("PlumRemote", map.containsKey("PlumRemote"));
    assertTrue("PlumRemote is FruitRemote", map.get("PlumRemote") instanceof FruitRemote);
}
 
Example 9
Source File: LdapGroupsMapping.java    From hadoop with Apache License 2.0 5 votes vote down vote up
List<String> doGetGroups(String user) throws NamingException {
  List<String> groups = new ArrayList<String>();

  DirContext ctx = getDirContext();

  // Search for the user. We'll only ever need to look at the first result
  NamingEnumeration<SearchResult> results = ctx.search(baseDN,
      userSearchFilter,
      new Object[]{user},
      SEARCH_CONTROLS);
  if (results.hasMoreElements()) {
    SearchResult result = results.nextElement();
    String userDn = result.getNameInNamespace();

    NamingEnumeration<SearchResult> groupResults =
        ctx.search(baseDN,
            "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
            new Object[]{userDn},
            SEARCH_CONTROLS);
    while (groupResults.hasMoreElements()) {
      SearchResult groupResult = groupResults.nextElement();
      Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
      groups.add(groupName.get().toString());
    }
  }

  return groups;
}
 
Example 10
Source File: LdapGroupsMapping.java    From big-c with Apache License 2.0 5 votes vote down vote up
List<String> doGetGroups(String user) throws NamingException {
  List<String> groups = new ArrayList<String>();

  DirContext ctx = getDirContext();

  // Search for the user. We'll only ever need to look at the first result
  NamingEnumeration<SearchResult> results = ctx.search(baseDN,
      userSearchFilter,
      new Object[]{user},
      SEARCH_CONTROLS);
  if (results.hasMoreElements()) {
    SearchResult result = results.nextElement();
    String userDn = result.getNameInNamespace();

    NamingEnumeration<SearchResult> groupResults =
        ctx.search(baseDN,
            "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
            new Object[]{userDn},
            SEARCH_CONTROLS);
    while (groupResults.hasMoreElements()) {
      SearchResult groupResult = groupResults.nextElement();
      Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
      groups.add(groupName.get().toString());
    }
  }

  return groups;
}
 
Example 11
Source File: Debug.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static void contextToMap(final Context context, final String baseName, final Map<String, Object> results) throws NamingException {
    final NamingEnumeration<Binding> namingEnumeration = context.listBindings("");
    while (namingEnumeration.hasMoreElements()) {
        final Binding binding = namingEnumeration.nextElement();
        final String name = binding.getName();
        final String fullName = baseName + name;
        final Object object = binding.getObject();
        results.put(fullName, object);
        if (object instanceof Context) {
            contextToMap((Context) object, fullName + "/", results);
        }
    }
}
 
Example 12
Source File: JndiTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void assertNameClassPair(NamingEnumeration<NameClassPair> namingEnumeration) {
    assertNotNull("namingEnumeration", namingEnumeration);

    Map<String, String> map = new HashMap<String, String>();
    while (namingEnumeration.hasMoreElements()) {
        NameClassPair pair = namingEnumeration.nextElement();
        map.put(pair.getName(), pair.getClassName());
    }

    assertTrue("OrangeRemote", map.containsKey("OrangeRemote"));
    assertTrue("AppleRemote", map.containsKey("AppleRemote"));
    assertTrue("PeachRemote", map.containsKey("PeachRemote"));
    assertTrue("PearRemote", map.containsKey("PearRemote"));
    assertTrue("PlumRemote", map.containsKey("PlumRemote"));
}
 
Example 13
Source File: DirContextAdapter.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
private void collectModifications(Attribute originalAttr,
		Attribute changedAttr, List<ModificationItem> modificationList)
		throws NamingException {

	Attribute originalClone = (Attribute) originalAttr.clone();
	Attribute addedValuesAttribute = new NameAwareAttribute(originalAttr
			.getID());

       NamingEnumeration<?> allValues = changedAttr.getAll();
       while(allValues.hasMoreElements()) {
           Object attributeValue = allValues.nextElement();
           if (!originalClone.remove(attributeValue)) {
               addedValuesAttribute.add(attributeValue);
           }
       }

       // We have now traversed and removed all values from the original that
       // were also present in the new values. The remaining values in the
       // original must be the ones that were removed.
       if(originalClone.size() > 0 && originalClone.size() == originalAttr.size()) {
           // This is actually a complete replacement of the attribute values.
           // Fall back to REPLACE
           modificationList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                   addedValuesAttribute));
       } else {
           if (originalClone.size() > 0) {
               modificationList.add(new ModificationItem(
                       DirContext.REMOVE_ATTRIBUTE, originalClone));
           }

           if (addedValuesAttribute.size() > 0) {
               modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE,
                       addedValuesAttribute));
           }
       }
}
 
Example 14
Source File: NameAwareAttributes.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance, populated with the data from the supplied instance.
 * @param attributes the instance to copy.
 */
public NameAwareAttributes(Attributes attributes) {
    NamingEnumeration<? extends Attribute> allAttributes = attributes.getAll();
    while(allAttributes.hasMoreElements()) {
        Attribute attribute = allAttributes.nextElement();
        put(new NameAwareAttribute(attribute));
    }
}
 
Example 15
Source File: LDAPIdentityStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Set<LDAPCapabilityRepresentation> queryServerCapabilities() {
    Set<LDAPCapabilityRepresentation> result = new LinkedHashSet<>();
    try {
        List<String> attrs = new ArrayList<>();
        attrs.add("supportedControl");
        attrs.add("supportedExtension");
        attrs.add("supportedFeatures");
        List<SearchResult> searchResults = operationManager
            .search("", "(objectClass=*)", Collections.unmodifiableCollection(attrs), SearchControls.OBJECT_SCOPE);
        if (searchResults.size() != 1) {
            throw new ModelException("Could not query root DSE: unexpected result size");
        }
        SearchResult rootDse = searchResults.get(0);
        Attributes attributes = rootDse.getAttributes();
        for (String attr: attrs) {
            Attribute attribute = attributes.get(attr);
            if (null != attribute) {
                CapabilityType capabilityType = CapabilityType.fromRootDseAttributeName(attr);
                NamingEnumeration<?> values = attribute.getAll();
                while (values.hasMoreElements()) {
                    Object o = values.nextElement();
                    LDAPCapabilityRepresentation capability = new LDAPCapabilityRepresentation(o, capabilityType);
                    logger.info("rootDSE query: " + capability);
                    result.add(capability);
                }
            }
        }
        return result;
    } catch (NamingException e) {
        throw new ModelException("Failed to query root DSE: " + e.getMessage(), e);
    }
}
 
Example 16
Source File: LdapSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
/**
 *Strips all the values from the attributes in <code>input</code>. This is performed to be able to delete 
 *the attributes without having to match the values. If values exist they must be exactly matched too in
 *order to delete the attribute.
 */
protected Attributes removeValuesFromAttributes(Attributes input) {
	Attributes result = new BasicAttributes(true);
	// ignore attribute name case
	NamingEnumeration enumeration = input.getIDs();
	while (enumeration.hasMoreElements()) {
		String attrId = (String) enumeration.nextElement();
		result.put(new BasicAttribute(attrId));
	}
	return result;
}
 
Example 17
Source File: GUISSOLdapClient.java    From uavstack with Apache License 2.0 4 votes vote down vote up
private List<SearchResult> ldapApiQuery(String name, String filter) {

        String action = "query";
        String logMsg = action + " " + filter;
        List<SearchResult> result = new ArrayList<SearchResult>();
        try {
            initLdapContext(action);
            LdapContext ldapCtx = ldapContexts.get(action);

            SearchControls constraints = new SearchControls();
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            
            NamingEnumeration<SearchResult> en = ldapCtx.search(name, filter, constraints);

            // means all nodes
            if (en == null) {
                loggerInfo("LDAP信息", "获取", "结果为空", logMsg);
                return Collections.emptyList();
            }
            if (!en.hasMoreElements()) {
                loggerInfo("LDAP信息", "获取", "结果为空", logMsg);
                return Collections.emptyList();
            }

            while (en != null && en.hasMoreElements()) {// maybe more than one element
                Object obj = en.nextElement();
                if (obj instanceof SearchResult) {
                    SearchResult si = (SearchResult) obj;
                    result.add(si);
                }
            }
        }
        catch (Exception e) {
            loggerError("LDAP用户信息获取", logMsg, e);
            clearLdapContext(action);
        }

        if (!result.isEmpty()) {
            loggerInfo("LDAP信息", "获取", "成功", logMsg);
        }
        return result;
    }
 
Example 18
Source File: OpenLdapUserManagerImpl.java    From cosmic with Apache License 2.0 4 votes vote down vote up
@Override
public List<LdapUser> searchUsers(final String username, final LdapContext context) throws NamingException, IOException {

    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    final String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }
    byte[] cookie = null;
    final int pageSize = _ldapConfiguration.getLdapPageSize();
    context.setRequestControls(new Control[]{new PagedResultsControl(pageSize, Control.NONCRITICAL)});
    final List<LdapUser> users = new ArrayList<>();
    NamingEnumeration<SearchResult> results;
    do {
        results = context.search(basedn, generateSearchFilter(username), searchControls);
        while (results.hasMoreElements()) {
            final SearchResult result = results.nextElement();
            if (!isUserDisabled(result)) {
                users.add(createUser(result));
            }
        }
        final Control[] contextControls = context.getResponseControls();
        if (contextControls != null) {
            for (final Control control : contextControls) {
                if (control instanceof PagedResultsResponseControl) {
                    final PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                    cookie = prrc.getCookie();
                }
            }
        } else {
            s_logger.info("No controls were sent from the ldap server");
        }
        context.setRequestControls(new Control[]{new PagedResultsControl(pageSize, cookie, Control.CRITICAL)});
    } while (cookie != null);

    return users;
}
 
Example 19
Source File: AbstractContextSource.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
static String formatForUrl(LdapName ldapName) {
    StringBuilder sb = new StringBuilder();
    ListIterator<Rdn> it = ldapName.getRdns().listIterator(ldapName.size());
    while (it.hasPrevious()) {
        Rdn component = it.previous();

        Attributes attributes = component.toAttributes();

        // Loop through all attribute of the rdn (usually just one, but more are supported by RFC)
        NamingEnumeration<? extends Attribute> allAttributes = attributes.getAll();
        while(allAttributes.hasMoreElements()) {
            Attribute oneAttribute = allAttributes.nextElement();
            String encodedAttributeName = nameEncodeForUrl(oneAttribute.getID());

            // Loop through all values of the attribute (usually just one, but more are supported by RFC)
            NamingEnumeration <?> allValues;
            try {
                allValues = oneAttribute.getAll();
            } catch (NamingException e) {
                throw new UncategorizedLdapException("Unexpected error occurred formatting base URL", e);
            }

            while(allValues.hasMoreElements()) {
                sb.append(encodedAttributeName).append('=');

                Object oneValue = allValues.nextElement();
                if (oneValue instanceof String) {
                    String oneString = (String) oneValue;
                    sb.append(nameEncodeForUrl(oneString));
                } else {
                    throw new IllegalArgumentException("Binary attributes not supported for base URL");
                }

                if(allValues.hasMoreElements()) {
                    sb.append('+');
                }
            }
            if(allAttributes.hasMoreElements()) {
                sb.append('+');
            }
        }

        if(it.hasPrevious()) {
            sb.append(',');
        }
    }
    return sb.toString();
}
 
Example 20
Source File: OpenLdapUserManagerImpl.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@Override
public List<LdapUser> searchUsers(final String username, final LdapContext context, Long domainId) throws NamingException, IOException {

    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes(domainId));

    String basedn = _ldapConfiguration.getBaseDn(domainId);
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException(String.format("ldap basedn is not configured (for domain: %s)", domainId));
    }
    byte[] cookie = null;
    int pageSize = _ldapConfiguration.getLdapPageSize(domainId);
    context.setRequestControls(new Control[]{new PagedResultsControl(pageSize, Control.NONCRITICAL)});
    final List<LdapUser> users = new ArrayList<LdapUser>();
    NamingEnumeration<SearchResult> results;
    do {
        results = context.search(basedn, generateSearchFilter(username, domainId), searchControls);
        while (results.hasMoreElements()) {
            final SearchResult result = results.nextElement();
            if (!isUserDisabled(result)) {
                users.add(createUser(result, domainId));
            }
        }
        Control[] contextControls = context.getResponseControls();
        if (contextControls != null) {
            for (Control control : contextControls) {
                if (control instanceof PagedResultsResponseControl) {
                    PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                    cookie = prrc.getCookie();
                }
            }
        } else {
            LOGGER.info("No controls were sent from the ldap server");
        }
        context.setRequestControls(new Control[] {new PagedResultsControl(pageSize, cookie, Control.CRITICAL)});
    } while (cookie != null);

    return users;
}