Example usage for javax.naming NamingEnumeration next

List of usage examples for javax.naming NamingEnumeration next

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration next.

Prototype

public T next() throws NamingException;

Source Link

Document

Retrieves the next element in the enumeration.

Usage

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

@Override
public void doUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles)
        throws UserStoreException {

    // get the DN of the user entry
    String userNameDN = this.getNameInSpaceForUserName(userName);
    String membershipAttribute = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
    /*/*w w w.  ja  va 2s  .  c  o m*/
     * check deleted roles and delete member entries from relevant groups.
     */
    String errorMessage = null;
    String roleSearchFilter = null;

    DirContext mainDirContext = this.connectionSource.getContext();

    try {
        if (deletedRoles != null && deletedRoles.length != 0) {
            // perform validation for empty role occurrences before
            // updating in LDAP
            // check whether this is shared roles and where shared roles are
            // enable

            for (String deletedRole : deletedRoles) {
                String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER);
                roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole));
                String[] returningAttributes = new String[] { membershipAttribute };
                String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);
                NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                        returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                SearchResult resultedGroup = null;
                if (groupResults.hasMore()) {
                    resultedGroup = groupResults.next();
                }
                if (resultedGroup != null && isOnlyUserInRole(userNameDN, resultedGroup)
                        && !emptyRolesAllowed) {
                    errorMessage = userName + " is the only user in the role: " + deletedRole
                            + ". Hence can not delete user from role.";
                    throw new UserStoreException(errorMessage);
                }

                JNDIUtil.closeNamingEnumeration(groupResults);
            }
            // if empty role violation does not happen, continue
            // updating the LDAP.
            for (String deletedRole : deletedRoles) {

                String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER);

                if (doCheckExistingRole(deletedRole)) {
                    roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole));
                    String[] returningAttributes = new String[] { membershipAttribute };
                    String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);
                    NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                            returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                    SearchResult resultedGroup = null;
                    String groupDN = null;
                    if (groupResults.hasMore()) {
                        resultedGroup = groupResults.next();
                        groupDN = resultedGroup.getName();
                    }
                    modifyUserInRole(userNameDN, groupDN, DirContext.REMOVE_ATTRIBUTE, searchBase);
                    JNDIUtil.closeNamingEnumeration(groupResults);
                } else {
                    errorMessage = "The role: " + deletedRole + " does not exist.";
                    throw new UserStoreException(errorMessage);
                }
            }
        }
        if (newRoles != null && newRoles.length != 0) {

            for (String newRole : newRoles) {
                String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER);

                if (doCheckExistingRole(newRole)) {
                    roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(newRole));
                    String[] returningAttributes = new String[] { membershipAttribute };
                    String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);

                    NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                            returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                    SearchResult resultedGroup = null;
                    // assume only one group with given group name
                    String groupDN = null;
                    if (groupResults.hasMore()) {
                        resultedGroup = groupResults.next();
                        groupDN = resultedGroup.getName();
                    }
                    if (resultedGroup != null && !isUserInRole(userNameDN, resultedGroup)) {
                        modifyUserInRole(userNameDN, groupDN, DirContext.ADD_ATTRIBUTE, searchBase);
                    } else {
                        errorMessage = "User: " + userName + " already belongs to role: " + groupDN;
                        throw new UserStoreException(errorMessage);
                    }

                    JNDIUtil.closeNamingEnumeration(groupResults);

                } else {
                    errorMessage = "The role: " + newRole + " does not exist.";
                    throw new UserStoreException(errorMessage);
                }
            }
        }

    } catch (NamingException e) {
        errorMessage = "Error occurred while modifying the role list of user: " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(mainDirContext);
    }
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

/**
 * Check whether user is in the group by searching through its member attributes.
 *
 * @param userDN/*  w w  w. jav  a  2s . c o m*/
 * @param groupEntry
 * @return
 * @throws UserStoreException
 */
protected boolean isUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException {
    boolean isUserInRole = false;
    try {
        Attributes groupAttributes = groupEntry.getAttributes();
        if (groupAttributes != null) {
            // get group's returned attributes
            NamingEnumeration attributes = groupAttributes.getAll();
            // loop through attributes
            while (attributes.hasMoreElements()) {
                Attribute memberAttribute = (Attribute) attributes.next();
                String memberAttributeName = realmConfig
                        .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                if (memberAttributeName.equalsIgnoreCase(memberAttribute.getID())) {
                    // loop through attribute values
                    for (int i = 0; i < memberAttribute.size(); i++) {
                        if (userDN.equalsIgnoreCase((String) memberAttribute.get(i))) {
                            return true;
                        }
                    }
                }

            }

            attributes.close();
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while looping through attributes set of group: "
                + groupEntry.getNameInNamespace();
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return isUserInRole;
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }/* w ww.j  a v a2 s.c  o m*/
    SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    InitialDirContext ctx = null;

    for (String userSearchBase : this.userSearchBases) {

        String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))";

        NamingEnumeration<SearchResult> searchResults = null;
        SearchResult result = null;

        try {
            ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

            // Execute the user query with an additional condition that ensures only the user with the required ID is
            // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation

            searchResults = ctx.search(userSearchBase,
                    "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))",
                    new Object[] { userId }, userSearchCtls);

            if (searchResults.hasMore()) {
                result = searchResults.next();
                Attributes attributes = result.getAttributes();
                Attribute uidAttribute = attributes.get(this.userIdAttributeName);
                if (uidAttribute == null) {
                    if (this.errorOnMissingUID) {
                        throw new AlfrescoRuntimeException(
                                "User returned by user search does not have mandatory user id attribute "
                                        + attributes);
                    } else {
                        LDAPMultiBaseUserRegistry.logger
                                .warn("User returned by user search does not have mandatory user id attribute "
                                        + attributes);
                    }
                }
                // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
                // only resolve this user if the user ID matches
                else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                    String name = result.getNameInNamespace();

                    // Close the contexts, see ALF-20682
                    Context context = (Context) result.getObject();
                    if (context != null) {
                        context.close();
                    }
                    result = null;
                    return name;
                }

                // Close the contexts, see ALF-20682
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
                result = null;
            }
        } catch (NamingException e) {
            // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory

            Object[] args1 = { userId, query };
            diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);
        }

        if (result != null) {
            try {
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
    }

    if (ctx != null) {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.debug("error when closing ldap context", e);
        }
    }

    // failed to search
    //        Object[] args = {e.getLocalizedMessage()};
    throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic);
}

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)
 *///w  ww.  j  a  v a  2  s  . 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;
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }/*  w  ww. j a v a 2  s.  c om*/
    SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName
            + "= userId))";

    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;

    InitialDirContext ctx = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

        // Execute the user query with an additional condition that ensures only the user with the required ID is
        // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation            

        searchResults = ctx.search(this.userSearchBase,
                "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId },
                userSearchCtls);

        if (searchResults.hasMore()) {
            result = searchResults.next();
            Attributes attributes = result.getAttributes();
            Attribute uidAttribute = attributes.get(this.userIdAttributeName);
            if (uidAttribute == null) {
                if (this.errorOnMissingUID) {
                    throw new AlfrescoRuntimeException(
                            "User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                } else {
                    LDAPUserRegistry.logger
                            .warn("User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                }
            }
            // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
            // only resolve this user if the user ID matches
            else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                String name = result.getNameInNamespace();

                // Close the contexts, see ALF-20682
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
                result = null;
                return name;
            }

            // Close the contexts, see ALF-20682
            Context context = (Context) result.getObject();
            if (context != null) {
                context.close();
            }
            result = null;
        }

        Object[] args = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args);

        throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic);
    } catch (NamingException e) {
        // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory

        Object[] args1 = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);

        // failed to search
        Object[] args = { e.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e);
    } finally {
        if (result != null) {
            try {
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                logger.debug("error when closing ldap context", e);
            }
        }
    }
}

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

/**
 * Returns the values of the specified fields for the supplied id. 
 * @see IExternalStorage#getFields(java.lang.String, java.util.List)
 */// www. j  a  v a  2s .c o  m
public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException {
    Hashtable<String, Object> htReturn = new Hashtable<String, Object>();
    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 UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] saFields = fields.toArray(new String[0]);
        oScope.setReturningAttributes(saFields);

        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 attributes '");
            sbFailed.append(fields);
            sbFailed.append("' for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, 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 neAttributes = oAttributes.getAll();
        while (neAttributes.hasMore()) {
            Attribute oAttribute = (Attribute) neAttributes.next();
            String sAttributeName = oAttribute.getID();

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

                htReturn.put(sAttributeName, vValue);
            } else {
                Object oValue = oAttribute.get();
                if (oValue == null)
                    oValue = "";
                htReturn.put(sAttributeName, oValue);
            }
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields: " + fields, 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 htReturn;
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

/**
 * Update role list of user by writing to LDAP.
 *
 * @param userName//from  ww w  . ja  v  a2 s  . c  o  m
 * @param deletedRoles
 * @param newRoles
 * @throws UserStoreException
 */
@SuppressWarnings("deprecation")
@Override
public void doUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles)
        throws UserStoreException {

    // get the DN of the user entry
    String userNameDN = this.getNameInSpaceForUserName(userName);
    String membershipAttribute = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);

    /*
     * check deleted roles and delete member entries from relevant groups.
     */
    String errorMessage = null;
    String roleSearchFilter = null;

    DirContext mainDirContext = this.connectionSource.getContext();

    try {
        if (deletedRoles != null && deletedRoles.length != 0) {
            // perform validation for empty role occurrences before
            // updating in LDAP
            // check whether this is shared roles and where shared roles are
            // enable

            for (String deletedRole : deletedRoles) {
                LDAPRoleContext context = (LDAPRoleContext) createRoleContext(deletedRole);
                deletedRole = context.getRoleName();
                String searchFilter = context.getSearchFilter();
                roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole));
                String[] returningAttributes = new String[] { membershipAttribute };
                String searchBase = context.getSearchBase();
                NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                        returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                SearchResult resultedGroup = null;
                if (groupResults.hasMore()) {
                    resultedGroup = groupResults.next();
                }
                if (resultedGroup != null && isOnlyUserInRole(userNameDN, resultedGroup)
                        && !emptyRolesAllowed) {
                    errorMessage = userName + " is the only user in the role: " + deletedRole
                            + ". Hence can not delete user from role.";
                    throw new UserStoreException(errorMessage);
                }

                JNDIUtil.closeNamingEnumeration(groupResults);
            }
            // if empty role violation does not happen, continue
            // updating the LDAP.
            for (String deletedRole : deletedRoles) {

                LDAPRoleContext context = (LDAPRoleContext) createRoleContext(deletedRole);
                deletedRole = context.getRoleName();
                String searchFilter = context.getSearchFilter();

                if (isExistingRole(deletedRole)) {
                    roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole));
                    String[] returningAttributes = new String[] { membershipAttribute };
                    String searchBase = context.getSearchBase();
                    NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                            returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                    SearchResult resultedGroup = null;
                    String groupDN = null;
                    if (groupResults.hasMore()) {
                        resultedGroup = groupResults.next();
                        groupDN = resultedGroup.getName();
                    }
                    this.modifyUserInRole(userNameDN, groupDN, DirContext.REMOVE_ATTRIBUTE, searchBase);

                    JNDIUtil.closeNamingEnumeration(groupResults);

                    // need to update authz cache of user since roles
                    // are deleted
                    userRealm.getAuthorizationManager().clearUserAuthorization(userName);

                } else {
                    errorMessage = "The role: " + deletedRole + " does not exist.";
                    throw new UserStoreException(errorMessage);
                }
            }
        }
        if (newRoles != null && newRoles.length != 0) {

            for (String newRole : newRoles) {

                LDAPRoleContext context = (LDAPRoleContext) createRoleContext(newRole);
                newRole = context.getRoleName();
                String searchFilter = context.getSearchFilter();

                if (isExistingRole(newRole)) {
                    roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(newRole));
                    String[] returningAttributes = new String[] { membershipAttribute };
                    String searchBase = context.getSearchBase();

                    NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                            returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                    SearchResult resultedGroup = null;
                    // assume only one group with given group name
                    String groupDN = null;
                    if (groupResults.hasMore()) {
                        resultedGroup = groupResults.next();
                        groupDN = resultedGroup.getName();
                    }
                    if (resultedGroup != null && !isUserInRole(userNameDN, resultedGroup)) {
                        modifyUserInRole(userNameDN, groupDN, DirContext.ADD_ATTRIBUTE, searchBase);
                    } else {
                        errorMessage = "User: " + userName + " already belongs to role: " + groupDN;
                        throw new UserStoreException(errorMessage);
                    }

                    JNDIUtil.closeNamingEnumeration(groupResults);

                } else {
                    errorMessage = "The role: " + newRole + " does not exist.";
                    throw new UserStoreException(errorMessage);
                }
            }
        }

    } catch (NamingException e) {
        errorMessage = "Error occurred while modifying the role list of user: " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(mainDirContext);
    }
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

protected void deleteLDAPRole(RoleContext context) throws UserStoreException {

    String roleName = context.getRoleName();
    String groupSearchFilter = ((LDAPRoleContext) context).getSearchFilter();
    groupSearchFilter = groupSearchFilter.replace("?", escapeSpecialCharactersForFilter(context.getRoleName()));
    String[] returningAttributes = { ((LDAPRoleContext) context).getRoleNameProperty() };
    String searchBase = ((LDAPRoleContext) context).getSearchBase();

    DirContext mainDirContext = null;
    DirContext groupContext = null;
    NamingEnumeration<SearchResult> groupSearchResults = null;

    try {/*from  ww  w .  java2  s . co  m*/

        mainDirContext = this.connectionSource.getContext();
        groupSearchResults = searchInGroupBase(groupSearchFilter, returningAttributes,
                SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
        SearchResult resultedGroup = null;
        while (groupSearchResults.hasMoreElements()) {
            resultedGroup = groupSearchResults.next();
        }

        if (resultedGroup == null) {
            throw new UserStoreException("Could not find specified group/role - " + roleName);
        }

        String groupName = resultedGroup.getName();

        groupContext = (DirContext) mainDirContext.lookup(groupSearchBase);
        String groupNameAttributeValue = (String) resultedGroup.getAttributes()
                .get(realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE)).get();
        if (groupNameAttributeValue.equals(roleName)) {
            groupContext.destroySubcontext(groupName);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while deleting the role: " + roleName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(groupSearchResults);
        JNDIUtil.closeContext(groupContext);
        JNDIUtil.closeContext(mainDirContext);
    }

}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * {@inheritDoc}// w ww .j  a va2s.co m
 */
public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    String[] userNames = new String[0];

    if (maxItemLimit == 0) {
        return userNames;
    }

    int givenMax;
    int searchTime;

    try {
        givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST));
    } catch (Exception e) {
        givenMax = CommonConstants.MAX_USER_LIST;
    }

    try {
        searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME));
    } catch (Exception e) {
        searchTime = CommonConstants.MAX_SEARCH_TIME;
    }

    if (maxItemLimit <= 0 || maxItemLimit > givenMax) {
        maxItemLimit = givenMax;
    }

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);
    searchCtls.setTimeLimit(searchTime);

    if (filter.contains("?") || filter.contains("**")) {
        throw new UserStoreException(
                "Invalid character sequence entered for user search. Please enter valid sequence.");
    }

    StringBuilder searchFilter = new StringBuilder(
            userStoreProperties.get(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE);

    String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE);

    String serviceNameAttribute = "sn";

    StringBuilder finalFilter = new StringBuilder();

    // read the display name attribute - if provided
    String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE);

    String[] returnedAtts;

    if (StringUtils.isNotEmpty(displayNameAttribute)) {
        returnedAtts = new String[] { userNameProperty, serviceNameAttribute, displayNameAttribute };
        finalFilter.append("(&").append(searchFilter).append("(").append(displayNameAttribute).append("=")
                .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");
    } else {
        returnedAtts = new String[] { userNameProperty, serviceNameAttribute };
        finalFilter.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=")
                .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");
    }

    if (debug) {
        log.debug(
                "Listing users. SearchBase: " + searchBases + " Constructed-Filter: " + finalFilter.toString());
        log.debug("Search controls. Max Limit: " + maxItemLimit + " Max Time: " + searchTime);
    }

    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    List<String> list = new ArrayList<>();

    try {
        dirContext = connectionSource.getContext();
        // handle multiple search bases
        String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR);

        for (String searchBase : searchBaseArray) {

            answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (sr.getAttributes() != null) {
                    log.debug("Result found ..");
                    Attribute attr = sr.getAttributes().get(userNameProperty);

                    // If this is a service principle, just ignore and
                    // iterate rest of the array. The entity is a service if
                    // value of surname is Service

                    Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute);

                    if (attrSurname != null) {
                        if (debug) {
                            log.debug(serviceNameAttribute + " : " + attrSurname);
                        }
                        String serviceName = (String) attrSurname.get();
                        if (serviceName != null
                                && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) {
                            continue;
                        }
                    }

                    if (attr != null) {
                        String name = (String) attr.get();
                        list.add(name);
                    }
                }
            }
        }
        userNames = list.toArray(new String[list.size()]);
        Arrays.sort(userNames);

        if (debug) {
            for (String username : userNames) {
                log.debug("result: " + username);
            }
        }
    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : "
                + maxItemLimit;
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : "
                + maxItemLimit;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return userNames;
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

@Override
public void doDeleteUserClaimValues(String userName, String[] claims, String profileName)
        throws UserStoreException {
    // get the LDAP Directory context
    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // search the relevant user entry by user name
    String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

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

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = null;

    try {/*ww  w  . ja va 2 s . c  om*/

        returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter,
                searchControls);
        // assume only one user is returned from the search
        // TODO:what if more than one user is returned
        if (returnedResultList.hasMore()) {
            returnedUserEntry = returnedResultList.next().getName();
        }

    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(returnedResultList);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);
        // if there is no attribute for profile configuration in LDAP, skip
        // updating it.
        // get the claimMapping related to this claimURI

        for (String claimURI : claims) {
            String attributeName = getClaimAtrribute(claimURI, userName, null);
            Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
            updatedAttributes.put(currentUpdatedAttribute);
        }

        subDirContext = (DirContext) dirContext.lookup(userSearchBase);
        subDirContext.modifyAttributes(returnedUserEntry, DirContext.REMOVE_ATTRIBUTE, updatedAttributes);

    } catch (Exception e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}