Java Code Examples for javax.naming.NamingEnumeration.hasMoreElements()

The following are Jave code examples for showing how to use hasMoreElements() of the javax.naming.NamingEnumeration class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: uavstack   File: GUISSOLdapClient.java   View Source Code Vote up 6 votes
@SuppressWarnings("rawtypes")
private String formatEmailList(SearchResult sResult) {

    if (null == sResult) {
        return "";
    }

    StringBuilder emailList = new StringBuilder();
    try {
        NamingEnumeration namingEnumeration = sResult.getAttributes().getAll();
        while (namingEnumeration.hasMoreElements()) {
            Attribute attr = (Attribute) namingEnumeration.next();
            emailList.append(formatEmailInfo(attr));
        }

    }
    catch (NamingException e) {
        loggerError("formatEmailList", "", e);
    }

    return emailList.toString();

}
 
Example 2
Project: uavstack   File: GUISSOLdapClient.java   View Source Code Vote up 6 votes
@SuppressWarnings("rawtypes")
private List<String> formatUserEnName(SearchResult sResult) {

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

    List<String> result = new ArrayList<String>();
    try {
        String memberKey = ldapConfig.get("memberKey");
        NamingEnumeration namingEnumeration = sResult.getAttributes().getAll();
        while (namingEnumeration.hasMoreElements()) {
            Attribute attr = (Attribute) namingEnumeration.next();
            String attrId = attr.getID();
            if (memberKey.equals(attrId)) {
                List<String> userEnNames = formatUserEnName(attr);
                result.addAll(userEnNames);
            }
        }

    }
    catch (Exception e) {
        loggerError("formatUserEnName 619", "", e);
    }
    return result;
}
 
Example 3
Project: tomcat7   File: DirContextURLConnection.java   View Source Code Vote up 5 votes
/**
 * List children of this collection. The names given are relative to this
 * URI's path. The full uri of the children is then : path + "/" + name.
 */
public Enumeration<String> list()
    throws IOException {

    if (!connected) {
        connect();
    }

    if ((resource == null) && (collection == null)) {
        throw new FileNotFoundException(
                getURL() == null ? "null" : getURL().toString());
    }

    Vector<String> result = new Vector<String>();

    if (collection != null) {
        try {
            NamingEnumeration<NameClassPair> enumeration =
                collection.list("/");
            UEncoder urlEncoder = new UEncoder(UEncoder.SafeCharsSet.WITH_SLASH);
            while (enumeration.hasMoreElements()) {
                NameClassPair ncp = enumeration.nextElement();
                String s = ncp.getName();
                result.addElement(
                        urlEncoder.encodeURL(s, 0, s.length()).toString());
            }
        } catch (NamingException e) {
            // Unexpected exception
            throw new FileNotFoundException(
                    getURL() == null ? "null" : getURL().toString());
        }
    }

    return result.elements();

}
 
Example 4
Project: Equella   File: MemberOfGroupSearch.java   View Source Code Vote up 5 votes
public List<SubgroupResult> getParentGroups()
{
	if( !Check.isEmpty(memberOfField) )
	{
		Attribute attribute = attributes.get(memberOfField);
		if( attribute != null )
		{
			try
			{
				NamingEnumeration<?> atts = attribute.getAll();
				List<SubgroupResult> results = Lists.newArrayList();
				while( atts.hasMoreElements() )
				{
					String n = atts.nextElement().toString();
					Name parentGroupName = LDAP.parse(n);
					results.add(new SubgroupResult(parentGroupName, ldap.getAttributes(ctx,
						parentGroupName, returnAttributes)));
				}
				return results;
			}
			catch( NamingException e )
			{
				throw new RuntimeException(e);
			}
		}
	}
	else if( !Check.isEmpty(memberField) )
	{
		return ldap.searchAllBases(ctx, getMemberFilter(name.toString()),
			new SubgroupResultHitsCollector(), true);
	}
	return null;
}
 
Example 5
Project: lams   File: TldConfig.java   View Source Code Vote up 5 votes
private void tldScanResourcePathsWebInf(DirContext resources,
                                        String rootPath,
                                        Set tldPaths) 
        throws IOException {

    if (log.isTraceEnabled()) {
        log.trace("  Scanning TLDs in " + rootPath + " subdirectory");
    }

    try {
        NamingEnumeration items = resources.list(rootPath);
        while (items.hasMoreElements()) {
            NameClassPair item = (NameClassPair) items.nextElement();
            String resourcePath = rootPath + "/" + item.getName();
            if (!resourcePath.endsWith(".tld")
                    && (resourcePath.startsWith("/WEB-INF/classes")
                        || resourcePath.startsWith("/WEB-INF/lib"))) {
                continue;
            }
            if (resourcePath.endsWith(".tld")) {
                if (log.isTraceEnabled()) {
                    log.trace("   Adding path '" + resourcePath + "'");
                }
                tldPaths.add(resourcePath);
            } else {
                tldScanResourcePathsWebInf(resources, resourcePath,
                                           tldPaths);
            }
        }
    } catch (NamingException e) {
        ; // Silent catch: it's valid that no /WEB-INF directory exists
    }
}
 
Example 6
Project: lams   File: DirContextURLConnection.java   View Source Code Vote up 5 votes
/**
 * List children of this collection. The names given are relative to this
 * URI's path. The full uri of the children is then : path + "/" + name.
 */
public Enumeration list()
    throws IOException {
    
    if (!connected) {
        connect();
    }
    
    if ((resource == null) && (collection == null)) {
        throw new FileNotFoundException();
    }
    
    Vector result = new Vector();
    
    if (collection != null) {
        try {
            NamingEnumeration enumeration = context.list(getURL().getFile());
            while (enumeration.hasMoreElements()) {
                NameClassPair ncp = (NameClassPair) enumeration.nextElement();
                result.addElement(ncp.getName());
            }
        } catch (NamingException e) {
            // Unexpected exception
            throw new FileNotFoundException();
        }
    }
    
    return result.elements();
    
}
 
Example 7
Project: jerrydog   File: DirContextURLConnection.java   View Source Code Vote up 5 votes
/**
 * List children of this collection. The names given are relative to this
 * URI's path. The full uri of the children is then : path + "/" + name.
 */
public Enumeration list()
    throws IOException {
    
    if (!connected) {
        connect();
    }
    
    if ((resource == null) && (collection == null)) {
        throw new FileNotFoundException();
    }
    
    Vector result = new Vector();
    
    if (collection != null) {
        try {
            NamingEnumeration _enum = context.list(getURL().getFile());

            while (_enum.hasMoreElements()) {
                NameClassPair ncp = (NameClassPair) _enum.nextElement();
                result.addElement(ncp.getName());
            }
        } catch (NamingException e) {
            // Unexpected exception
            throw new FileNotFoundException();
        }
    }
    
    return result.elements();
    
}
 
Example 8
Project: ChronoBike   File: LdapRequester.java   View Source Code Vote up 5 votes
/**
 * @param csUser: specific user we want to login
 * @param csPassword: specific password
 * @param bUseGenericUser: true if connecting using generic user, not the specific user (csUser / csPassword); in that case csUser/csPassword is ignored   
 * @return String UserDN; set to null or empty if user did not login correctly.
 */
public String getUserLogin(String csUser, String csPassword, boolean bUseGenericUser)
{
	String csUserLogin = csUser;
	String csPasswordLogin = csPassword;
	if (bUseGenericUser)
	{
		csUserLogin = m_csLDAPGenericUser;
		csPasswordLogin = m_csLDAPGenericPassword;
	}
	
	if (!validateLogin(csUserLogin, csPasswordLogin))
	{
		return null ;
	}
	if (m_ldap == null)
	{
		return null ;
	}
	
	NamingEnumeration enumer = m_ldap.searchSubtree(m_csLDAPRootOU, "sAMAccountName="+csUser) ;
	if (enumer.hasMoreElements())
	{
		SearchResult res = (SearchResult)enumer.nextElement() ;
		String name = res.getNameInNamespace() ;
		return name ;
	}
	return null;
}
 
Example 9
Project: apache-tomcat-7.0.73-with-comment   File: DirContextURLConnection.java   View Source Code Vote up 5 votes
/**
 * List children of this collection. The names given are relative to this
 * URI's path. The full uri of the children is then : path + "/" + name.
 */
public Enumeration<String> list()
    throws IOException {

    if (!connected) {
        connect();
    }

    if ((resource == null) && (collection == null)) {
        throw new FileNotFoundException(
                getURL() == null ? "null" : getURL().toString());
    }

    Vector<String> result = new Vector<String>();

    if (collection != null) {
        try {
            NamingEnumeration<NameClassPair> enumeration =
                collection.list("/");
            UEncoder urlEncoder = new UEncoder(UEncoder.SafeCharsSet.WITH_SLASH);
            while (enumeration.hasMoreElements()) {
                NameClassPair ncp = enumeration.nextElement();
                String s = ncp.getName();
                result.addElement(
                        urlEncoder.encodeURL(s, 0, s.length()).toString());
            }
        } catch (NamingException e) {
            // Unexpected exception
            throw new FileNotFoundException(
                    getURL() == null ? "null" : getURL().toString());
        }
    }

    return result.elements();

}
 
Example 10
Project: hadoop   File: LdapGroupsMapping.java   View Source Code Vote up 5 votes
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
Project: uavstack   File: GUISSOLdapClient.java   View Source Code Vote up 5 votes
private List<SearchResult> ldapApiQuery(String action, String name, String filter) {

        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 12
Project: uavstack   File: GUISSOLdapClient.java   View Source Code Vote up 5 votes
@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);
            }
        }

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

    return result;
}
 
Example 13
Project: openshift-ldapsync   File: LdapGroupConverter.java   View Source Code Vote up 5 votes
@Override
public Optional<Group> convert(final String dn, final Attributes ldapGroup) throws NamingException {
    LOG.info("Working on LDAP group: {}", dn);
    GroupBuilder builder = new GroupBuilder()
            .withDn(dn)
            .withLdapServer(server.getName())
            .withOcpName(calculateOCPGroupName(ldapGroup));


    try {
        @SuppressWarnings("unchecked")
        NamingEnumeration<String> members = (NamingEnumeration<String>) ldapGroup.get(MEMBER_ATTRIBUTE).getAll();
        LOG.info("Group has members: group={}, members={}", dn, members);

        while (members.hasMoreElements()) {
            String memberDn = members.nextElement();
            LOG.debug("Working on member: {}", memberDn);

            Attributes memberEntry = server.getByDn(memberDn);

            if (isUser(memberEntry)) {
                LOG.trace("Member is an user: dn={}", memberDn);
                Optional<User> memberUser = userConverter.convert(memberDn, memberEntry);
                memberUser.ifPresent(builder::addUser);
            } else { /* need to load the new group data ... */
                LOG.trace("Member is a group: dn={}", memberDn);
                Optional<Group> memberGroup = convert(memberDn, memberEntry);
                memberGroup.ifPresent(builder::addGroup);
            }
        }
    } catch (NullPointerException e) {
        LOG.debug("LDAP Group has no members: {}", dn);
    }

    return Optional.of(builder.build());
}
 
Example 14
Project: lazycat   File: DirContextURLConnection.java   View Source Code Vote up 5 votes
/**
 * List children of this collection. The names given are relative to this
 * URI's path. The full uri of the children is then : path + "/" + name.
 */
public Enumeration<String> list() throws IOException {

	if (!connected) {
		connect();
	}

	if ((resource == null) && (collection == null)) {
		throw new FileNotFoundException(getURL() == null ? "null" : getURL().toString());
	}

	Vector<String> result = new Vector<String>();

	if (collection != null) {
		try {
			NamingEnumeration<NameClassPair> enumeration = collection.list("/");
			UEncoder urlEncoder = new UEncoder(UEncoder.SafeCharsSet.WITH_SLASH);
			while (enumeration.hasMoreElements()) {
				NameClassPair ncp = enumeration.nextElement();
				String s = ncp.getName();
				result.addElement(urlEncoder.encodeURL(s, 0, s.length()).toString());
			}
		} catch (NamingException e) {
			// Unexpected exception
			throw new FileNotFoundException(getURL() == null ? "null" : getURL().toString());
		}
	}

	return result.elements();

}
 
Example 15
Project: hadoop-oss   File: LdapGroupsMapping.java   View Source Code Vote up 4 votes
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 = null;

    if (isPosix) {
      String gidNumber = null;
      String uidNumber = null;
      Attribute gidAttribute = result.getAttributes().get(posixGidAttr);
      Attribute uidAttribute = result.getAttributes().get(posixUidAttr);
      if (gidAttribute != null) {
        gidNumber = gidAttribute.get().toString();
      }
      if (uidAttribute != null) {
        uidNumber = uidAttribute.get().toString();
      }
      if (uidNumber != null && gidNumber != null) {
        groupResults =
            ctx.search(baseDN,
                "(&"+ groupSearchFilter + "(|(" + posixGidAttr + "={0})" +
                    "(" + groupMemberAttr + "={1})))",
                new Object[] { gidNumber, uidNumber },
                SEARCH_CONTROLS);
      }
    } else {
      groupResults =
          ctx.search(baseDN,
              "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
              new Object[]{userDn},
              SEARCH_CONTROLS);
    }
    if (groupResults != null) {
      while (groupResults.hasMoreElements()) {
        SearchResult groupResult = groupResults.nextElement();
        Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
        groups.add(groupName.get().toString());
      }
    }
  }

  return groups;
}
 
Example 16
Project: directory-ldap-api   File: AttributeUtils.java   View Source Code Vote up 4 votes
/**
 * Check if the attributes is a BasicAttributes, and if so, switch
 * the case sensitivity to false to avoid tricky problems in the server.
 * (Ldap attributeTypes are *always* case insensitive)
 * 
 * @param attributes The Attributes to check
 * @return The modified Attributes
 */
public static Attributes toCaseInsensitive( Attributes attributes )
{
    if ( attributes == null )
    {
        return attributes;
    }

    if ( attributes instanceof BasicAttributes )
    {
        if ( attributes.isCaseIgnored() )
        {
            // Just do nothing if the Attributes is already case insensitive
            return attributes;
        }
        else
        {
            // Ok, bad news : we have to create a new BasicAttributes
            // which will be case insensitive
            Attributes newAttrs = new BasicAttributes( true );

            NamingEnumeration<?> attrs = attributes.getAll();

            if ( attrs != null )
            {
                // Iterate through the attributes now
                while ( attrs.hasMoreElements() )
                {
                    newAttrs.put( ( javax.naming.directory.Attribute ) attrs.nextElement() );
                }
            }

            return newAttrs;
        }
    }
    else
    {
        // we can safely return the attributes if it's not a BasicAttributes
        return attributes;
    }
}