Example usage for javax.naming.directory SearchControls setSearchScope

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

Introduction

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

Prototype

public void setSearchScope(int scope) 

Source Link

Document

Sets the search scope to one of: OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

Usage

From source file:com.konakart.bl.LDAPMgrCore.java

/**
 * Called if the LDAP module is installed and active. This method should return:
 * <ul>/*  w ww .j a v  a 2s.  c  o  m*/
 * <li>A negative number in order for the login attempt to fail. The KonaKart login() method
 * will return a null sessionId</li>
 * <li>Zero to signal that this method is not implemented. The KonaKart login() method will
 * perform the credential check.</li>
 * <li>A positive number for the login attempt to pass. The KonaKart login() will not check
 * credentials, and will log in the customer, returning a valid session id.</li>
 * </ul>
 * This method may need to be modified slightly depending on the structure of your LDAP. The
 * example works when importing the exampleData.ldif file in the LDAP module jar:
 * 
 * dn: cn=Robert Smith,ou=people,dc=example,dc=com<br/>
 * objectclass: inetOrgPerson<br/>
 * cn: Robert Smith<br/>
 * cn: Robert J Smith<br/>
 * cn: bob smith<br/>
 * sn: smith<br/>
 * uid: rjsmith<br/>
 * userpassword: rJsmitH<br/>
 * carlicense: HISCAR 123<br/>
 * homephone: 555-111-2222<br/>
 * mail: r.smith@example.com<br/>
 * mail: rsmith@example.com<br/>
 * mail: bob.smith@example.com<br/>
 * description: swell guy<br/>
 * 
 * The code attempts to connect to LDAP using the username, password and URL in the
 * configuration variables set when the module was installed through the admin app.<br/>
 * 
 * After having connected, the person object is searched for using the email address of the
 * user. If found we use the "cn" attribute and the password of the user to attempt to bind to
 * LDAP. If the bind is successful, we return a positive number which means that authentication
 * was successful.
 * 
 * @param emailAddr
 *            The user name required to log in
 * @param password
 *            The log in password
 * @return Returns an integer
 * @throws Exception
 */
public int checkCredentials(String emailAddr, String password) throws Exception {
    DirContext ctx = null;

    try {
        Hashtable<String, String> environment = new Hashtable<String, String>();

        if (log.isDebugEnabled()) {
            log.debug("LDAP connection URL                          =   " + url);
            log.debug("LDAP user name                               =   " + ldapUserName);
            log.debug("LDAP person object distinguished name (DN)   =   " + personDN);
        }

        if (ldapUserName == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_USER_NAME configuration variable hasn't been set.");
        }
        if (ldapPassword == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_PASSWORD configuration variable hasn't been set.");
        }
        if (url == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_URL configuration variable hasn't been set.");
        }
        if (personDN == null) {
            throw new KKException(
                    "Cannot validate through LDAP because the MODULE_OTHER_LDAP_PERSON_DN (Distinguished Name of Person Object) configuration variable hasn't been set.");
        }

        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.PROVIDER_URL, url);
        environment.put(Context.SECURITY_PRINCIPAL, ldapUserName);
        environment.put(Context.SECURITY_CREDENTIALS, ldapPassword);

        /*
         * connect to LDAP using the credentials and connection string from the configuration
         * variables
         */
        try {
            ctx = new InitialDirContext(environment);
        } catch (Exception e) {
            log.error("Cannot connect to LDAP", e);
            return -1;
        }

        /* Specify the search filter on the eMail address */
        String filter = "(mail=" + emailAddr + ")";

        /*
         * limit returned attributes to those we care about. In this case we only require the
         * "cn" attribute which we will use to attempt to bind the user in order to validate his
         * password
         */
        String[] attrIDs = { "cn" };
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(attrIDs);
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        /* Search for objects using filter and controls */
        NamingEnumeration<SearchResult> answer = ctx.search(personDN, filter, ctls);

        /* close the connection */
        ctx.close();

        if (answer == null || !answer.hasMore()) {
            return -1;
        }

        SearchResult sr = answer.next();
        Attributes attrs = sr.getAttributes();
        String cn = attrs.get("cn").toString();
        if (log.isDebugEnabled()) {
            log.debug("cn of user with eMail (" + emailAddr + ") is " + cn);
        }

        /*
         * cn could be in the format "cn: Peter Smith, Pete Smith, Smithy" so we need to capture
         * just the first entry
         */
        if (cn != null) {
            if (cn.contains(",")) {
                cn = cn.split(",")[0];
                if (cn.contains(":")) {
                    cn = cn.split(":")[1];
                }
            } else if (cn.contains(":")) {
                cn = cn.split(":")[1];
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Cleaned cn of user with eMail (" + emailAddr + ") is " + cn);
        }

        /* Now we try to bind as the user */
        String userName = "cn=" + cn + "," + personDN;

        if (log.isDebugEnabled()) {
            log.debug("LDAP user name of user with eMail (" + emailAddr + ") is " + userName);
        }

        /* Bind as the user */
        environment.put(Context.SECURITY_PRINCIPAL, userName);
        environment.put(Context.SECURITY_CREDENTIALS, password);
        try {
            ctx = new InitialDirContext(environment);
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Could not bind user " + userName);
            }
            return -1;
        }
        ctx.close();
        if (log.isDebugEnabled()) {
            log.debug("user with eMail (" + emailAddr + ") was successfully authenticated using LDAP");
        }
        return 1;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.error("Received an exception while closing the LDAP DirContext", e);
            }
        }
    }
}

From source file:org.jasig.schedassist.impl.ldap.LDAPDelegateCalendarAccountDaoImpl.java

/**
 * //from  ww  w.j  ava 2s . c om
 * @param searchFilter
 * @param owner
 * @return
 */
@SuppressWarnings("unchecked")
protected List<IDelegateCalendarAccount> executeSearchReturnList(final Filter searchFilter,
        final ICalendarAccount owner) {
    SearchControls searchControls = new SearchControls();
    searchControls.setCountLimit(searchResultsLimit);
    searchControls.setTimeLimit(searchTimeLimit);
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    List<IDelegateCalendarAccount> results = Collections.emptyList();
    try {
        results = ldapTemplate.search(baseDn, searchFilter.toString(), searchControls,
                new DefaultDelegateAccountAttributesMapperImpl(ldapAttributesKey, owner));
        if (log.isDebugEnabled()) {
            log.debug("search " + searchFilter + " returned " + results.size() + " results");
        }

        if (isTreatOwnerAttributeAsDistinguishedName() && owner != null
                && owner instanceof HasDistinguishedName) {
            HasDistinguishedName ldapOwnerAccount = (HasDistinguishedName) owner;
            enforceDistinguishedNameMatch(results, ldapOwnerAccount);
        }
        Collections.sort(results, new DelegateDisplayNameComparator());
    } catch (SizeLimitExceededException e) {
        log.debug("search filter exceeded size limit (" + searchResultsLimit + "): " + searchFilter);
    } catch (TimeLimitExceededException e) {
        log.debug("search filter exceeded time limit(" + searchTimeLimit + " milliseconds): " + searchFilter);
    }
    return results;
}

From source file:com.openkm.principal.LdapPrincipalAdapter.java

@SuppressWarnings("unchecked")
private List<String> ldapSearch(List<String> searchBases, String searchFilter, String attribute) {
    log.debug("ldapSearch({}, {}, {})", new Object[] { searchBases, searchFilter, attribute });
    List<String> al = new ArrayList<String>();
    DirContext ctx = null;/*from  www.  j  a v a2 s .  c o  m*/
    Hashtable<String, String> env = getEnvironment();

    try {
        ctx = new InitialDirContext(env);
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        for (String searchBase : searchBases) {
            NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchCtls);

            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();

                if (attribute.equals("")) {
                    StringBuilder sb = new StringBuilder();

                    for (NamingEnumeration<?> ne = attributes.getAll(); ne.hasMore();) {
                        Attribute attr = (Attribute) ne.nextElement();
                        sb.append(attr.toString());
                        sb.append("\n");
                    }

                    al.add(sb.toString());
                } else {
                    Attribute attrib = attributes.get(attribute);

                    if (attrib != null) {
                        // Handle multi-value attributes
                        for (NamingEnumeration<?> ne = attrib.getAll(); ne.hasMore();) {
                            String value = (String) ne.nextElement();

                            // If FQDN get only main part
                            if (value.startsWith("CN=") || value.startsWith("cn=")) {
                                String cn = value.substring(3, value.indexOf(','));
                                log.debug("FQDN: {}, CN: {}", value, cn);
                                al.add(cn);
                            } else {
                                al.add(value);
                            }
                        }
                    }
                }
            }
        }
    } catch (ReferralException e) {
        log.error("ReferralException: {}", e.getMessage());
        log.error("ReferralInfo: {}", e.getReferralInfo());
        log.error("ResolvedObj: {}", e.getResolvedObj());

        try {
            log.error("ReferralContext: {}", e.getReferralContext());
        } catch (NamingException e1) {
            log.error("NamingException logging context: {}", e1.getMessage());
        }
    } catch (NamingException e) {
        log.error("NamingException: {} (Base: {} - Filter: {} - Attribute: {})",
                new Object[] { e.getMessage(), searchBases, searchFilter, attribute });
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException e) {
            log.error("NamingException closing context: {}", e.getMessage());
        }
    }

    log.debug("ldapSearch: {}", al);
    return al;
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java

private String searchUser(String login, HashMap<String, String> userAttrs, DirContext ctx)
        throws NamingException {
    String uid;/*from  w w w .j ava2s  .co  m*/
    SearchControls ctls = new SearchControls();
    ctls.setReturningObjFlag(true);
    ctls.setSearchScope(searchScope);
    String search = searchPattern.replaceAll(Pattern.quote("%LOGIN%"), escapeLDAPSearchFilter(login));
    log.debug("Searching LDAP for " + search);
    NamingEnumeration<SearchResult> answer = ctx.search(base, search, ctls);
    try {
        if (!answer.hasMore())
            throw new NoSuchElementException();
        log.debug("LDAP returned >=1 record.");
        SearchResult result = answer.next();
        uid = result.getName();
        for (Map.Entry<String, String> e : attributeMap.entrySet()) {
            log.debug("found LDAP attribute: " + e.getKey());
            Attribute a = result.getAttributes().get(e.getKey());
            if (a != null)
                userAttrs.put(e.getValue(), a.get().toString());
        }
    } finally {
        answer.close();
    }
    return uid;
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

public boolean authenticateUser(String userLogin, UserEdit edit, String password) {
    Hashtable env = new Hashtable();
    InitialDirContext ctx;/*  www  .j  a va 2 s  . c o m*/

    String INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory";
    String MY_HOST = getLdapHost() + ":" + getLdapPort();
    String cn;
    boolean returnVal = false;

    if (!password.equals("")) {

        env.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
        env.put(Context.PROVIDER_URL, MY_HOST);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, "secret");

        String[] returnAttribute = { "ou" };
        SearchControls srchControls = new SearchControls();
        srchControls.setReturningAttributes(returnAttribute);
        srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(userLogin) + "))";

        try {
            ctx = new InitialDirContext(env);
            NamingEnumeration answer = ctx.search(getBasePath(), searchFilter, srchControls);
            String trobat = "false";

            while (answer.hasMore() && trobat.equals("false")) {

                SearchResult sr = (SearchResult) answer.next();
                String dn = sr.getName().toString() + "," + getBasePath();

                // Second binding
                Hashtable authEnv = new Hashtable();
                try {
                    authEnv.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
                    authEnv.put(Context.PROVIDER_URL, MY_HOST);
                    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
                    authEnv.put(Context.SECURITY_PRINCIPAL, sr.getName() + "," + getBasePath());
                    authEnv.put(Context.SECURITY_CREDENTIALS, password);
                    try {
                        DirContext authContext = new InitialDirContext(authEnv);
                        returnVal = true;
                        trobat = "true";
                        authContext.close();
                    } catch (AuthenticationException ae) {
                        M_log.info("Access forbidden");
                    }

                } catch (NamingException namEx) {
                    M_log.info("User doesn't exist");
                    returnVal = false;
                    namEx.printStackTrace();
                }
            }
            if (trobat.equals("false"))
                returnVal = false;

        } catch (NamingException namEx) {
            namEx.printStackTrace();
            returnVal = false;
        }
    }
    return returnVal;
}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

protected NamingEnumeration<SearchResult> searchUsers(DirContext context, String[] returnAttributes,
        LdapUserQuery query) throws NamingException {
    if (query == null) {
        query = new LdapUserQuery();
    }/*w  w w . ja v a  2 s . co m*/
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(mapper.getReturningAttributes());
    ctls.setCountLimit(((LdapUserMapper) mapper).getMaxResultCount());

    String finalFilter = new StringBuilder("(&(objectClass=" + mapper.getUserObjectClass() + ")")
            .append((mapper.getUserFilter() != null ? mapper.getUserFilter() : ""))
            .append(query.getLdapFilter(mapper) + ")").toString();

    log.debug("Searching for users with filter: '{}' from base dn: {}", finalFilter, mapper.getUserBaseDn());

    return context.search(mapper.getUserBaseDn(), finalFilter, ctls);
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java

private boolean ldapAuthorizationVerification(String user) {
    M_log.debug("ldapAuthorizationVerification(): called");
    boolean isAuthorized = false;
    DirContext dirContext = null;
    NamingEnumeration listOfPeopleInAuthGroup = null;
    NamingEnumeration allSearchResultAttributes = null;
    NamingEnumeration simpleListOfPeople = null;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY);
        env.put(Context.PROVIDER_URL, providerURL);
    } else {/*from w  w w.j av  a  2s  .  c o m*/
        M_log.error(
                " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file");
        return isAuthorized;
    }
    try {
        dirContext = new InitialDirContext(env);
        String[] attrIDs = { "member" };
        SearchControls searchControls = new SearchControls();
        searchControls.setReturningAttributes(attrIDs);
        searchControls.setReturningObjFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = OU_GROUPS;
        String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))";
        listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls);
        String positiveMatch = "uid=" + user + ",";
        outerloop: while (listOfPeopleInAuthGroup.hasMore()) {
            SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next();
            allSearchResultAttributes = (searchResults.getAttributes()).getAll();
            while (allSearchResultAttributes.hasMoreElements()) {
                Attribute attr = (Attribute) allSearchResultAttributes.nextElement();
                simpleListOfPeople = attr.getAll();
                while (simpleListOfPeople.hasMoreElements()) {
                    String val = (String) simpleListOfPeople.nextElement();
                    if (val.indexOf(positiveMatch) != -1) {
                        isAuthorized = true;
                        break outerloop;
                    }
                }
            }
        }
        return isAuthorized;
    } catch (NamingException e) {
        M_log.error("Problem getting attribute:" + e);
        return isAuthorized;
    } finally {
        try {
            if (simpleListOfPeople != null) {
                simpleListOfPeople.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ",
                    e);
        }
        try {
            if (allSearchResultAttributes != null) {
                allSearchResultAttributes.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ",
                    e);
        }
        try {
            if (listOfPeopleInAuthGroup != null) {
                listOfPeopleInAuthGroup.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ",
                    e);
        }
        try {
            if (dirContext != null) {
                dirContext.close();
            }
        } catch (NamingException e) {
            M_log.error("Problem occurred while closing the  \"dirContext\"  object", e);
        }
    }

}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Returns <code>true</code> if the supplied id is found in the JNDI storage.
 * @see IStorage#exists(java.lang.String)
 *///from   ww  w. j  ava  2 s  . c om
public boolean exists(String id) throws UserException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;

    boolean bReturn = false;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

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

        String searchFilter = resolveSearchQuery(id);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
            bReturn = oNamingEnumeration.hasMore();
        } catch (InvalidSearchFilterException e) {
            _logger.error("Wrong filter: " + searchFilter);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown, naming exception. query: " + searchFilter, e);
            return false; //user unknown
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not verify if user exists: " + id, e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + id, e);
            }
        }
    }
    return bReturn;
}

From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Gathers attributes from JNDI storage to the supplied attributes object.
 * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes)
 *//*from   ww w  .  j a v  a  2  s  .c  o  m*/
public void process(String sUserId, IAttributes oAttributes) throws AttributeException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (_listGather.size() > 0) {
            String[] saAttributes = _listGather.toArray(new String[0]);
            oScope.setReturningAttributes(saAttributes);
        }

        String searchFilter = resolveSearchQuery(sUserId);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(sUserId);
            _logger.error(sbFailed.toString(), e);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown: " + sUserId);
            return;
        }

        if (oNamingEnumeration.hasMore()) {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
            Attributes oSearchedAttributes = oSearchResult.getAttributes();
            NamingEnumeration neAttributes = oSearchedAttributes.getAll();
            while (neAttributes.hasMore()) {
                Attribute oAttribute = (Attribute) neAttributes.next();
                String sAttributeName = oAttribute.getID();
                String sMappedName = _htMapper.get(sAttributeName);
                if (sMappedName != null)
                    sAttributeName = sMappedName;

                if (oAttribute.size() > 1) {
                    Vector<Object> vValue = new Vector<Object>();
                    NamingEnumeration neAttribute = oAttribute.getAll();
                    while (neAttribute.hasMore())
                        vValue.add(neAttribute.next());

                    oAttributes.put(sAttributeName, vValue);
                } else {
                    Object oValue = oAttribute.get();
                    if (oValue == null)
                        oValue = "";
                    oAttributes.put(sAttributeName, oValue);
                }
            }
        }
    } catch (AttributeException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch attributes for user: " + sUserId, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId,
                        e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e);
            }
        }
    }
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Returns the field value of the specified field for the specified id. 
 * @see IExternalStorage#getField(java.lang.String, java.lang.String)
 *///from   www.  jav a 2s. c o m
public Object getField(String id, String field) throws UserException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    Object oValue = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

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

        String searchFilter = resolveSearchQuery(id);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attribute '");
            sbFailed.append(field);
            sbFailed.append("' for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new UserException(SystemErrors.ERROR_INTERNAL, e);
        } catch (NamingException e) {
            _logger.error("User unknown: " + id);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        }

        if (!oNamingEnumeration.hasMore()) {
            StringBuffer sbFailed = new StringBuffer("User with id '");
            sbFailed.append(id);
            sbFailed.append("' not found after LDAP search with filter: ");
            sbFailed.append(searchFilter);
            _logger.error(sbFailed.toString());
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
        Attributes oAttributes = oSearchResult.getAttributes();
        NamingEnumeration oAttrEnum = oAttributes.getAll();
        if (oAttrEnum.hasMore()) {
            Attribute oAttribute = (Attribute) oAttrEnum.next();
            oValue = oAttribute.get();
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not retrieve field: " + field, e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + id, e);
            }
        }
    }
    return oValue;
}