Example usage for javax.naming.directory DirContext search

List of usage examples for javax.naming.directory DirContext search

Introduction

In this page you can find the example usage for javax.naming.directory DirContext search.

Prototype

public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons)
        throws NamingException;

Source Link

Document

Searches in the named context or object for entries that satisfy the given search filter.

Usage

From source file:ru.efo.security.ADUserDetailsService.java

private void describeRoles(DirContext context, Attribute memberOf, Set<String> groups, Set<String> roles)
        throws NamingException {
    if (memberOf != null) {
        for (int i = 0; i < memberOf.size(); i++) {
            Attribute attr = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" }).get("CN");
            if (attr != null) {
                final String role = attr.get().toString();
                if (rolesMapping != null) {
                    for (String key : rolesMapping.keySet()) {
                        if (role.matches(rolesMapping.get(key))) {
                            if (logger.isLoggable(Level.FINE)) {
                                if (!roles.contains(key)) {
                                    logger.log(Level.FINE, "Role: " + key);
                                }//from w w w  .j a v  a 2 s.  com
                            }
                            roles.add(key);
                        }
                    }
                } else {
                    final String roleWithPrefix = (rolePrefix == null ? "" : rolePrefix)
                            + role.toUpperCase().replaceAll("(\\s|-)+", "_");
                    if (logger.isLoggable(Level.FINE)) {
                        if (!roles.contains(role)) {
                            logger.log(Level.FINE, "Role: " + roleWithPrefix);
                        }
                    }
                    roles.add(roleWithPrefix);
                }
                groups.add(role);

                if (recursiveRoleSearch) {
                    SearchControls controls = new SearchControls();
                    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                    NamingEnumeration<SearchResult> renum = context.search(
                            groupSearchBase != null ? groupSearchBase : userSearchBase, "(CN=" + role + ")",
                            controls);
                    if (renum.hasMore()) {
                        SearchResult searchResult = renum.next();
                        attr = searchResult.getAttributes().get("memberOf");
                        describeRoles(context, attr, groups, roles);
                    }
                }
            }
        }
    }
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public List<String> getGroups(String username, DirContext context) throws MappingException {

    List<String> userGroups = new ArrayList<String>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/*from  w w  w  .j a  v a 2s.  c o  m*/

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String groupEntry = null;
        try {
            //try to look the user up
            User user = userManager.findUser(username);
            if (user instanceof LdapUser) {
                LdapUser ldapUser = LdapUser.class.cast(user);
                Attribute dnAttribute = ldapUser.getOriginalAttributes().get(getLdapDnAttribute());
                if (dnAttribute != null) {
                    groupEntry = String.class.cast(dnAttribute.get());
                }

            }
        } catch (UserNotFoundException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        } catch (UserManagerException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        }
        if (groupEntry == null) {
            //failed to look up the user's groupEntry directly
            StringBuilder builder = new StringBuilder();
            String posixGroup = "posixGroup";
            if (posixGroup.equals(getLdapGroupClass())) {
                builder.append(username);
            } else {
                builder.append(this.userIdAttribute).append("=").append(username).append(",")
                        .append(getBaseDn());
            }
            groupEntry = builder.toString();
        }

        String filter = new StringBuilder().append("(&").append("(objectClass=" + getLdapGroupClass() + ")")
                .append("(").append(getLdapGroupMember()).append("=").append(Rdn.escapeValue(groupEntry))
                .append(")").append(")").toString();

        log.debug("filter: {}", filter);

        namingEnumeration = context.search(getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            List<String> allMembers = new ArrayList<String>();

            Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember());

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {

                    String userName = allMembersEnum.next();
                    //the original dn
                    allMembers.add(userName);
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    allMembers.add(userName);
                }
                close(allMembersEnum);
            }

            if (allMembers.contains(username)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);

            } else if (allMembers.contains(groupEntry)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);
            }

        }

        return userGroups;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    } finally {
        close(namingEnumeration);
    }
}

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

/**
 * Called if the LDAP module is installed and active. This method should return:
 * <ul>/*  w w  w.j  a  v  a  2 s.c  om*/
 * <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:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java

private boolean doBind(String sUserID, String sPassword) throws OAException, UserException {
    StringBuffer sbTemp = null;//from  www .  j ava  2s  .c o  m
    DirContext oDirContext = null;
    String sQuery = null;
    String sRelUserDn = null;
    boolean bResult = false;
    NamingEnumeration enumSearchResults = null;

    Hashtable<String, String> htEnvironment = new Hashtable<String, String>();

    htEnvironment.put(Context.PROVIDER_URL, _sJNDIUrl);
    htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, _sDriver);
    htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (_bSSL) {
        htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    if (_sPrincipalDn.length() <= 0)
    // If no principal dn is known, we do a simple binding
    {
        String sEscUserID = JNDIUtil.escapeDN(sUserID);
        _logger.debug("Escaped user: " + sEscUserID);
        sbTemp = new StringBuffer(_sUserDn);
        sbTemp.append('=');
        sbTemp.append(sEscUserID);
        sbTemp.append(", ");
        sbTemp.append(_sBaseDn);
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());

        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            // If supplied credentials are invalid or when authentication fails
            // while accessing the directory or naming service.
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            // If communication with the directory or naming service fails.
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            // The initial dir context could not be created.
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {

            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + '\'', e);
            }
        }
    } else //search through the subtree
    {
        // 1 - Try to bind to LDAP using the security principal's DN and its password
        htEnvironment.put(Context.SECURITY_PRINCIPAL, _sPrincipalDn);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, _sPrincipalPwd);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
        } catch (AuthenticationException eA) {
            _logger.warn("Could not bind to LDAP server", eA);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 2 - Search through the context for user's DN relative to the base DN
        sQuery = resolveSearchQuery(sUserID);

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

        try {
            enumSearchResults = oDirContext.search(_sBaseDn, sQuery, oScope);
        } catch (NamingException eN) {
            _logger.warn("User id not found in password backend for user: " + sUserID, eN);
            throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
        } finally {
            try {

                oDirContext.close();
                oDirContext = null;

            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'", e);
            }
        }

        try {
            if (!enumSearchResults.hasMoreElements()) {
                StringBuffer sb = new StringBuffer("User '");
                sb.append(sUserID);
                sb.append("' not found during LDAP search. The filter was: '");
                sb.append(sQuery);
                sb.append("'");
                _logger.warn(sb.toString());
                throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
            }

            SearchResult searchResult = (SearchResult) enumSearchResults.next();
            sRelUserDn = searchResult.getName();
            if (sRelUserDn == null) {
                _logger.warn("no user dn was returned for '" + sUserID + "'.");
                throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
            }
        } catch (NamingException eN) {

            _logger.warn("failed to fetch profile of user '" + sUserID + "'.", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 3 - Bind user using supplied credentials
        sbTemp = new StringBuffer(sRelUserDn);
        sbTemp.append(",");
        sbTemp.append(_sBaseDn);

        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {
            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'.", e);
            }
        }
    }
    return bResult;
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationSearch(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        String filterExpression, int scope) throws SenderException, ParameterException {
    int timeout = getSearchTimeout();
    SearchControls controls = new SearchControls(scope, getMaxEntriesReturned(), timeout,
            getAttributesReturnedParameter(), false, false);
    //      attrs = parseAttributesFromMessage(message);
    DirContext dirContext = null;
    try {//from w w w . j a v  a2  s .  com
        dirContext = getDirContext(paramValueMap);
        return searchResultsToXml(dirContext.search(entryName, filterExpression, controls)).toXML();
    } catch (NamingException e) {
        if (isReplyNotFound() && e.getMessage().equals("Unprocessed Continuation Reference(s)")) {
            if (log.isDebugEnabled())
                log.debug("Searching object not found using filter[" + filterExpression + "]");
            return DEFAULT_RESULT_SEARCH;
        } else {
            storeLdapException(e, prc);
            throw new SenderException("Exception searching using filter [" + filterExpression + "]", e);
        }
    } finally {
        closeDirContext(dirContext);
    }
}

From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java

/**
 * Gets and returns the entries from the server.
 * //from   w  w w . j a v a2  s.co  m
 * @throws ToolCommandException
 * @throws NamingException
 */
public NamingEnumeration connectToServerAndGetEntries() throws ToolCommandException {
    // Connecting to the LDAP Server
    if (isDebugEnabled()) {
        notifyOutputListener("Connecting to LDAP server");
        notifyOutputListener("Host: " + host);
        notifyOutputListener("Port: " + port);
        notifyOutputListener("User DN: " + user);
        notifyOutputListener("Base DN: " + baseDN);
        notifyOutputListener("Authentication: " + auth);
    }
    Hashtable env = new Hashtable();
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + baseDN);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    DirContext ctx;
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException e) {
        throw new ToolCommandException("Could not connect to the server.\nError: " + e.getMessage());
    }

    // Setting up search scope
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(scope);

    // Fetching entries
    try {
        return ctx.search(exportPoint, "(objectClass=*)", ctls);
    } catch (NamingException e) {
        throw new ToolCommandException("Could not retreive entries");
    }
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected boolean authenticate(String username) throws Exception {
    DirContext context = open();
    try {//from  w ww  . j av a 2s . co m

        String filter = userSearchMatchingFormat.format(new String[] { username });
        SearchControls constraints = new SearchControls();
        if (userSearchSubtreeBool) {
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }

        // setup attributes
        String[] attribs;
        if (userRoleName == null) {
            attribs = new String[] {};
        } else {
            attribs = new String[] { userRoleName };
        }
        constraints.setReturningAttributes(attribs);

        NamingEnumeration results = context.search(userBase, filter, constraints);

        if (results == null || !results.hasMore()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        }

        SearchResult result = (SearchResult) results.next();

        if (results.hasMore()) {
            // ignore for now
        }
        NameParser parser = context.getNameParser("");
        Name contextName = parser.parse(context.getNameInNamespace());
        Name baseName = parser.parse(userBase);
        Name entryName = parser.parse(result.getName());
        Name name = contextName.addAll(baseName);
        name = name.addAll(entryName);
        String dn = name.toString();

        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            return false;
        }
        ArrayList<String> roles = null;
        if (userRoleName != null) {
            roles = addAttributeValues(userRoleName, attrs, roles);
        }
        // check the credentials by binding to server
        // bindUser(context, dn);
        // if authenticated add more roles
        roles = getRoles(context, dn, username, roles);
        for (String role : roles) {
            groups.add(role);
        }
        if (groups.isEmpty()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        } else
            loginSucceeded = true;

    } catch (CommunicationException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    } catch (NamingException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    }
    return true;
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected ArrayList<String> getRoles(DirContext context, String dn, String username, ArrayList<String> list)
        throws NamingException {
    if (list == null) {
        list = new ArrayList<String>();
    }//from  w w w  .  j  av a2s .co m
    if (roleName == null || "".equals(roleName)) {
        return list;
    }
    String filter = roleSearchMatchingFormat.format(new String[] { doRFC2254Encoding(dn), username });

    SearchControls constraints = new SearchControls();
    if (roleSearchSubtreeBool) {
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    } else {
        constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    }
    NamingEnumeration results = context.search(roleBase, filter, constraints);
    while (results.hasMore()) {
        SearchResult result = (SearchResult) results.next();
        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            continue;
        }
        list = addAttributeValues(roleName, attrs, list);
    }
    return list;
}

From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java

public void getAttributes(PIPRequest pipRequest, PIPFinder pipFinder, StdMutablePIPResponse mutablePIPResponse,
        LDAPResolver ldapResolver) throws PIPException {
    /*// w w  w.  j ava2  s  . co m
     * Check with the resolver to get the base string
     */
    String stringBase = ldapResolver.getBase(this, pipRequest, pipFinder);
    if (stringBase == null) {
        this.logger.warn(this.getName() + " does not handle " + pipRequest.toString());
        return;
    }

    /*
     * Get the filter string
     */
    String stringFilter = ldapResolver.getFilterString(this, pipRequest, pipFinder);

    /*
     * Check the cache
     */
    Cache<String, PIPResponse> cache = this.getCache();
    String cacheKey = stringBase + "::" + (stringFilter == null ? "" : stringFilter);
    if (cache != null) {
        PIPResponse pipResponse = cache.getIfPresent(cacheKey);
        if (pipResponse != null) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Returning cached response: " + pipResponse);
            }
            mutablePIPResponse.addAttributes(pipResponse.getAttributes());
            return;
        }
    }
    /*
     * Not in the cache, so set up the LDAP query session
     */
    DirContext dirContext = null;
    PIPResponse pipResponse = null;
    try {
        /*
         * Create the DirContext
         */
        dirContext = new InitialDirContext(this.ldapEnvironment);

        /*
         * Set up the search controls
         */
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(this.ldapScope);

        /*
         * Do the search
         */
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(stringBase, stringFilter,
                searchControls);
        if (namingEnumeration != null && namingEnumeration.hasMore()) {
            while (namingEnumeration.hasMore()) {
                List<Attribute> listAttributes = ldapResolver.decodeResult(namingEnumeration.next());
                if (listAttributes != null && listAttributes.size() > 0) {
                    mutablePIPResponse.addAttributes(listAttributes);
                }
            }
        }
        /*
         * Put in the cache
         */
        if (cache != null) {
            cache.put(cacheKey, pipResponse);
        }
    } catch (NamingException ex) {
        this.logger.error("NamingException creating the DirContext: " + ex.getMessage(), ex);
    } finally {
        if (dirContext != null) {
            try {
                dirContext.close();
            } catch (Exception ex) {
                this.logger.warn("Exception closing DirContext: " + ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.apache.syncope.fit.core.GroupITCase.java

@Test
public void issueSYNCOPE632() {
    DerSchemaTO orig = schemaService.read(SchemaType.DERIVED, "displayProperty");
    DerSchemaTO modified = SerializationUtils.clone(orig);
    modified.setExpression("icon + '_' + show");

    GroupTO groupTO = GroupITCase.getSampleTO("lastGroup");
    try {//from w  w w.j a  va 2 s. com
        schemaService.update(SchemaType.DERIVED, modified);

        // 0. create group
        groupTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        groupTO.getPlainAttrs().add(attrTO("show", "true"));
        groupTO.getResources().clear();

        groupTO = createGroup(groupTO).getEntity();
        assertNotNull(groupTO);

        // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPriority(0);

        for (ProvisionTO provision : newLDAP.getProvisions()) {
            provision.getVirSchemas().clear();
        }

        MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).get().getMapping();

        ItemTO connObjectKey = mapping.getConnObjectKeyItem();
        connObjectKey.setIntAttrName("displayProperty");
        connObjectKey.setPurpose(MappingPurpose.PROPAGATION);
        mapping.setConnObjectKeyItem(connObjectKey);
        mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        ItemTO description = new ItemTO();
        description.setIntAttrName("key");
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.PROPAGATION);
        mapping.add(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. update group and give the resource created above
        GroupPatch patch = new GroupPatch();
        patch.setKey(groupTO.getKey());
        patch.getResources().add(
                new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE).value("new-ldap").build());

        groupTO = updateGroup(patch).getEntity();
        assertNotNull(groupTO);

        // 3. update the group
        GroupPatch groupPatch = new GroupPatch();
        groupPatch.setKey(groupTO.getKey());
        groupPatch.getPlainAttrs().add(attrAddReplacePatch("icon", "anotherIcon"));

        groupTO = updateGroup(groupPatch).getEntity();
        assertNotNull(groupTO);

        // 4. check that a single group exists in LDAP for the group created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + groupTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        schemaService.update(SchemaType.DERIVED, orig);
        if (groupTO.getKey() != null) {
            groupService.delete(groupTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}