javax.naming.ldap.LdapContext#close ( )源码实例Demo

下面列出了javax.naming.ldap.LdapContext#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: uavstack   文件: GUISSOLdapClient.java
private void clearLdapContext(String action) {

        try {
            loggerInfo("LDAPContext", "清空", "开始", action);

            if (ldapContexts.containsKey(action)) {
                LdapContext context = ldapContexts.get(action);
                context.close();
                context = null;
                ldapContexts.remove(action);
            }

            loggerInfo("LDAPContext", "清空", "完成", action);
        }
        catch (Exception e) {
            loggerError("LDAPContext清空", action, e);
        }

    }
 
源代码2 项目: james-project   文件: ReadOnlyLDAPUser.java
/**
 * Verifies that the password supplied is actually the user's password, by
 * attempting to rebind to a copy of the LDAP server context using the user's 
 * username and the supplied password.
 * 
 * @param password
 *            The password to validate.
 * @return <code>True</code> if a connection can successfully be established
 *         to the LDAP host using the user's id and the supplied password,
 *         and <code>False</code> otherwise.
 */
@Override
public boolean verifyPassword(String password) {
    boolean result = false;
    LdapContext ldapContext = null;
    try {
        ldapContext = this.ldapContext.newInstance(null);
        ldapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION,
                LdapConstants.SECURITY_AUTHENTICATION_SIMPLE);
        ldapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
        ldapContext.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ldapContext.reconnect(null);
        result = true;
    } catch (NamingException exception) {
        // no-op
    } finally {
        if (null != ldapContext) {
            try {
                ldapContext.close();
            } catch (NamingException ex) {
                // no-op
            }
        }
    }
    return result;
}
 
源代码3 项目: seppb   文件: UserServiceImpl.java
private void ldapClose(LdapContext ctx) {
	if (null != ctx) {
		try {
			ctx.close();
		} catch (NamingException e) {
			log.error("认证服务关闭异常", e.getMessage());
		}
	}
}
 
源代码4 项目: pmq   文件: LdapUserService.java
private void doInitUser(Map<String, UserInfo> userInfos, Map<String, Organization> orgMap, String serverPath)
		throws NamingException {
	Properties env = new Properties();
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_PRINCIPAL, "corp\\" + soaConfig.getMqLdapUser());
	env.put(Context.SECURITY_CREDENTIALS, soaConfig.getMqLdapPass());
	env.put(Context.PROVIDER_URL, adServer.get());

	LdapContext ctx = new InitialLdapContext(env, null);
	SearchControls searchCtls = new SearchControls();
	searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

	String searchFilter = String
			.format("(&(objectClass=top)(objectClass=user)(objectClass=person)(objectClass=organizationalPerson))");

	String returnedAtts[] = { "memberOf", "sAMAccountName", "cn", "distinguishedName", "mail" };
	searchCtls.setReturningAttributes(returnedAtts);
	NamingEnumeration<SearchResult> answer = ctx.search(serverPath, searchFilter, searchCtls);
	while (answer.hasMoreElements()) {
		SearchResult sr = (SearchResult) answer.next();
		Attributes at = sr.getAttributes();
		UserInfo userInfo = new UserInfo();
		userInfo.setDepartment(getDValue(at.get("distinguishedName")));
		userInfo.setEmail(getValue(at.get("mail")));
		userInfo.setUserId(getValue(at.get("sAMAccountName")));
		userInfo.setName(getValue(at.get("cn")));
		userInfo.setAdmin(roleService.isAdmin(userInfo.getUserId()));
		userInfos.put(userInfo.getUserId(), userInfo);
		if (!StringUtils.isEmpty(userInfo.getDepartment())) {
			Organization organization = new Organization();
			organization.setOrgId(userInfo.getDepartment());
			orgMap.put(userInfo.getDepartment(), organization);
		}
	}
	ctx.close();
}
 
源代码5 项目: cosmic   文件: LdapManagerImpl.java
private void closeContext(final LdapContext context) {
    try {
        if (context != null) {
            context.close();
        }
    } catch (final NamingException e) {
        s_logger.warn(e.getMessage(), e);
    }
}
 
源代码6 项目: Openfire   文件: LdapGroupProvider.java
/**
 * Reads the group with the given DN
 *
 * @param groupDN         the absolute DN of the group
 * @param membersToIgnore A mutable set of DNs and/or UIDs (for Posix mode) to ignore. This set will be
 *                        filled with visited DNs. If flatten of hierarchies of groups is active
 *                        ({@link LdapManager#isFlattenNestedGroups()}, this will prevent endless loops
 *                        for cyclic hierarchies.
 * @return A group (never null)
 * @throws NamingException When a group can't be read from LDAP.
 */
private Group getGroupByDN(LdapName groupDN, Set<String> membersToIgnore) throws NamingException {
    LdapContext ctx = null;
    try {
        LdapName baseDN;
        Name relativeDN;
        if (manager.getAlternateBaseDN() != null
            && groupDN.startsWith(manager.getAlternateBaseDN())) {
            baseDN = manager.getAlternateBaseDN();
        } else if (groupDN.startsWith(manager.getBaseDN())) {
            baseDN = manager.getBaseDN();
        }
        else {
            throw new IllegalArgumentException("GroupDN does not match any baseDN");
        }
        relativeDN = groupDN.getSuffix(baseDN.size());
        membersToIgnore.add(groupDN.toString());
        // Load record.
        ctx = manager.getContext(baseDN);
        Attributes attrs = ctx.getAttributes(relativeDN, standardAttributes);

        return processGroup(ctx, attrs, membersToIgnore);
    }
    finally {
        try {
            if (ctx != null) {
                ctx.setRequestControls(null);
                ctx.close();
            }
        }
        catch (Exception ex) {
            Log.debug( "An exception was ignored while trying to close the Ldap context after trying to get a group.", ex );
        }
    }
}
 
源代码7 项目: cloudstack   文件: LdapManagerImpl.java
private void closeContext(final LdapContext context) {
    try {
        if (context != null) {
            context.close();
        }
    } catch (final NamingException e) {
        LOGGER.warn(e.getMessage(), e);
    }
}
 
源代码8 项目: radar   文件: LdapUserService.java
private void doInitUser(Map<String, UserBo> userInfos, Map<String, OrganizationBo> orgMap, String serverPath)
        throws NamingException {
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, soaConfig.getRadarLdapUser());
    env.put(Context.SECURITY_CREDENTIALS, soaConfig.getRadarLdapPass());
    env.put(Context.PROVIDER_URL, adServer.get());

    LdapContext ctx = new InitialLdapContext(env, null);
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String searchFilter = String
            .format("(&(objectClass=top)(objectClass=user)(objectClass=person)(objectClass=organizationalPerson))");

    String returnedAtts[] = { "memberOf", "sAMAccountName", "cn", "distinguishedName", "mail" };
    searchCtls.setReturningAttributes(returnedAtts);
    NamingEnumeration<SearchResult> answer = ctx.search(serverPath, searchFilter, searchCtls);
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();
        Attributes at = sr.getAttributes();
        UserBo userBo = new UserBo();
        userBo.setDepartment(getDValue(at.get("distinguishedName")));
        userBo.setEmail(getValue(at.get("mail")));
        userBo.setUserId(getValue(at.get("sAMAccountName")));
        userBo.setName(getValue(at.get("cn")));
        userBo.setAdmin(false);
        if ((","+soaConfig.getAdminUsers()+",").indexOf(","+userBo.getUserId()+",") != -1) {
            userBo.setAdmin(true);
        }
        userInfos.put(userBo.getUserId(), userBo);
        if (!StringUtils.isEmpty(userBo.getDepartment())) {
            OrganizationBo organization = new OrganizationBo();
            organization.setOrgId(userBo.getDepartment());
            organization.setOrgName(userBo.getDepartment());
            orgMap.put(userBo.getDepartment(), organization);
        }
    }
    ctx.close();
}
 
源代码9 项目: light-oauth2   文件: LdapAccessControl.java
@Override
public boolean hasRole(final String username, final String attribute) {
    final String key = username + "_attr_" + attribute;
    final long now = System.currentTimeMillis();

    try {
        if (!matchedExpired(key, now)) {
            return true;
        }

        if (!unMatchedExpired(key, now)) {
            return false;
        }

        // query AD to update both MapS and expiration time
        LOGGER.fine("username: " + username + "; role: " + attribute);

        this.writeLock.lock();
        try {
            // remove from cache if exists
            this.matchedList.remove(key);
            this.unMatchedList.remove(key);

            int count = 0;
            final LdapContext context = new InitialLdapContext(environment, null);
            for (String filter : this.policy) {
                // perform AD lookup add to cache 
                final NamingEnumeration<SearchResult> results =
                        context.search(this.deecee
                                , String.format(filter, username, attribute)
                                , this.srchCntrls);

                final boolean found = results.hasMoreElements();
                results.close();

                // add to cache
                if (found) {
                    count++;
                    //LOGGER.info("add attribute to matchedList: " + attribute);
                    this.matchedList.put(key, System.currentTimeMillis());
                    if (!this.uniqueOnly) {
                        break;
                    }
                }

                // check if we have a duplicate attribute
                if (count > 1 && this.uniqueOnly) {
                    this.matchedList.remove(key);
                    throw new IllegalArgumentException("Uniqueness property violated. "
                            + "Found duplicate role/attribute:" + attribute
                            + ". This MAY be caused by an improper policy definition"
                            + "; filter=" + filter
                            + "; policy=" + this.policy);
                }
            }
            context.close();

            if (0 == count) {
                //LOGGER.info("add attribute to unMatchedList: " + attribute);
                this.unMatchedList.put(key, System.currentTimeMillis());
            } else {
                cacheUserInfo(username);
            }

        } finally {
            this.writeLock.unlock();
        }
    } catch (NamingException lex) {
        LOGGER.severe(lex.getMessage());
        throw new RuntimeException(lex);
    }

    return hasRole(username, attribute);
}
 
源代码10 项目: Openfire   文件: LdapManager.java
/**
 * Generic routine for retrieving a single element from the LDAP server.  It's meant to be very
 * flexible so that just about any query for a single results can make use of it without having
 * to reimplement their own calls to LDAP.
 * <p>
 * The passed in filter string needs to be pre-prepared!  In other words, nothing will be changed
 * in the string before it is used as a string.
 *
 * @param attribute             LDAP attribute to be pulled from each result and placed in the return results.
 *                              Typically pulled from this manager. Null means the the absolute DN is returned.
 * @param searchFilter          Filter to use to perform the search.  Typically pulled from this manager.
 * @param failOnMultipleResults It true, an {@link IllegalStateException} will be thrown, if the
 *                              search result is not unique. If false, just the first result will be returned.
 * @param baseDN                DN where to start the search. Typically {@link #getBaseDN()} or {@link #getAlternateBaseDN()}.
 * @return A single string.
 */
public String retrieveSingle(String attribute, String searchFilter, boolean failOnMultipleResults, LdapName baseDN) {
    LdapContext ctx = null;
    try {
        ctx = getContext(baseDN);

        SearchControls searchControls = new SearchControls();
        // See if recursive searching is enabled. Otherwise, only search one level.
        if (isSubTreeSearch()) {
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        }
        else {
            searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        searchControls.setReturningAttributes(attribute == null ? new String[0] : new String[]{attribute});

        NamingEnumeration<SearchResult> answer = ctx.search("", searchFilter, searchControls);
        if (answer == null || !answer.hasMoreElements()) {
            return null;
        }
        SearchResult searchResult = answer.next();
        String result = attribute == null
            ? new LdapName(searchResult.getName()).addAll(0, baseDN).toString() :
            (String) searchResult.getAttributes().get(attribute).get();
        if (answer.hasMoreElements()) {
            Log.debug("Search result for '{}' is not unique.", searchFilter);
            if (failOnMultipleResults)
                throw new IllegalStateException("Search result for " + searchFilter + " is not unique.");
        }
        answer.close();
        return result;
    }
    catch (Exception e) {
        Log.error("Error while searching for single result of: {}", searchFilter, e);
        return null;
    }
    finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception ex) {
            Log.debug("An exception occurred while trying to close a LDAP context after trying to retrieve a single attribute element for {}.", attribute, ex);
        }
    }
}