當前位置: 首頁>>代碼示例>>Java>>正文


Java DirContext.search方法代碼示例

本文整理匯總了Java中javax.naming.directory.DirContext.search方法的典型用法代碼示例。如果您正苦於以下問題:Java DirContext.search方法的具體用法?Java DirContext.search怎麽用?Java DirContext.search使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.naming.directory.DirContext的用法示例。


在下文中一共展示了DirContext.search方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getUserAttributes

import javax.naming.directory.DirContext; //導入方法依賴的package包/類
public static Map<String, String> getUserAttributes(DirContext ctx, String searchBase, String userName,
    String principalDomain, String... attributeNames)
    throws NamingException {
  if (StringUtils.isBlank(userName)) {
    throw new IllegalArgumentException("Username and password can not be blank.");
  }

  if (attributeNames.length == 0) {
    return Collections.emptyMap();
  }

  Attributes matchAttr = new BasicAttributes(true);
  BasicAttribute basicAttr = new BasicAttribute("userPrincipalName", userName + principalDomain);
  matchAttr.put(basicAttr);

  NamingEnumeration<? extends SearchResult> searchResult = ctx.search(searchBase, matchAttr, attributeNames);

  if (ctx != null) {
    ctx.close();
  }

  Map<String, String> result = new HashMap<>();

  if (searchResult.hasMore()) {
    NamingEnumeration<? extends Attribute> attributes = searchResult.next().getAttributes().getAll();

    while (attributes.hasMore()) {
      Attribute attr = attributes.next();
      String attrId = attr.getID();
      String attrValue = (String) attr.get();

      result.put(attrId, attrValue);
    }
  }
  return result;
}
 
開發者ID:SirAeroWN,項目名稱:premier-wherehows,代碼行數:37,代碼來源:AuthenticationManager.java

示例2: search

import javax.naming.directory.DirContext; //導入方法依賴的package包/類
/**
 * @return null if there are zero results
 */
private NamingEnumeration<SearchResult> search(DirContext ctx, Name base, String[] returnAttributes, Filter filter,
	boolean recurse)
{
	SearchControls ctls = new SearchControls();
	ctls.setCountLimit(filter.getLimit());
	ctls.setReturningAttributes(returnAttributes);
	ctls.setSearchScope(recurse ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);

	try
	{
		// Search for objects using the filter
		String query = filter.toFilter();
		if( LOGGER.isDebugEnabled() )
		{
			LOGGER.debug("Query:" + query + " Base:" + base);
		}
		NamingEnumeration<SearchResult> ne = ctx.search(base, query, ctls);
		if( ne.hasMore() )
		{
			return ne;
		}
	}
	catch( PartialResultException pre )
	{
		LOGGER.info(pre);
	}
	catch( SizeLimitExceededException slee )
	{
		LOGGER.info(slee);
	}
	catch( Exception e )
	{
		LOGGER.warn(e);
	}

	return null;
}
 
開發者ID:equella,項目名稱:Equella,代碼行數:41,代碼來源:LDAP.java

示例3: doGetGroups

import javax.naming.directory.DirContext; //導入方法依賴的package包/類
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;
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:29,代碼來源:LdapGroupsMapping.java

示例4: doGetGroups

import javax.naming.directory.DirContext; //導入方法依賴的package包/類
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;
}
 
開發者ID:nucypher,項目名稱:hadoop-oss,代碼行數:54,代碼來源:LdapGroupsMapping.java

示例5: searchByLimit

import javax.naming.directory.DirContext; //導入方法依賴的package包/類
private <T> List<T> searchByLimit(Properties properties, String baseDN,
        String filter, ILdapResultMapper<T> mapper, boolean checkAttribute,
        int searchLimit) throws NamingException {
    List<T> list = new ArrayList<T>();
    NamingEnumeration<SearchResult> namingEnum = null;

    DirContext ctx = getDirContext(properties);

    SearchControls ctls = new SearchControls();
    String[] attrIds = mapper.getAttributes();
    ctls.setReturningAttributes(attrIds);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setCountLimit(searchLimit);

    try {
        namingEnum = ctx.search(baseDN, escapeLDAPSearchFilter(filter),
                ctls);
        int count = 0;
        while (count++ < searchLimit && hasMoreEnum(namingEnum)) {
            SearchResult res = namingEnum.next();
            Attributes ldapAttributes = res.getAttributes();
            String[] values = new String[attrIds.length];
            for (int i = 0; i < values.length; i++) {
                Attribute ldapAttr = ldapAttributes
                        .get(escapeLDAPSearchFilter(attrIds[i]));
                if (checkAttribute && ldapAttr == null) {
                    NamingException e = new NamingException(
                            "Unknown LDAP attribute " + attrIds[i]);
                    throw e;
                }
                if (ldapAttr != null && ldapAttr.get() != null) {
                    values[i] = ldapAttr.get().toString();
                }
            }
            T t = mapper.map(values);
            if (t != null) {
                list.add(t);
            }
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } finally {
                closeContext(ctx);
            }
        }
        closeContext(ctx);
    }
    return list;
}
 
開發者ID:servicecatalog,項目名稱:oscm,代碼行數:52,代碼來源:LdapAccessServiceBean.java

示例6: getRolesRecursive

import javax.naming.directory.DirContext; //導入方法依賴的package包/類
/**
 * Add roles to a user and search for other roles containing them themselves.
 * We search recursively with a limited depth.
 * By default the depth is 0, and we only use direct roles.
 * The search needs to use the distinguished role names,
 * but to return the role names.
 *
 * @param depth Recursion depth, starting at zero
 * @param context The directory context we are searching
 * @param recursiveMap The cumulative result map of role names and DNs.
 * @param recursiveSet The cumulative result set of role names.
 * @param groupName The role name to add to the list.
 * @param groupDName The distinguished name of the role.
 *
 * @exception NamingException if a directory server error occurs
 */
private void getRolesRecursive(int depth, DirContext context, Map<String, String> recursiveMap, Set<String> recursiveSet,
                                 String groupName, String groupDName) throws NamingException {
    if (containerLog.isTraceEnabled())
        containerLog.trace("Recursive search depth " + depth + " for group '" + groupDName + " (" + groupName + ")'");
    // Adding the given group to the result set if not already found
    if (!recursiveSet.contains(groupDName)) {
        recursiveSet.add(groupDName);
        recursiveMap.put(groupDName, groupName);
        if (depth >= roleRecursionLimit) {
            if (roleRecursionLimit > 0)
                containerLog.warn("Terminating recursive role search because of recursion limit " +
                                  roleRecursionLimit + ", results might be incomplete");
            return;
        }
        // Prepare the parameters for searching groups
        String filter = roleFormat.format(new String[] { groupDName });
        SearchControls controls = new SearchControls();
        controls.setSearchScope(roleSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
        controls.setReturningAttributes(new String[] { roleName });
        if (containerLog.isTraceEnabled()) {
            containerLog.trace("Recursive search in role base '" + roleBase + "' for attribute '" + roleName + "'" +
                               " with filter expression '" + filter + "'");
        }
        // Searching groups that assign the given group
        NamingEnumeration results = context.search(roleBase, filter, controls);
        if (results != null) {
            // Iterate over the resulting groups
            try {
                while (results.hasMore()) {
                    SearchResult result = (SearchResult) results.next();
                    Attributes attrs = result.getAttributes();
                    if (attrs == null)
                        continue;
                    String dname = getDistinguishedName(context, roleBase, result);
                    String name = getAttributeValue(roleName, attrs);
                    if (name != null && dname != null) {
                       getRolesRecursive(depth+1, context, recursiveMap, recursiveSet, name, dname);
                    }
                }
            } catch (PartialResultException ex) {
                if (!adCompat)
                    throw ex;
            }
        }
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:63,代碼來源:JNDIRealm.java

示例7: moreLdapInjections

import javax.naming.directory.DirContext; //導入方法依賴的package包/類
public static void moreLdapInjections(String input) throws NamingException {
    //Stub instances
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, "ldap://ldap.example.com");
    props.put(Context.REFERRAL, "ignore");

    SearchControls ctrls = new SearchControls();
    ctrls.setReturningAttributes(new String[]{"givenName", "sn"});
    ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    //Various context instance store in various type (class or interface)
    DirContext         context1 = new InitialDirContext(props);
    InitialDirContext  context2 = new InitialDirContext(props);
    InitialLdapContext context3 = new InitialLdapContext();
    LdapContext        context4 = new InitialLdapContext();

    NamingEnumeration<SearchResult> answers;
    answers = context1.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context1.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context1.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context1.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);

    answers = context2.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context2.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context2.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context2.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);

    answers = context3.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context3.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context3.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context3.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);

    answers = context4.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context4.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context4.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context4.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);


    //False positive
    answers = context1.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=bob)", ctrls);
    answers = context1.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=bob)", new Object[0], ctrls);
    answers = context1.search("dc=People,dc=example,dc=com", "(uid=bob)", ctrls);
    answers = context1.search("dc=People,dc=example,dc=com", "(uid=bob)", new Object[0], ctrls);
}
 
開發者ID:blackarbiter,項目名稱:Android_Code_Arbiter,代碼行數:46,代碼來源:JndiLdapAdditionalSignature.java


注:本文中的javax.naming.directory.DirContext.search方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。