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

The following examples show how to use javax.naming.NamingEnumeration#next() . 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: EntityFacade.java    From cukes with Apache License 2.0 6 votes vote down vote up
public void entityHasAttributeWithValueMatchingPattern(String attribute, String pattern) {
    Attribute attr = getNotNullAttribute(attribute);
    Matcher<CharSequence> matcher = ContainsPattern.containsPattern(pattern);
    try {
        NamingEnumeration<?> e = attr.getAll();
        while (e.hasMore()) {
            Object next = e.next();
            String s = String.valueOf(next);
            if (matcher.matches(s)) {
                return;
            }
        }
    } catch (NamingException ex) {
        throw new CukesRuntimeException(ex);
    }
    fail();
}
 
Example 2
Source File: JmsPoolXAConnectionFactory.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
private void configFromJndiConf(Object rootContextName) {
    if (rootContextName instanceof String) {
        String name = (String) rootContextName;
        name = name.substring(0, name.lastIndexOf('/')) + "/conf" + name.substring(name.lastIndexOf('/'));
        try {
            InitialContext ctx = new InitialContext();
            NamingEnumeration<Binding> bindings = ctx.listBindings(name);

            while (bindings.hasMore()) {
                Binding bd = bindings.next();
                IntrospectionSupport.setProperty(this, bd.getName(), bd.getObject());
            }

        } catch (Exception ignored) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("exception on config from jndi: " + name, ignored);
            }
        }
    }
}
 
Example 3
Source File: LDAPCertStore.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the values for the given attribute. If the attribute is null
 * or does not contain any values, a zero length byte array is
 * returned. NOTE that it is assumed that all values are byte arrays.
 */
private byte[][] getAttributeValues(Attribute attr)
        throws NamingException {
    byte[][] values;
    if (attr == null) {
        values = BB0;
    } else {
        values = new byte[attr.size()][];
        int i = 0;
        NamingEnumeration<?> enum_ = attr.getAll();
        while (enum_.hasMore()) {
            Object obj = enum_.next();
            if (debug != null) {
                if (obj instanceof String) {
                    debug.println("LDAPCertStore.getAttrValues() "
                        + "enum.next is a string!: " + obj);
                }
            }
            byte[] value = (byte[])obj;
            values[i++] = value;
        }
    }
    return values;
}
 
Example 4
Source File: Rdn.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs an Rdn from the given attribute set. See
 * {@link javax.naming.directory.Attributes Attributes}.
 * <p>
 * The string attribute values are not interpreted as
 * <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
 * formatted RDN strings. That is, the values are used
 * literally (not parsed) and assumed to be unescaped.
 *
 * @param attrSet The non-null and non-empty attributes containing
 * type/value mappings.
 * @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
 *          be used to construct a valid RDN.
 */
public Rdn(Attributes attrSet) throws InvalidNameException {
    if (attrSet.size() == 0) {
        throw new InvalidNameException("Attributes cannot be empty");
    }
    entries = new ArrayList<>(attrSet.size());
    NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
    try {
        for (int nEntries = 0; attrs.hasMore(); nEntries++) {
            RdnEntry entry = new RdnEntry();
            Attribute attr = attrs.next();
            entry.type = attr.getID();
            entry.value = attr.get();
            entries.add(nEntries, entry);
        }
    } catch (NamingException e) {
        InvalidNameException e2 = new InvalidNameException(
                                    e.getMessage());
        e2.initCause(e);
        throw e2;
    }
    sort(); // arrange entries for comparison
}
 
Example 5
Source File: Rdn.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs an Rdn from the given attribute set. See
 * {@link javax.naming.directory.Attributes Attributes}.
 * <p>
 * The string attribute values are not interpreted as
 * <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
 * formatted RDN strings. That is, the values are used
 * literally (not parsed) and assumed to be unescaped.
 *
 * @param attrSet The non-null and non-empty attributes containing
 * type/value mappings.
 * @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
 *          be used to construct a valid RDN.
 */
public Rdn(Attributes attrSet) throws InvalidNameException {
    if (attrSet.size() == 0) {
        throw new InvalidNameException("Attributes cannot be empty");
    }
    entries = new ArrayList<>(attrSet.size());
    NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
    try {
        for (int nEntries = 0; attrs.hasMore(); nEntries++) {
            RdnEntry entry = new RdnEntry();
            Attribute attr = attrs.next();
            entry.type = attr.getID();
            entry.value = attr.get();
            entries.add(nEntries, entry);
        }
    } catch (NamingException e) {
        InvalidNameException e2 = new InvalidNameException(
                                    e.getMessage());
        e2.initCause(e);
        throw e2;
    }
    sort(); // arrange entries for comparison
}
 
Example 6
Source File: TestLdap.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public void testGalfind() throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    NamingEnumeration<SearchResult> searchResults = ldapContext.search("ou=people", "(uid="+session.getAlias()+ ')', searchControls);
    assertTrue(searchResults.hasMore());
    SearchResult searchResult = searchResults.next();
    Attributes attributes = searchResult.getAttributes();
    Attribute attribute = attributes.get("uid");
    assertEquals(session.getAlias(), attribute.get());
    // given name not available on Exchange 2007 over Dav (no gallookup)
    //assertNotNull(attributes.get("givenName"));
    searchResults.close();
}
 
Example 7
Source File: BasicAttributes.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determines whether this <tt>BasicAttributes</tt> is equal to another
 * <tt>Attributes</tt>
 * Two <tt>Attributes</tt> are equal if they are both instances of
 * <tt>Attributes</tt>,
 * treat the case of attribute IDs the same way, and contain the
 * same attributes. Each <tt>Attribute</tt> in this <tt>BasicAttributes</tt>
 * is checked for equality using <tt>Object.equals()</tt>, which may have
 * be overridden by implementations of <tt>Attribute</tt>).
 * If a subclass overrides <tt>equals()</tt>,
 * it should override <tt>hashCode()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 * @param obj the possibly null object to compare against.
 *
 * @return true If obj is equal to this BasicAttributes.
 * @see #hashCode
 */
public boolean equals(Object obj) {
    if ((obj != null) && (obj instanceof Attributes)) {
        Attributes target = (Attributes)obj;

        // Check case first
        if (ignoreCase != target.isCaseIgnored()) {
            return false;
        }

        if (size() == target.size()) {
            Attribute their, mine;
            try {
                NamingEnumeration<?> theirs = target.getAll();
                while (theirs.hasMore()) {
                    their = (Attribute)theirs.next();
                    mine = get(their.getID());
                    if (!their.equals(mine)) {
                        return false;
                    }
                }
            } catch (NamingException e) {
                return false;
            }
            return true;
        }
    }
    return false;
}
 
Example 8
Source File: BasicAttributes.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determines whether this <tt>BasicAttributes</tt> is equal to another
 * <tt>Attributes</tt>
 * Two <tt>Attributes</tt> are equal if they are both instances of
 * <tt>Attributes</tt>,
 * treat the case of attribute IDs the same way, and contain the
 * same attributes. Each <tt>Attribute</tt> in this <tt>BasicAttributes</tt>
 * is checked for equality using <tt>Object.equals()</tt>, which may have
 * be overridden by implementations of <tt>Attribute</tt>).
 * If a subclass overrides <tt>equals()</tt>,
 * it should override <tt>hashCode()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 * @param obj the possibly null object to compare against.
 *
 * @return true If obj is equal to this BasicAttributes.
 * @see #hashCode
 */
public boolean equals(Object obj) {
    if ((obj != null) && (obj instanceof Attributes)) {
        Attributes target = (Attributes)obj;

        // Check case first
        if (ignoreCase != target.isCaseIgnored()) {
            return false;
        }

        if (size() == target.size()) {
            Attribute their, mine;
            try {
                NamingEnumeration<?> theirs = target.getAll();
                while (theirs.hasMore()) {
                    their = (Attribute)theirs.next();
                    mine = get(their.getID());
                    if (!their.equals(mine)) {
                        return false;
                    }
                }
            } catch (NamingException e) {
                return false;
            }
            return true;
        }
    }
    return false;
}
 
Example 9
Source File: LDAPLoginManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
private boolean isPagedResultControlSupported(final LdapContext ctx) {
    try {
        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) {
        log.error("Exception when trying to know if the server support paged results.", e);
        return false;
    }
}
 
Example 10
Source File: BasicAttributes.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Determines whether this <tt>BasicAttributes</tt> is equal to another
 * <tt>Attributes</tt>
 * Two <tt>Attributes</tt> are equal if they are both instances of
 * <tt>Attributes</tt>,
 * treat the case of attribute IDs the same way, and contain the
 * same attributes. Each <tt>Attribute</tt> in this <tt>BasicAttributes</tt>
 * is checked for equality using <tt>Object.equals()</tt>, which may have
 * be overridden by implementations of <tt>Attribute</tt>).
 * If a subclass overrides <tt>equals()</tt>,
 * it should override <tt>hashCode()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 * @param obj the possibly null object to compare against.
 *
 * @return true If obj is equal to this BasicAttributes.
 * @see #hashCode
 */
public boolean equals(Object obj) {
    if ((obj != null) && (obj instanceof Attributes)) {
        Attributes target = (Attributes)obj;

        // Check case first
        if (ignoreCase != target.isCaseIgnored()) {
            return false;
        }

        if (size() == target.size()) {
            Attribute their, mine;
            try {
                NamingEnumeration<?> theirs = target.getAll();
                while (theirs.hasMore()) {
                    their = (Attribute)theirs.next();
                    mine = get(their.getID());
                    if (!their.equals(mine)) {
                        return false;
                    }
                }
            } catch (NamingException e) {
                return false;
            }
            return true;
        }
    }
    return false;
}
 
Example 11
Source File: BasicAttributes.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determines whether this <tt>BasicAttributes</tt> is equal to another
 * <tt>Attributes</tt>
 * Two <tt>Attributes</tt> are equal if they are both instances of
 * <tt>Attributes</tt>,
 * treat the case of attribute IDs the same way, and contain the
 * same attributes. Each <tt>Attribute</tt> in this <tt>BasicAttributes</tt>
 * is checked for equality using <tt>Object.equals()</tt>, which may have
 * be overridden by implementations of <tt>Attribute</tt>).
 * If a subclass overrides <tt>equals()</tt>,
 * it should override <tt>hashCode()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 * @param obj the possibly null object to compare against.
 *
 * @return true If obj is equal to this BasicAttributes.
 * @see #hashCode
 */
public boolean equals(Object obj) {
    if ((obj != null) && (obj instanceof Attributes)) {
        Attributes target = (Attributes)obj;

        // Check case first
        if (ignoreCase != target.isCaseIgnored()) {
            return false;
        }

        if (size() == target.size()) {
            Attribute their, mine;
            try {
                NamingEnumeration<?> theirs = target.getAll();
                while (theirs.hasMore()) {
                    their = (Attribute)theirs.next();
                    mine = get(their.getID());
                    if (!their.equals(mine)) {
                        return false;
                    }
                }
            } catch (NamingException e) {
                return false;
            }
            return true;
        }
    }
    return false;
}
 
Example 12
Source File: BasicAttributes.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determines whether this <tt>BasicAttributes</tt> is equal to another
 * <tt>Attributes</tt>
 * Two <tt>Attributes</tt> are equal if they are both instances of
 * <tt>Attributes</tt>,
 * treat the case of attribute IDs the same way, and contain the
 * same attributes. Each <tt>Attribute</tt> in this <tt>BasicAttributes</tt>
 * is checked for equality using <tt>Object.equals()</tt>, which may have
 * be overridden by implementations of <tt>Attribute</tt>).
 * If a subclass overrides <tt>equals()</tt>,
 * it should override <tt>hashCode()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 * @param obj the possibly null object to compare against.
 *
 * @return true If obj is equal to this BasicAttributes.
 * @see #hashCode
 */
public boolean equals(Object obj) {
    if ((obj != null) && (obj instanceof Attributes)) {
        Attributes target = (Attributes)obj;

        // Check case first
        if (ignoreCase != target.isCaseIgnored()) {
            return false;
        }

        if (size() == target.size()) {
            Attribute their, mine;
            try {
                NamingEnumeration<?> theirs = target.getAll();
                while (theirs.hasMore()) {
                    their = (Attribute)theirs.next();
                    mine = get(their.getID());
                    if (!their.equals(mine)) {
                        return false;
                    }
                }
            } catch (NamingException e) {
                return false;
            }
            return true;
        }
    }
    return false;
}
 
Example 13
Source File: GUISSOLdapClient.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private Map<String, String> formatEmailInfo(SearchResult sResult, String targetKey) {

    if (null == sResult) {
        return Collections.emptyMap();
    }

    Map<String, String> result = new LinkedHashMap<String, String>();
    try {
        NamingEnumeration namingEnumeration = sResult.getAttributes().getAll();
        while (namingEnumeration.hasMoreElements()) {
            Attribute attr = (Attribute) namingEnumeration.next();
            String attrId = attr.getID();
            String attrValue = attr.getAll().next().toString();
            if (targetKey.equals(attrId)) {
                result.put("email", attrValue);
            }
            if ("cn".equals(attrId)) {
                result.put("name", attrValue);
            }

            result.put(attrId, attrValue);
        }

    }
    catch (Exception e) {
        loggerError("formatEmailInfo 591", "", e);
    }

    return result;
}
 
Example 14
Source File: LdapGroupRealm.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public Set<String> getRoleNamesForUser(String username, LdapContext ldapContext,
        String userDnTemplate) throws NamingException {
  try {
    Set<String> roleNames = new LinkedHashSet<>();

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

    String searchFilter = "(&(objectClass=groupOfNames)(member=" + userDnTemplate + "))";
    Object[] searchArguments = new Object[]{username};

    NamingEnumeration<?> answer = ldapContext.search(
        String.valueOf(ldapContext.getEnvironment().get("ldap.searchBase")),
        searchFilter,
        searchArguments,
        searchCtls);

    while (answer.hasMoreElements()) {
      SearchResult sr = (SearchResult) answer.next();
      Attributes attrs = sr.getAttributes();
      if (attrs != null) {
        NamingEnumeration<?> ae = attrs.getAll();
        while (ae.hasMore()) {
          Attribute attr = (Attribute) ae.next();
          if (attr.getID().equals("cn")) {
            roleNames.add((String) attr.get());
          }
        }
      }
    }
    return roleNames;

  } catch (Exception e) {
    LOG.error("Error", e);
  }

  return new HashSet<>();
}
 
Example 15
Source File: BasicAttributes.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determines whether this <tt>BasicAttributes</tt> is equal to another
 * <tt>Attributes</tt>
 * Two <tt>Attributes</tt> are equal if they are both instances of
 * <tt>Attributes</tt>,
 * treat the case of attribute IDs the same way, and contain the
 * same attributes. Each <tt>Attribute</tt> in this <tt>BasicAttributes</tt>
 * is checked for equality using <tt>Object.equals()</tt>, which may have
 * be overridden by implementations of <tt>Attribute</tt>).
 * If a subclass overrides <tt>equals()</tt>,
 * it should override <tt>hashCode()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 * @param obj the possibly null object to compare against.
 *
 * @return true If obj is equal to this BasicAttributes.
 * @see #hashCode
 */
public boolean equals(Object obj) {
    if ((obj != null) && (obj instanceof Attributes)) {
        Attributes target = (Attributes)obj;

        // Check case first
        if (ignoreCase != target.isCaseIgnored()) {
            return false;
        }

        if (size() == target.size()) {
            Attribute their, mine;
            try {
                NamingEnumeration<?> theirs = target.getAll();
                while (theirs.hasMore()) {
                    their = (Attribute)theirs.next();
                    mine = get(their.getID());
                    if (!their.equals(mine)) {
                        return false;
                    }
                }
            } catch (NamingException e) {
                return false;
            }
            return true;
        }
    }
    return false;
}
 
Example 16
Source File: Organization2Activedirectory.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean update(Organizations organization)  throws Exception{
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+organization.getId()+"))", constraints);
		String oldDn="";
		String rdn="";
		if (results == null || !results.hasMore()) {
			return create(organization);
		}else{
			SearchResult sr = (SearchResult) results.next();
			oldDn =sr.getNameInNamespace();
			String[] dnSplit=oldDn.split(",");
			rdn=oldDn.substring(oldDn.indexOf(",")+1, oldDn.length());
			
			String ouName=dnSplit[0].split("=")[1];
			if(organization.getName()!=ouName){
				String newDn="ou="+organization.getName()+","+rdn;
				logger.debug("oldDn : "+oldDn);
				logger.debug("newDn : "+newDn);
				ldapUtils.getCtx().rename(oldDn, newDn);
				
				//ModificationItem[] modificationItems = new ModificationItem[1];
				//modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("ou",ouName));
				//modificationItems[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("name",organization.getName()));
				//ldapUtils.getCtx().modifyAttributes(newDn, modificationItems);
			}
		}
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return super.update(organization);
}
 
Example 17
Source File: Group2Activedirectory.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
@Override
public boolean addMember(GroupMember groupMember) throws Exception {
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(cn="+groupMember.getGroupName()+")", constraints);
		if (results == null || !results.hasMore()) {
			Groups  group =new Groups();
			group.setName(groupMember.getGroupName());
			return create(group);
		}
		
		
		String uniqueMember="";
		SearchControls memberSearchControls = new SearchControls();
		logger.debug("user Search : "+"(sAMAccountName="+groupMember.getMemberName()+")");
		memberSearchControls.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> memberResults = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(sAMAccountName="+groupMember.getMemberName()+")", memberSearchControls);
		if (memberResults == null || !memberResults.hasMore()) {
			
		}else{
			SearchResult memberSr = (SearchResult) memberResults.next();
			uniqueMember =memberSr.getNameInNamespace();
			logger.debug("uniqueMember : "+uniqueMember);
			ModificationItem[] modificationItems = new ModificationItem[1];
			modificationItems[0]=new ModificationItem(DirContext.ADD_ATTRIBUTE,new BasicAttribute("member",uniqueMember));
			
			String dn="cn="+groupMember.getGroupName()+",cn=groups,"+ldapUtils.getBaseDN();
			
			ldapUtils.getCtx().modifyAttributes(dn, modificationItems);
		}
		
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 18
Source File: LdapRolesMappingProvider.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected void rolesSearch(InitialLdapContext ctx, SearchControls constraints, String user, String previousRoleDn,
                           int recursionMax, int nesting, RoleGroup roleGroup) throws NamingException
{
   Object[] filterArgs = {user};
   String searchFilter = previousRoleDn == null ? roleFilter : "member=" + previousRoleDn;
   NamingEnumeration<SearchResult> results = ctx.search(rolesCtxDN, searchFilter, filterArgs, constraints);
   try
   {
      while (results.hasMore())
      {
         SearchResult sr = results.next();
         String dn = canonicalize(sr.getName());

         // Query the context for the roleDN values
         String[] attrNames = {roleAttributeID};
         Attributes result = ctx.getAttributes(dn, attrNames);
         if (result != null && result.size() > 0)
         {
            Attribute roles = result.get(roleAttributeID);
            for (int n = 0; n < roles.size(); n++)
            {
               String roleName = (String) roles.get(n);
               if (roleAttributeIsDN && parseRoleNameFromDN)
               {
                  parseRole(roleName, roleGroup);
               }
               else if (roleAttributeIsDN)
               {
                  // Query the roleDN location for the value of roleNameAttributeID
                  String roleDN = roleName;
                  String[] returnAttribute = {roleNameAttributeID};
                  PicketBoxLogger.LOGGER.traceFollowRoleDN(roleDN);
                  try
                  {
                     Attributes result2 = ctx.getAttributes(roleDN, returnAttribute);
                     Attribute roles2 = result2.get(roleNameAttributeID);
                     if (roles2 != null)
                     {
                        for (int m = 0; m < roles2.size(); m++)
                        {
                           roleName = (String) roles2.get(m);
                           addRole(roleName, roleGroup);
                        }
                     }
                  }
                  catch (NamingException e)
                  {
                     PicketBoxLogger.LOGGER.debugFailureToQueryLDAPAttribute(roleNameAttributeID, roleDN, e);
                  }
               }
               else
               {
                  // The role attribute value is the role name
                  addRole(roleName, roleGroup);
               }
            }
         }

         if (nesting < recursionMax)
         {
            rolesSearch(ctx, constraints, user, dn, recursionMax, nesting + 1, roleGroup);
         }
      }
   }
   finally
   {
      if (results != null)
         results.close();
   }
}
 
Example 19
Source File: ReadOnlyLDAPUserStoreManager.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Parse the search result of non group filtering and get the user list.
 *
 * @param answer
 * @param returnedAttributes
 * @return
 * @throws UserStoreException
 */
private List<String> getUserListFromNonGroupFilterResult(NamingEnumeration<SearchResult> answer,
                                                         List<String> returnedAttributes)
        throws UserStoreException {

    List<String> finalUserList = new ArrayList<>();
    String userAttributeSeparator = ",";
    NamingEnumeration<?> attrs = null;

    try {
        while (answer.hasMoreElements()) {
            SearchResult searchResult = answer.next();
            Attributes attributes = searchResult.getAttributes();
            if (attributes == null) {
                continue;
            }
            Attribute attribute = attributes.get(returnedAttributes.get(0));
            if (attribute == null) {
                continue;
            }
            StringBuffer attrBuffer = new StringBuffer();
            for (attrs = attribute.getAll(); attrs.hasMore(); ) {
                String attr = (String) attrs.next();
                if (StringUtils.isNotEmpty(attr.trim())) {
                    String attrSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                    if (StringUtils.isNotEmpty(attrSeparator.trim())) {
                        userAttributeSeparator = attrSeparator;
                    }
                    attrBuffer.append(attr + userAttributeSeparator);
                    if (log.isDebugEnabled()) {
                        log.debug(returnedAttributes.get(0) + " : " + attr);
                    }
                }
            }
            String propertyValue = attrBuffer.toString();
            Attribute serviceNameObject = attributes.get(returnedAttributes.get(1));
            String serviceNameAttributeValue = null;
            if (serviceNameObject != null) {
                serviceNameAttributeValue = (String) serviceNameObject.get();
            }
            /* Length needs to be more than userAttributeSeparator.length() for a valid attribute,
            since we attach userAttributeSeparator. */
            if (propertyValue.trim().length() > userAttributeSeparator.length()) {
                if (LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE.equals(serviceNameAttributeValue)) {
                    continue;
                }
                propertyValue = propertyValue.substring(0, propertyValue.length() -
                        userAttributeSeparator.length());
                finalUserList.add(propertyValue);
            }
        }
    } catch (NamingException e) {
        log.error(String.format("Error occurred while getting user list from non group filter %s", e.getMessage()));
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        // Close the naming enumeration and free up resources
        JNDIUtil.closeNamingEnumeration(attrs);
    }
    return finalUserList;
}
 
Example 20
Source File: GreenStepBaseAuthorizingActiveDirectoryCustomQueryAttributeRealm.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {
    final GreenStepBaseUsernamePasswordToken usernamePasswordToken = (GreenStepBaseUsernamePasswordToken) token;
    LdapContext ctx = null;
    /*
    try {
    	ctx = ldapContextFactory.getSystemLdapContext();
        final String attribName = "userPrincipalName";
        final SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, new String[] { attribName }, false, false);
        final NamingEnumeration<SearchResult> search = ctx.search(searchBase, this.getCustomQueryAttributeValue(), new Object[] { usernamePasswordToken.getPrincipal() }, searchControls);
        if (search.hasMore()) {
        	final SearchResult next = search.next();
            String loginUser= next.getAttributes().get(attribName).get().toString();
            if (search.hasMore()) {
                throw new RuntimeException("More than one user matching: "+usernamePasswordToken.getPrincipal());
            } else {
                try {
                	ldapContextFactory.getLdapContext(loginUser, usernamePasswordToken.getPassword());
                } catch (Exception ex) {
                    throw ex;
                }
            }
        }
        else {
            throw new RuntimeException("No user matching: " + usernamePasswordToken.getPrincipal());
        }
    } catch (NamingException ne) {
        throw ne;
    } finally {
        LdapUtils.closeContext(ctx);
    }
    */
    String searchBaseArr[] = StringUtils.defaultString(searchBase).split( Constants.ID_DELIMITER );
    boolean searchUser = false;
    for (int i = 0; searchBaseArr != null && !searchUser && i<searchBaseArr.length; i++) {
        try {
        	ctx = ldapContextFactory.getSystemLdapContext();
            final String attribName = "userPrincipalName";
            final SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, new String[] { attribName }, false, false);
            final NamingEnumeration<SearchResult> search = ctx.search(searchBaseArr[i], this.getCustomQueryAttributeValue(), new Object[] { usernamePasswordToken.getPrincipal() }, searchControls);
            if (search.hasMore()) {
            	searchUser = true;
            	final SearchResult next = search.next();
                String loginUser= next.getAttributes().get(attribName).get().toString();
                if (search.hasMore()) {
                    throw new RuntimeException("More than one user matching: "+usernamePasswordToken.getPrincipal());
                } else {
                    try {
                    	ldapContextFactory.getLdapContext(loginUser, usernamePasswordToken.getPassword());
                    } catch (Exception ex) {
                        throw ex;
                    }
                }
            }
            /*
            else {
                throw new RuntimeException("No user matching: " + usernamePasswordToken.getPrincipal());
            }
            */
        } catch (NamingException ne) {
            throw ne;
        } finally {
            LdapUtils.closeContext(ctx);
        }        	
    }
    if (!searchUser) {
    	throw new RuntimeException("No user matching: " + usernamePasswordToken.getPrincipal());
    }        
    return buildAuthenticationInfo(usernamePasswordToken.getUsername(), usernamePasswordToken.getPassword());
}