Example usage for javax.naming.ldap LdapContext close

List of usage examples for javax.naming.ldap LdapContext close

Introduction

In this page you can find the example usage for javax.naming.ldap LdapContext close.

Prototype

public void close() throws NamingException;

Source Link

Document

Closes this context.

Usage

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserExporterImpl.java

@Override
public void exportUser(User user, Map<String, Serializable> userExpandoAttributes) throws Exception {

    if (user.isDefaultUser() || (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {

        return;/*from  w  ww .  j  ava2  s  .co  m*/
    }

    long companyId = user.getCompanyId();

    if (!_ldapSettings.isExportEnabled(companyId)) {
        return;
    }

    long ldapServerId = _portalLDAP.getLdapServerId(companyId, user.getScreenName(), user.getEmailAddress());

    LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

    try {
        if (ldapContext == null) {
            return;
        }

        Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);
        Properties userExpandoMappings = _ldapSettings.getUserExpandoMappings(ldapServerId, companyId);

        Binding binding = _portalLDAP.getUser(ldapServerId, user.getCompanyId(), user.getScreenName(),
                user.getEmailAddress(), true);

        if (binding == null) {
            binding = addUser(ldapServerId, ldapContext, user, userMappings);
        } else {
            Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext,
                    binding.getNameInNamespace());

            String modifyTimestamp = LDAPUtil.getAttributeString(attributes, "modifyTimestamp");

            if (Validator.isNotNull(modifyTimestamp)) {
                Date modifiedDate = LDAPUtil.parseDate(modifyTimestamp);

                if (modifiedDate.equals(user.getModifiedDate())) {
                    if (_log.isDebugEnabled()) {
                        _log.debug("Skipping user " + user.getEmailAddress()
                                + " because he is already synchronized");
                    }

                    return;
                }
            }
        }

        Name name = new CompositeName();

        name.add(binding.getNameInNamespace());

        Modifications modifications = _portalToLDAPConverter.getLDAPUserModifications(user,
                userExpandoAttributes, userMappings, userExpandoMappings);

        if (modifications == null) {
            return;
        }

        ModificationItem[] modificationItems = modifications.getItems();

        ldapContext.modifyAttributes(name, modificationItems);

        if (!_ldapSettings.isExportGroupEnabled(companyId)) {
            return;
        }

        List<UserGroup> userGroups = _userGroupLocalService.getUserUserGroups(user.getUserId());

        for (UserGroup userGroup : userGroups) {
            exportUser(user.getUserId(), userGroup.getUserGroupId(), UserOperation.ADD);
        }

        Modifications groupModifications = _portalToLDAPConverter.getLDAPUserGroupModifications(ldapServerId,
                userGroups, user, userMappings);

        ModificationItem[] groupModificationItems = groupModifications.getItems();

        if (groupModificationItems.length > 0) {
            ldapContext.modifyAttributes(name, groupModificationItems);
        }
    } catch (NameNotFoundException nnfe) {
        LDAPAuthConfiguration ldapAuthConfiguration = _ldapAuthConfigurationProvider
                .getConfiguration(companyId);

        if (ldapAuthConfiguration.required()) {
            throw nnfe;
        }

        _log.error(nnfe, nnfe);
    } finally {
        if (ldapContext != null) {
            ldapContext.close();
        }
    }
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

@Override
public User importUser(long ldapServerId, long companyId, String emailAddress, String screenName)
        throws Exception {

    LdapContext ldapContext = null;

    NamingEnumeration<SearchResult> enu = null;

    try {/*from   ww w .  ja v  a  2 s .  c o  m*/
        LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider
                .getConfiguration(companyId, ldapServerId);

        String baseDN = ldapServerConfiguration.baseDN();

        ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

        if (ldapContext == null) {
            _log.error("Unable to bind to the LDAP server");

            return null;
        }

        String filter = ldapServerConfiguration.authSearchFilter();

        if (_log.isDebugEnabled()) {
            _log.debug("Search filter before transformation " + filter);
        }

        filter = StringUtil.replace(filter, new String[] { "@company_id@", "@email_address@", "@screen_name@" },
                new String[] { String.valueOf(companyId), emailAddress, screenName });

        LDAPUtil.validateFilter(filter);

        if (_log.isDebugEnabled()) {
            _log.debug("Search filter after transformation " + filter);
        }

        Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

        String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName"));

        userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName);

        SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0,
                new String[] { userMappingsScreenName }, false, false);

        enu = ldapContext.search(baseDN, filter, searchControls);

        if (enu.hasMoreElements()) {
            if (_log.isDebugEnabled()) {
                _log.debug("Search filter returned at least one result");
            }

            Binding binding = enu.nextElement();

            Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext,
                    binding.getNameInNamespace());

            return importUser(ldapServerId, companyId, ldapContext, attributes, null);
        } else {
            return null;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn("Problem accessing LDAP server " + e.getMessage());
        }

        if (_log.isDebugEnabled()) {
            _log.debug(e, e);
        }

        throw new SystemException("Problem accessing LDAP server " + e.getMessage());
    } finally {
        if (enu != null) {
            enu.close();
        }

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

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will query the LDAP with the supplied dn, filter, filter arguments,
 * and search controls. See {@link #search(String, String, Object[],
 * SearchControls, SearchResultHandler...)}. The PagedResultsControl is used
 * in conjunction with {@link LdapConfig#getPagedResultsSize()} to produce the
 * results.//from   ww w . j a  va  2  s .  co m
 *
 * @param  dn  <code>String</code> name to begin search at
 * @param  filter  <code>String</code> expression to use for the search
 * @param  filterArgs  <code>Object[]</code> to substitute for variables in
 * the filter
 * @param  searchControls  <code>SearchControls</code> to perform search with
 * @param  handler  <code>SearchResultHandler[]</code> to post process results
 *
 * @return  <code>Iterator</code> - of LDAP search results
 *
 * @throws  NamingException  if the LDAP returns an error
 */
protected Iterator<SearchResult> pagedSearch(final String dn, final String filter, final Object[] filterArgs,
        final SearchControls searchControls, final SearchResultHandler... handler) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Paginated search with the following parameters:");
        this.logger.debug("  dn = " + dn);
        this.logger.debug("  filter = " + filter);
        this.logger.debug("  filterArgs = " + Arrays.toString(filterArgs));
        this.logger.debug("  searchControls = " + searchControls);
        this.logger.debug("  handler = " + Arrays.toString(handler));
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    final List<SearchResult> results = new ArrayList<SearchResult>();
    LdapContext ctx = null;
    NamingEnumeration<SearchResult> en = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                byte[] cookie = null;
                ctx = this.getContext();
                ctx.setRequestControls(new Control[] {
                        new PagedResultsControl(this.config.getPagedResultsSize(), Control.CRITICAL), });
                do {
                    List<SearchResult> pagedResults = null;
                    en = ctx.search(dn, filter, filterArgs, searchControls);

                    if (handler != null && handler.length > 0) {
                        final SearchCriteria sc = new SearchCriteria();
                        if (ctx != null && !"".equals(ctx.getNameInNamespace())) {
                            sc.setDn(ctx.getNameInNamespace());
                        } else {
                            sc.setDn(dn);
                        }
                        sc.setFilter(filter);
                        sc.setFilterArgs(filterArgs);
                        if (searchControls != null) {
                            sc.setReturnAttrs(searchControls.getReturningAttributes());
                        }
                        for (int j = 0; j < handler.length; j++) {
                            if (j == 0) {
                                pagedResults = handler[j].process(sc, en,
                                        this.config.getHandlerIgnoreExceptions());
                            } else {
                                pagedResults = handler[j].process(sc, pagedResults);
                            }
                        }
                    } else {
                        pagedResults = SR_COPY_RESULT_HANDLER.process(null, en,
                                this.config.getHandlerIgnoreExceptions());
                    }

                    results.addAll(pagedResults);

                    final Control[] controls = ctx.getResponseControls();
                    if (controls != null) {
                        for (int j = 0; j < controls.length; j++) {
                            if (controls[j] instanceof PagedResultsResponseControl) {
                                final PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[j];
                                cookie = prrc.getCookie();
                            }
                        }
                    }

                    // re-activate paged results
                    ctx.setRequestControls(
                            new Control[] { new PagedResultsControl(this.config.getPagedResultsSize(), cookie,
                                    Control.CRITICAL), });

                } while (cookie != null);

                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            } catch (IOException e) {
                if (this.logger.isErrorEnabled()) {
                    this.logger.error("Could not encode page size into control", e);
                }
                throw new NamingException(e.getMessage());
            }
        }
    } finally {
        if (en != null) {
            en.close();
        }
        if (ctx != null) {
            ctx.close();
        }
    }
    return results.iterator();
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Gets all persons for a group//from ww w.j av  a  2  s . c om
 * 
 * @param groups
 * @param siteBean
 * @param filter
 * @return
 * @throws Exception
 */
static List<TPersonBean> getAllLdapUsersDescendants(String providerUrl, String bindDN, String bindPassword,
        String loginAttributeName, String filter) throws Exception {
    List<TPersonBean> personBeans = new ArrayList<TPersonBean>();
    if (filter == null || "".equals(filter) || "*".equals(filter)) {
        filter = loginAttributeName + "=*";
    }
    int recordCount = 0;
    SearchControls ctls = null;
    LdapContext ctx = null;
    try {
        ctx = getInitialContext(providerUrl, bindDN, bindPassword);
        if (ctx == null) {
            return personBeans;
        }
        // Activate paged results
        int pageSize = 5;
        // TODO replace for GROOVY
        ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;
        String searchStr = "(" + filter + ")";
        // Control the search
        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle
                                                                                                                                                                     // anyways
        if (ldapMap == null || ldapMap.isEmpty()) {
            LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
            return personBeans;
        }
        String firstNameAttributeName = ldapMap.get("firstName");
        String lastNameAttributName = ldapMap.get("lastName");
        String emailAttributeName = ldapMap.get("email");
        String phoneAttributName = ldapMap.get("phone");
        byte[] cookie = null;
        // TODO replace for GROOVY
        cookie = new byte[] {};
        // cookie = [] as byte[];
        while (cookie != null) {
            NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls);
            while (results != null && results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName,
                        lastNameAttributName, emailAttributeName, phoneAttributName);
                if (personBean != null) {
                    personBeans.add(personBean);
                    ++recordCount;
                }
            }
            // Examine the paged results control response
            Control[] controls = ctx.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                    + ") *****************\n");
                        } else {
                            LOGGER.debug(
                                    "***************** END-OF-PAGE " + "(total: unknown) ***************\n");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                LOGGER.debug("No controls were sent from the server");
            }
            // Re-activate paged results
            // TODO replace for GROOVY
            ctx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
        }
    } catch (SizeLimitExceededException sle) {
        if (recordCount < ctls.getCountLimit()) {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
            LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                    + sle.getMessage());
            LOGGER.error(
                    "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
        } else {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                    + recordCount + ").");
            LOGGER.error(
                    "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
        }
        LOGGER.error("The LDAP synchronization is most likely incomplete.");
    } catch (NamingException e) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException ie) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(ie));
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
    return personBeans;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Returns a HashMap <login name, TPersonBean> for all LDAP objects found in
 * the directory und the DN configured in the Genji server configuration.
 * //from   w w w  .  j a va  2 s. c  o m
 * @return Map with <login name, TPersonBean>
 */
public static HashMap<String, TPersonBean> getAllLdapPersonsPaged(TSiteBean siteBean, String filter)
        throws Exception {
    if (filter == null || "".equals(filter) || "*".equals(filter)) {
        filter = siteBean.getLdapAttributeLoginName() + "=*";
    }
    if (!(filter.startsWith("(") && filter.endsWith(")"))) {
        filter = "(" + filter + ")";
    }
    LOGGER.debug("User filter expression " + filter);
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    HashMap<String, TPersonBean> ldapPersonsMap = new HashMap<String, TPersonBean>();
    LdapContext context = getInitialContext(siteBean.getLdapServerURL(), bindDN, bindPassword);
    if (context == null) {
        return ldapPersonsMap;
    }
    int recordCount = 0;
    // Create initial context
    // Control the search
    SearchControls ctls = null;
    try {
        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;
        // Control the search
        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle
                                                                                                                                                                     // anyways
        if (ldapMap == null || ldapMap.isEmpty()) {
            LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
            return null;
        }
        String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME);
        String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME);
        String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL);
        String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE);
        String loginAttributeName = siteBean.getLdapAttributeLoginName();
        do {
            /* perform the search */
            NamingEnumeration<SearchResult> results = context.search("", filter, ctls);
            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                // Attributes atrs = sr.getAttributes();
                TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName,
                        lastNameAttributName, emailAttributeName, phoneAttributName);
                if (personBean != null) {
                    ldapPersonsMap.put(personBean.getLoginName(), personBean);
                }
                ++recordCount;
            }
            // Examine the paged results control response
            Control[] controls = context.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                    + ") *****************\n");
                        } else {
                            LOGGER.debug(
                                    "***************** END-OF-PAGE " + "(total: unknown) ***************\n");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                LOGGER.debug("No controls were sent from the server");
            }
            // Re-activate paged results
            context.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);
    } catch (SizeLimitExceededException sle) {
        if (recordCount < ctls.getCountLimit()) {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
            LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                    + sle.getMessage());
            LOGGER.error(
                    "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
        } else {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                    + recordCount + ").");
            LOGGER.error(
                    "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
        }
        LOGGER.error("The LDAP synchronization is most likely incomplete.");
    } catch (NamingException e) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException ie) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(ie));
    } finally {
        if (context != null) {
            context.close();
        }
    }
    return ldapPersonsMap;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Get all ldap groups//from  w w w  .  j  a v a2 s . co m
 * 
 * @param siteBean
 * @param baseDnGroup
 * @param ldapFilterGroups
 * @param groupAttributeName
 * @param groupToMemberReferencesMap
 * @return
 * @throws Exception
 */
public static Map<String, TPersonBean> getLdapGroupsByList(String baseURL, TSiteBean siteBean,
        String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap,
        Map<String, String> groups) throws Exception {
    HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>();
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER);
    if (groupMemberAttributName == null) {
        LOGGER.debug(
                "No groupMember attribute defined in quartz-jobs.xml. Fall back to " + DEFAULT_GROUP_MEMBER);
        groupMemberAttributName = DEFAULT_GROUP_MEMBER;
    }
    LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword);
    if (baseContext == null) {
        LOGGER.warn("Context is null for baseURL " + baseURL);
        return ldapGroupsMap;
    }
    for (Map.Entry<String, String> groupEntry : groups.entrySet()) {
        String groupName = groupEntry.getKey();
        String groupDN = groupEntry.getValue();
        int index = groupDN.indexOf(",");
        if (index != -1) {
            String searchPart = groupDN.substring(0, index);
            String searchStr = "(" + searchPart + ")";
            String parentDNPart = groupDN.substring(index + 1);
            LdapContext context = (LdapContext) baseContext.lookup(parentDNPart);
            if (context == null) {
                LOGGER.warn("Context is null after lookup for " + parentDNPart);
                continue;
            }
            int recordCount = 0;
            SearchControls ctls = null;
            try {
                // Activate paged results
                int pageSize = 5;
                byte[] cookie = null;
                context.setRequestControls(
                        new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
                int total;
                // Control the search
                ctls = new SearchControls();
                ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                        + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can
                                                                                                                                                                             // handle anyways
                do {
                    /* perform the search */
                    NamingEnumeration<SearchResult> results = context.search("", searchStr, ctls);
                    /*
                     * for each entry print out name + all attrs and values
                     */
                    while (results != null && results.hasMore()) {
                        SearchResult searchResult = (SearchResult) results.next();
                        // Attributes atrs = sr.getAttributes();
                        Attributes attributes = searchResult.getAttributes();
                        if (attributes == null) {
                            LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName());
                            continue;
                        }
                        TPersonBean personBean = new TPersonBean();
                        try {
                            personBean.setLoginName(groupName);
                            ldapGroupsMap.put(personBean.getLoginName(), personBean);
                            Attribute memberAttribute = attributes.get(groupMemberAttributName);
                            if (memberAttribute != null) {
                                NamingEnumeration<?> members = memberAttribute.getAll();
                                while (members != null && members.hasMore()) {
                                    String memberSearchResult = (String) members.next();
                                    List<String> memberDNList = groupToMemberReferencesMap.get(groupName);
                                    if (memberDNList == null) {
                                        memberDNList = new ArrayList<String>();
                                        groupToMemberReferencesMap.put(groupName, memberDNList);
                                    }
                                    LOGGER.debug("Member found: " + memberSearchResult);
                                    memberDNList.add(memberSearchResult);
                                }
                            } else {
                                LOGGER.info("Could not find value(s) for group member attribute "
                                        + groupMemberAttributName + " for group " + groupName);
                            }
                            LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get());
                            LOGGER.debug("Processed group " + groupName);
                        } catch (Exception e) {
                            LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage());
                            LOGGER.warn(
                                    "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml");
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Stack trace:", e);
                            }
                        }
                        ++recordCount;
                    }
                    // Examine the paged results control response
                    Control[] controls = context.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                            + ") *****************\n");
                                } else {
                                    LOGGER.debug("***************** END-OF-PAGE "
                                            + "(total: unknown) ***************\n");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOGGER.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    context.setRequestControls(
                            new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

                } while (cookie != null);
            } catch (SizeLimitExceededException sle) {
                if (recordCount < ctls.getCountLimit()) {
                    LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
                    LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                            + sle.getMessage());
                    LOGGER.error(
                            "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
                } else {
                    LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                            + recordCount + ").");
                    LOGGER.error(
                            "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
                }
                LOGGER.error("The LDAP synchronization is most likely incomplete.");
            } catch (NamingException e) {
                LOGGER.error("PagedSearch failed.");
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            } catch (IOException ie) {
                LOGGER.error("PagedSearch failed.");
                LOGGER.debug(ExceptionUtils.getStackTrace(ie));
            } finally {
                context.close();
            }
        }
    }
    return ldapGroupsMap;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Get all ldap groups//from w  w w  .ja  va2  s.  c o  m
 * 
 * @param siteBean
 * @param baseDnGroup
 * @param ldapFilterGroups
 * @param groupAttributeName
 * @param groupToMemberReferencesMap
 * @return
 * @throws Exception
 */
public static Map<String, TPersonBean> getLdapGroupsPaged(String baseURL, TSiteBean siteBean,
        String baseDnGroup, String ldapFilterGroups, String groupAttributeName,
        Map<String, List<String>> groupToMemberReferencesMap) throws Exception {
    if (ldapFilterGroups == null || "".equals(ldapFilterGroups) || "*".equals(ldapFilterGroups)) {
        ldapFilterGroups = "(" + groupAttributeName + "=*)";
    }
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    LdapContext context = getInitialContext(baseURL + baseDnGroup, bindDN, bindPassword);
    HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>();
    if (context == null) {
        LOGGER.warn("Context is null");
        return ldapGroupsMap;
    }
    int recordCount = 0;
    SearchControls ctls = null;
    String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER);
    if (groupMemberAttributName == null) {
        groupMemberAttributName = DEFAULT_GROUP_MEMBER;
    }
    try {
        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;
        // Control the search
        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle
                                                                                                                                                                     // anyways
        do {
            /* perform the search */
            NamingEnumeration<SearchResult> results = context.search("", ldapFilterGroups, ctls);
            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                // Attributes atrs = sr.getAttributes();
                Attributes attributes = searchResult.getAttributes();
                if (attributes == null) {
                    LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName());
                    return null;
                }
                TPersonBean personBean = new TPersonBean();
                try {
                    Attribute groupNameAttribute = attributes.get(groupAttributeName);
                    if (groupNameAttribute != null) {
                        String groupName = (String) groupNameAttribute.get();
                        LOGGER.debug("Groupname: " + groupName);
                        if (groupName == null || "".equals(groupName)) {
                            LOGGER.info("No value for group name attribute " + groupAttributeName);
                            return null;
                        } else {
                            personBean.setLoginName(groupName);
                            ldapGroupsMap.put(personBean.getLoginName(), personBean);
                        }
                        Attribute memberAttribute = attributes.get(groupMemberAttributName);
                        if (memberAttribute != null) {
                            NamingEnumeration<?> members = memberAttribute.getAll();
                            while (members != null && members.hasMore()) {
                                String memberSearchResult = (String) members.next();
                                List<String> memberDNList = groupToMemberReferencesMap.get(groupName);
                                if (memberDNList == null) {
                                    memberDNList = new ArrayList<String>();
                                    groupToMemberReferencesMap.put(groupName, memberDNList);
                                }
                                memberDNList.add(memberSearchResult);
                            }
                        } else {
                            LOGGER.info("Could not find value(s) for group member attribute "
                                    + groupMemberAttributName + " for group " + groupName);
                        }
                    }
                    LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get());
                    LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName()
                            + " " + personBean.getLastName() + ")");
                } catch (Exception e) {
                    LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage());
                    LOGGER.warn(
                            "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml");
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Stack trace:", e);
                    }
                }
                ++recordCount;
            }
            // Examine the paged results control response
            Control[] controls = context.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                    + ") *****************\n");
                        } else {
                            LOGGER.debug(
                                    "***************** END-OF-PAGE " + "(total: unknown) ***************\n");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                LOGGER.debug("No controls were sent from the server");
            }
            // Re-activate paged results
            context.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);
    } catch (SizeLimitExceededException sle) {
        if (recordCount < ctls.getCountLimit()) {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
            LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                    + sle.getMessage());
            LOGGER.error(
                    "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
        } else {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                    + recordCount + ").");
            LOGGER.error(
                    "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
        }
        LOGGER.error("The LDAP synchronization is most likely incomplete.");
    } catch (NamingException e) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException ie) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(ie));
    } finally {
        context.close();
    }
    return ldapGroupsMap;
}

From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java

private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException {
    LdapContext ctx = null;
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);

    try {//w  ww  .  j  a v  a2  s  .com
        // Create initial context
        ctx = new InitialLdapContext(env, null);
        // Establish TLS session
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());

        if (disableHostNameVerification) {
            tls.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }

        tls.negotiate();

        // Initialize security credentials & perform read operation for
        // verification.
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.lookup(userDN);
        logger.debug("Authentication successful for {}", userDN);

    } catch (NamingException | IOException ex) {
        throw new AuthenticationException("Error validating LDAP user", ex);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) { /* Ignore. */
            }
        }
    }
}

From source file:org.apache.ranger.ldapconfigcheck.LdapConfigCheckMain.java

public static void main(String[] args) {

    CommandLineOptions cli = new CommandLineOptions(args);
    cli.parse();//from   w  w  w.j a  va  2 s.  c o m
    String inFileName = cli.getInput();
    String outputDir = cli.getOutput();
    if (!outputDir.endsWith("/")) {
        outputDir = outputDir.concat("/");
    }

    LdapConfig config = new LdapConfig(inFileName, cli.getBindPassword());
    if (cli.getLdapUrl() != null && !cli.getLdapUrl().isEmpty()) {
        config.updateInputPropFile(cli.getLdapUrl(), cli.getBindDn(), cli.getBindPassword(),
                cli.getUserSearchBase(), cli.getUserSearchFilter(), cli.getAuthUser(), cli.getAuthPass());
    }

    PrintStream logFile = null;
    PrintStream ambariProps = null;
    PrintStream installProps = null;
    LdapContext ldapContext = null;

    try {
        logFile = new PrintStream(new File(outputDir + LOG_FILE));
        ambariProps = new PrintStream(new File(outputDir + AMBARI_PROPERTIES));
        installProps = new PrintStream(new File(outputDir + INSTALL_PROPERTIES));

        UserSync userSyncObj = new UserSync(config, logFile, ambariProps, installProps);

        String bindDn = config.getLdapBindDn();

        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, config.getLdapUrl());
        env.put(Context.SECURITY_PRINCIPAL, bindDn);
        env.put(Context.SECURITY_CREDENTIALS, cli.getBindPassword());
        env.put(Context.SECURITY_AUTHENTICATION, config.getLdapAuthenticationMechanism());
        env.put(Context.REFERRAL, "follow");

        ldapContext = new InitialLdapContext(env, null);

        if (config.isPagedResultsEnabled()) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(config.getPagedResultsSize(), Control.CRITICAL) });
        }

        String retrieveValues = "all";

        if (cli.getDiscoverProperties() != null) {
            retrieveValues = cli.getDiscoverProperties();
            if (cli.getDiscoverProperties().equalsIgnoreCase("users")) {
                userSyncObj.findUserProperties(ldapContext);
            } else if (cli.getDiscoverProperties().equalsIgnoreCase("groups")) {
                userSyncObj.findGroupProperties(ldapContext);
            } else {
                findAllUserSyncProperties(ldapContext, userSyncObj);
            }
        } else if (cli.getRetrieveValues() != null) {
            retrieveValues = cli.getRetrieveValues();

        } else {
            cli.help();
        }

        if (cli.isAuthEnabled()) {
            authenticate(userSyncObj, config, logFile, ambariProps, installProps);
        }

        retrieveUsersGroups(ldapContext, userSyncObj, retrieveValues);

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

    } catch (FileNotFoundException fe) {
        System.out.println(fe.getMessage());
    } catch (IOException ioe) {
        logFile.println("ERROR: Failed while setting the paged results controls\n" + ioe);
    } catch (NamingException ne) {
        System.out.println("ERROR: Failed to perfom ldap bind. Please verify values for "
                + "ranger.usersync.ldap.binddn and ranger.usersync.ldap.ldapbindpassword\n" + ne);
    } catch (Throwable t) {
        if (logFile != null) {
            logFile.println("ERROR: Connection failed: " + t.getMessage());
        } else {
            System.out.println("ERROR: Connection failed: " + t.getMessage());
        }
    } finally {
        if (logFile != null) {
            logFile.close();
        }
        if (ambariProps != null) {
            ambariProps.close();
        }
        if (installProps != null) {
            installProps.close();
        }
        try {
            if (ldapContext != null) {
                ldapContext.close();
            }
        } catch (NamingException ne) {
            System.out.println("Failed to close LdapContext!");
        }
    }
}

From source file:org.apache.roller.weblogger.ui.rendering.plugins.comments.LdapCommentAuthenticator.java

public boolean authenticate(HttpServletRequest request) {
    boolean validUser = false;
    LdapContext context = null;

    String ldapDc = WebloggerConfig.getProperty("comment.authenticator.ldap.dc");
    String ldapOu = WebloggerConfig.getProperty("comment.authenticator.ldap.ou");
    String ldapPort = WebloggerConfig.getProperty("comment.authenticator.ldap.port");
    String ldapHost = WebloggerConfig.getProperty("comment.authenticator.ldap.host");
    String ldapSecurityLevel = WebloggerConfig.getProperty("comment.authenticator.ldap.securityLevel");

    boolean rollerPropertiesValid = validateRollerProperties(ldapDc, ldapOu, ldapPort, ldapHost);

    String ldapUser = request.getParameter("ldapUser");
    String ldapPass = request.getParameter("ldapPass");

    boolean userDataValid = validateUsernamePass(ldapUser, ldapPass);

    if (rollerPropertiesValid && userDataValid) {
        try {//  www.  ja v a  2 s .  com
            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            if (ldapSecurityLevel != null && (ldapSecurityLevel.equalsIgnoreCase("none")
                    || ldapSecurityLevel.equalsIgnoreCase("simple")
                    || ldapSecurityLevel.equalsIgnoreCase("strong"))) {
                env.put(Context.SECURITY_AUTHENTICATION, ldapSecurityLevel);
            }
            env.put(Context.SECURITY_PRINCIPAL, getQualifedDc(ldapDc, ldapOu, ldapUser));
            env.put(Context.SECURITY_CREDENTIALS, ldapPass);
            env.put(Context.PROVIDER_URL, "ldap://" + ldapHost + ":" + ldapPort);
            context = new InitialLdapContext(env, null);
            validUser = true;
            LOG.info("LDAP Authentication Successful. user: " + ldapUser);
        } catch (Exception e) {
            // unexpected
            LOG.error(e);
        } finally {
            if (context != null) {
                try {
                    context.close();
                } catch (NamingException e) {
                    LOG.error(e);
                }
            }
        }
    }
    return validUser;
}