Example usage for javax.naming.directory SearchControls SUBTREE_SCOPE

List of usage examples for javax.naming.directory SearchControls SUBTREE_SCOPE

Introduction

In this page you can find the example usage for javax.naming.directory SearchControls SUBTREE_SCOPE.

Prototype

int SUBTREE_SCOPE

To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.

Click Source Link

Document

Search the entire subtree rooted at the named object.

Usage

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

@SuppressWarnings("nls")
private SearchControls getSearchControls() {
    SearchControls sc = new SearchControls();
    if ("base".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    } else if ("onelevel".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    } else if ("subtree".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    }//from ww w. j av  a 2  s.  c  o m
    sc.setReturningAttributes(LDAPAttributeNames.getAll());
    return sc;
}

From source file:org.nuxeo.wizard.RouterServlet.java

public void handleUserPOST(Page currentPage, HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Context ctx = Context.instance(req);
    ParamCollector collector = ctx.getCollector();

    String refreshParam = req.getParameter("refresh");
    String directoryType = collector.getConfigurationParam("nuxeo.directory.type");

    if ("true".equals(refreshParam)) {
        currentPage.dispatchToJSP(req, resp);
        return;//from w w  w.  ja  va2s.c  o m
    }

    if ("checkNetwork".equals(refreshParam) || "checkAuth".equals(refreshParam)
            || "checkUserLdapParam".equals(refreshParam) || "checkGroupLdapParam".equals(refreshParam)) {
        try {
            if ("checkNetwork".equals(refreshParam)) {
                bindLdapConnection(collector, false);
                ctx.trackInfo("nuxeo.ldap.url", "info.host.found");
            } else if ("checkAuth".equals(refreshParam)) {
                bindLdapConnection(collector, true);
                ctx.trackInfo("nuxeo.ldap.auth", "info.auth.success");
            } else {
                DirContext dirContext = new InitialDirContext(getContextEnv(collector, true));
                String searchScope;
                String searchBaseDn;
                String searchClass;
                String searchFilter;
                if ("checkUserLdapParam".equals(refreshParam)) {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.user.searchScope");
                    searchClass = collector.getConfigurationParam("nuxeo.ldap.user.searchClass");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.user.searchFilter");
                } else {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.group.searchScope");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.group.searchFilter");
                    searchClass = "";
                }

                SearchControls scts = new SearchControls();
                if ("onelevel".equals(searchScope)) {
                    scts.setSearchScope(SearchControls.ONELEVEL_SCOPE);
                } else {
                    scts.setSearchScope(SearchControls.SUBTREE_SCOPE);
                }
                String filter = String.format("(&(%s)(objectClass=%s))",
                        searchFilter.isEmpty() ? "objectClass=*" : searchFilter,
                        searchClass.isEmpty() ? "*" : searchClass);
                NamingEnumeration<SearchResult> results;
                try {
                    results = dirContext.search(searchBaseDn, filter, scts);
                    if (!results.hasMore()) {
                        ctx.trackError("nuxeo.ldap.search", "error.ldap.noresult");
                    } else {
                        SearchResult result = results.next();
                        if (searchBaseDn.equalsIgnoreCase(result.getNameInNamespace()) && results.hasMore()) {
                            // try not to display the root of the search
                            // base DN
                            result = results.next();
                        }
                        ctx.trackInfo("dn", result.getNameInNamespace());
                        Attributes attributes = result.getAttributes();
                        NamingEnumeration<String> ids = attributes.getIDs();
                        String id;
                        StringBuilder sb;
                        while (ids.hasMore()) {
                            id = ids.next();
                            NamingEnumeration<?> values = attributes.get(id).getAll();
                            sb = new StringBuilder();
                            while (values.hasMore()) {
                                sb.append(values.next()).append(" , ");
                            }
                            ctx.trackInfo(id, sb.substring(0, sb.length() - 3));
                        }
                    }
                } catch (NameNotFoundException e) {
                    ctx.trackError("nuxeo.ldap.search", "error.ldap.searchBaseDn");
                    log.warn(e);
                }
                dirContext.close();
            }
        } catch (AuthenticationException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.auth.failed");
            log.warn(e);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.url", "error.host.not.found");
            log.warn(e);
        }
    }

    // Form submit
    if (!"default".equals(directoryType) && refreshParam.isEmpty()) {
        // first check bind to LDAP server
        try {
            bindLdapConnection(collector, true);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.ldap.bind.failed");
            log.warn(e);
        }

        // then check mandatory fields
        if (collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.searchBaseDn", "error.user.searchBaseDn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.rdn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.rdn", "error.user.rdn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.username").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.username", "error.user.username.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.password").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.password", "error.user.password.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.firstname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.firstname", "error.user.firstname.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.lastname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.lastname", "error.user.lastname.required");
        }
        String userGroupStorage = collector.getConfigurationParam("nuxeo.user.group.storage");
        if (!"userLdapOnly".equals(userGroupStorage) && !"multiUserSqlGroup".equals(userGroupStorage)) {
            if (collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.searchBaseDn", "error.group.searchBaseDn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.rdn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.rdn", "error.group.rdn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.name").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.name", "error.group.name.required");
            }
        }
        if ("true".equals(collector.getConfigurationParam("nuxeo.user.emergency.enable"))) {
            if (collector.getConfigurationParam("nuxeo.user.emergency.username").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.username", "error.emergency.username.required");
            }
            if (collector.getConfigurationParam("nuxeo.user.emergency.password").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.password", "error.emergency.password.required");
            }
        }
    }

    if (ctx.hasErrors() || ctx.hasInfos()) {
        currentPage.dispatchToJSP(req, resp);
    } else {
        currentPage.next().dispatchToJSP(req, resp, true);
    }
}

From source file:org.orbeon.oxf.processor.LDAPProcessor.java

private int convertSearchScope(String scope) {
    if (scope != null && scope.toUpperCase().equals("SUBTREE")) {
        return SearchControls.SUBTREE_SCOPE;
    } else if (scope != null && scope.toUpperCase().equals("OBJECT")) {
        return SearchControls.OBJECT_SCOPE;
    } else if (scope != null
            && (scope.toUpperCase().equals("ALLLEVELS") || scope.toUpperCase().equals("ONELEVEL"))) {
        return SearchControls.ONELEVEL_SCOPE;
    } else {//from  w  w w.  j a va 2 s . c o  m
        return SearchControls.SUBTREE_SCOPE;
    }
}

From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * return false if user or password is wrong
 *    /* www . ja v  a2s  .c  o m*/
 * here we expand attributes: %u, %d, %s
 *    if defined userSearch, retrieve user's DN  and try to bind with it
 * @param username
 * @param password
 * @return
 */
private boolean ldapBind(String username, String password) {
    String userDN = null;
    try {
        TempParams t = new TempParams();
        // if username  is an email substitute %u e %d in baseDn:  
        expandSearchAndBaseDn(username, t);

        // setup the default LdapInterface configured with bean data
        ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapInterface.init(getLdapUrl(), getBaseDn(), getSearchBindDn(), getSearchBindPassword(),
                isFollowReferral(), isConnectionPooling(), null);

        // set the userDN when custom user search
        if (!StringUtils.isEmpty(getUserSearch())) {
            // customize the field used to search the user.

            SearchResult sr = ldapInterface.searchOneEntry(getUserSearch(), new String[] { "dn" },
                    SearchControls.SUBTREE_SCOPE);

            if (sr == null) {
                log.info("Username " + username + " not found");
                return false;
            }

            userDN = sr.getNameInNamespace().trim();
            log.info("binding with dn:" + userDN);

        }
        // on failure, set the user DN with append
        if (userDN == null) {
            userDN = "uid=" + username + "," + baseDn;
        }
    } catch (Exception e) {
        log.error("Can't instantiate LdapInterface: " + e.getMessage());
        return false;
    }
    // Set up environment for creating initial context
    Hashtable<String, String> env = new Hashtable<String, String>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getLdapUrl());

    // Authenticate as  User and password  
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, password);

    try {
        DirContext ctx = new InitialDirContext(env);
        log.debug(ctx.lookup(userDN));
        ctx.close();
    } catch (AuthenticationException e) {
        log.info("User not authenticated: " + e.getMessage());
        return false;
    } catch (NamingException e) {
        log.warn("User not authenticated: problem while accessing ldap " + e.getMessage());
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public List<Map<String, Object>> search(String context, String filter, String[] returningAttrs) {
    if (null == filter) {
        return null;
    }/*  ww  w  .ja v  a2  s  .  c o  m*/

    LogUtils.debug(LOG, String.format("search %s with filter=%s, returningAttrs=%s", context, filter,
            Arrays.toString(returningAttrs)));

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(returningAttrs);

    try {
        List<Map<String, Object>> retVal = new ArrayList<Map<String, Object>>();
        NamingEnumeration<SearchResult> results = ctx.search(context, filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                retVal.add(fromAttributesToMap(result.getAttributes()));
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the map", e);
            }
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

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

/**
 * Get all ldap groups/*from w  w  w .j a v a  2s  .  c o 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:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public boolean saveUserRole(String roleName, String username, DirContext context) throws MappingException {

    String groupName = findGroupName(roleName);

    if (groupName == null) {
        log.warn("no group found for role '{}", roleName);
        groupName = roleName;//from   w  w  w.j a va 2  s. com
    }

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {
        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();
            Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember());
            if (attribute == null) {
                BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember());
                basicAttribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn());
                context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] {
                        new ModificationItem(DirContext.ADD_ATTRIBUTE, basicAttribute) });
            } else {
                attribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn());
                context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] {
                        new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute) });
            }
            return true;
        }

        return false;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        if (namingEnumeration != null) {
            try {
                namingEnumeration.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

public List<String> lookup(String context, String filter) {
    if (null == filter) {
        return null;
    }// www  . ja v a 2s .  c o  m

    LogUtils.debug(LOG, String.format("search DNs with context=%s, filter=%s", context, filter));

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(new String[] {});

    try {
        List<String> retVal = new ArrayList<String>();
        NamingEnumeration<SearchResult> results = ctx.search(context, filter, ctrl);
        while (results.hasMore()) {
            retVal.add(results.next().getNameInNamespace());
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_COMMON_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//*from  w w  w . ja v  a  2s . c o  m*/
public void loadUserByCommonName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByCommonName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String commonName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aUserBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_COMMON_NAME))
            commonName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (commonName == null) {
        String msgStr = String.format("LDAP common name '%s' is unassigned.", LDAP_COMMON_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_COMMON_NAME, commonName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:org.projectforge.business.ldap.LdapUserDao.java

public LdapUser findByUsername(final Object username, final String... organizationalUnits) {
    return (LdapUser) new LdapTemplate(ldapConnector) {
        @Override//from www. ja  v  a 2s.  co m
        protected Object call() throws NameNotFoundException, Exception {
            NamingEnumeration<?> results = null;
            final SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            final String searchBase = getSearchBase(organizationalUnits);
            results = ctx.search(searchBase, "(&(objectClass=" + getObjectClass() + ")(uid=" + username + "))",
                    controls);
            if (results.hasMore() == false) {
                return null;
            }
            final SearchResult searchResult = (SearchResult) results.next();
            final String dn = searchResult.getName();
            final Attributes attributes = searchResult.getAttributes();
            if (results.hasMore() == true) {
                log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + username);
            }
            return mapToObject(dn, searchBase, attributes);
        }
    }.excecute();
}