Example usage for javax.naming.ldap LdapContext lookup

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

Introduction

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

Prototype

public Object lookup(Name name) throws NamingException;

Source Link

Document

Retrieves the named object.

Usage

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

/**
 * Get all ldap groups/*  w w w. j  av  a 2s  .  com*/
 * 
 * @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

/**
 * Gets the ldap persons for ldap groups based on the person DNs
 * //from w  w  w.j  av a 2 s . com
 * @param siteBean
 * @param groups
 * @param groupToMemberReferencesMap
 * @return
 */
public static Map<String, List<TPersonBean>> getGroupToPersonMaps1(String baseURL, TSiteBean siteBean,
        Map<String, TPersonBean> groups, Map<String, List<String>> groupToMemberReferencesMap) {
    String loginAttributeName = siteBean.getLdapAttributeLoginName();
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    Map<String, String> ldapMap = getLdapMap();
    String personFilter = ldapMap.get(LdapUtil.LDAP_CONFIG.LDAP_FILTER_PERSONS);
    boolean hasPersonFilter = false;
    if (personFilter != null && !"".equals(personFilter) && !"*".equals(personFilter)) {
        hasPersonFilter = true;
        if (!(personFilter.startsWith("(") && personFilter.endsWith(")"))) {
            personFilter = "(" + personFilter + ")";
        }
        LOGGER.debug("General user filter expression " + personFilter);
    }
    Map<String, List<TPersonBean>> groupToPersons = new HashMap<String, List<TPersonBean>>();
    if (groupToMemberReferencesMap != null) {
        for (Map.Entry<String, List<String>> groupPersons : groupToMemberReferencesMap.entrySet()) {
            String groupName = groupPersons.getKey();
            List<String> personDNs = groupPersons.getValue();
            Map<String, List<String>> parentDNPartToPersonSearchStrings = new HashMap<String, List<String>>();
            if (personDNs != null) {
                LOGGER.debug("Getting the persons for group " + groupName);
                for (String personDN : personDNs) {
                    int index = personDN.indexOf(",");
                    if (index != -1) {
                        String searchPart = personDN.substring(0, index);
                        String searchStr = "(" + searchPart + ")";
                        if (hasPersonFilter) {
                            searchStr = "(&" + personFilter + searchStr + ")";
                        }
                        String parentDNPart = personDN.substring(index + 1);
                        List<String> personSearchStrings = parentDNPartToPersonSearchStrings.get(parentDNPart);
                        if (personSearchStrings == null) {
                            personSearchStrings = new LinkedList<String>();
                            parentDNPartToPersonSearchStrings.put(parentDNPart, personSearchStrings);
                        }
                        personSearchStrings.add(searchStr);
                    }
                }
            }
            List<TPersonBean> personsInGroup = new LinkedList<TPersonBean>();
            LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword);
            if (baseContext == null) {
                LOGGER.warn("Context is null for base url " + baseURL);
                continue;
            }
            for (Map.Entry<String, List<String>> parentDnToPersonSearchStrings : parentDNPartToPersonSearchStrings
                    .entrySet()) {
                String parentDn = parentDnToPersonSearchStrings.getKey();
                List<String> searchStrs = parentDnToPersonSearchStrings.getValue();
                if (searchStrs == null || searchStrs.isEmpty()) {
                    continue;
                }
                LdapContext ldapContext = null;
                try {
                    LOGGER.debug(
                            "Number of persons searched for parentDn " + parentDn + ": " + searchStrs.size());
                    ldapContext = (LdapContext) baseContext.lookup(parentDn);
                    if (ldapContext == null) {
                        LOGGER.warn("Lookup context is null for " + parentDn);
                        continue;
                    }
                    List<TPersonBean> personsInParentDN = getLdapUsers(ldapContext, loginAttributeName,
                            searchStrs);
                    if (personsInParentDN != null) {
                        LOGGER.debug("Number of persons found for parentDn " + parentDn + ": "
                                + personsInParentDN.size());
                        personsInGroup.addAll(personsInParentDN);
                    }
                } catch (Exception e) {
                    LOGGER.warn("Getting the persons with parentDn  " + parentDn + " for group " + groupName
                            + " failed with " + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                } finally {
                    try {
                        if (ldapContext != null) {
                            ldapContext.close();
                        }
                    } catch (NamingException e) {
                        LOGGER.warn("Closing the context with " + parentDn + " for group " + groupName
                                + " failed with " + e.getMessage());
                        LOGGER.debug(ExceptionUtils.getStackTrace(e));
                    }
                }
            }
            groupToPersons.put(groupName, personsInGroup);
            if (baseContext != null) {
                try {
                    baseContext.close();
                } catch (NamingException e) {
                    LOGGER.warn("Closing the base context with failed with " + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
    }
    return groupToPersons;
}

From source file:com.google.enterprise.connector.sharepoint.spiimpl.SharepointConnectorType.java

public boolean checkForSearchBase(LdapContext ldapContext, String searchBase, ErrorDignostics ed) {
    /**/*from   w w  w .  j av a 2  s . co  m*/
     * InvalidNameException indicates that specified name does not conform to
     * the naming syntax for search base naming convention
     */
    try {
        if (ldapContext.lookup(searchBase) != null) {
            return true;
        }
    } catch (InvalidNameException e) {
        LOGGER.log(Level.WARNING, "Invalid name for search base lookup." + "\n" + e);
        ed.set(SPConstants.SEARCH_BASE, rb.getString(SPConstants.SEARCH_BASE_INVALID_SYNTAX));
    } catch (NameNotFoundException e) {
        LOGGER.log(Level.WARNING, "Invalid name for search base" + "\n" + e);
        ed.set(SPConstants.SEARCH_BASE, rb.getString(SPConstants.SEARCH_BASE_INVALID_NAME));
    } catch (NamingException e) {
        LOGGER.log(Level.WARNING, "Invalid naming exception for search base lookup." + "\n" + e);
        ed.set(SPConstants.SEARCH_BASE, rb.getString(SPConstants.SEARCH_BASE_INVALID));
    }
    return false;
}

From source file:org.apache.directory.server.core.jndi.ObjStateFactoryIT.java

@Test
public void testObjectFactory() throws Exception {
    LdifEntry akarasulu = getUserAddLdif();
    getService().getAdminSession().add(new DefaultEntry(getService().getSchemaManager(), akarasulu.getEntry()));

    LdapContext sysRoot = getSystemContext(getService());
    sysRoot.addToEnvironment(Context.OBJECT_FACTORIES, PersonObjectFactory.class.getName());
    Object obj = sysRoot.lookup("uid=akarasulu, ou=users");
    Attributes attrs = sysRoot.getAttributes("uid=akarasulu, ou=users");
    assertEquals(Person.class, obj.getClass());
    Person me = (Person) obj;/*from  w w w .j  a v a 2 s  .  c  o  m*/
    assertEquals(attrs.get("sn").get(), me.getLastname());
    assertEquals(attrs.get("cn").get(), me.getCn());
    assertTrue(ArrayUtils.isEquals(attrs.get("userPassword").get(), Strings.getBytesUtf8("test")));
    assertEquals(attrs.get("telephonenumber").get(), me.getTelephoneNumber());
    assertNull(me.getSeealso());
    assertNull(me.getDescription());
}

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 {/*from   w  w  w . j  a  va2s  .  c om*/
        // 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. */
            }
        }
    }
}