Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

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

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

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

public boolean hasRole(DirContext context, String roleName) throws MappingException {
    String groupName = findGroupName(roleName);

    if (groupName == null) {
        if (this.useDefaultRoleName) {
            groupName = roleName;/* w w  w  . j  a v  a2  s. c o m*/
        } else {
            log.warn("skip group creation as no mapping for roleName:'{}'", roleName);
            return false;
        }
    }
    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {

        SearchControls searchControls = new SearchControls();

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

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

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

        return namingEnumeration.hasMore();
    } catch (NameNotFoundException e) {
        log.debug("group {} for role {} not found", groupName, roleName);
        return false;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        close(namingEnumeration);
    }
}

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

@Override
public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException {

    if (!isSSLConnection) {
        logger.warn("Unsecured connection is being used. Password operations will fail");
    }/*from  ww  w.j  a  v a  2s  .  co m*/

    DirContext dirContext = this.connectionSource.getContext();
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER);
    String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "="
            + escapeSpecialCharactersForFilter(userName) + "))";
    SearchControls searchControl = new SearchControls();
    String[] returningAttributes = { "CN" };
    searchControl.setReturningAttributes(returningAttributes);
    searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE);

    DirContext subDirContext = null;
    NamingEnumeration<SearchResult> searchResults = null;
    try {
        // search the user with UserNameAttribute and obtain its CN attribute
        searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl);
        SearchResult user = null;
        int count = 0;
        while (searchResults.hasMore()) {
            if (count > 0) {
                throw new UserStoreException(
                        "There are more than one result in the user store " + "for user: " + userName);
            }
            user = searchResults.next();
            count++;
        }
        String userCNValue = null;
        if (user.getAttributes() != null) {
            Attribute cnAttribute = user.getAttributes().get("CN");
            if (cnAttribute != null) {
                userCNValue = (String) cnAttribute.get();
            } else {
                throw new UserStoreException("Can not update credential: CN attribute is null");
            }
        }

        ModificationItem[] mods = null;

        if (newCredential != null) {
            mods = new ModificationItem[1];
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                            createUnicodePassword((String) newCredential)));

            subDirContext = (DirContext) dirContext.lookup(searchBase);
            subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods);
        }

    } catch (NamingException e) {
        String error = "Can not access the directory service for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(error, e);
        }
        throw new UserStoreException(error, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(searchResults);
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Fetches the supplied user.// w w w  .  j  a  v  a  2 s .co m
 *
 * @param attrValue the user id
 * @return the user id for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 */
protected String selectUser(String attrId, String attrValue) throws NamingException {
    String uidValue = null;

    InitialLdapContext ctx = createLdapInitialContext();

    String uidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + attrId + "=" + attrValue + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(uidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user attrValue attribute '" + uidAttrName + "'");
                continue;
            }

            uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user '" + uidAttrName + "=" + uidValue + "' for user '" + attrValue + "'");
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for user '" + attrValue + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return uidValue;
}

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

public boolean removeUserRole(String roleName, String username, DirContext context) throws MappingException {
    String groupName = findGroupName(roleName);

    if (groupName == null) {
        log.warn("no group found for role '{}", roleName);
        return false;
    }/*w  w  w. jav a  2  s.  c  om*/

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {

        SearchControls searchControls = new SearchControls();

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

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

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

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

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

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

From source file: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)
 *//*w  w  w.ja v  a  2 s . co m*/
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:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

/**
 *
 *//*from  ww  w  .  jav a  2s . c o  m*/
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
        throws UserStoreException {

    if (!isSSLConnection) {
        logger.warn("Unsecured connection is being used. Password operations will fail");
    }

    DirContext dirContext = this.connectionSource.getContext();
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER);
    String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    // String searchFilter =
    // realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "="
            + escapeSpecialCharactersForFilter(userName) + "))";

    SearchControls searchControl = new SearchControls();
    String[] returningAttributes = { "CN" };
    searchControl.setReturningAttributes(returningAttributes);
    searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext subDirContext = null;
    NamingEnumeration<SearchResult> searchResults = null;
    try {
        // search the user with UserNameAttribute and obtain its CN attribute
        searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl);
        SearchResult user = null;
        int count = 0;
        while (searchResults.hasMore()) {
            if (count > 0) {
                throw new UserStoreException(
                        "There are more than one result in the user store " + "for user: " + userName);
            }
            user = searchResults.next();
            count++;
        }
        String userCNValue = null;
        if (user.getAttributes() != null) {
            Attribute cnAttribute = user.getAttributes().get("CN");
            if (cnAttribute != null) {
                userCNValue = (String) cnAttribute.get();
            } else {
                throw new UserStoreException("Can not update credential: CN attribute is null");
            }
        }

        ModificationItem[] mods = null;

        // The user tries to change his own password
        if (oldCredential != null && newCredential != null) {
            mods = new ModificationItem[1];
            /*
            * byte[] oldUnicodePassword = createUnicodePassword((String) oldCredential); byte[]
            * newUnicodePassword = createUnicodePassword((String) newCredential);
            */
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                            createUnicodePassword((String) newCredential)));
            /*
             * mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(
             * LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, newUnicodePassword));
             */
        }
        subDirContext = (DirContext) dirContext.lookup(searchBase);
        subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods);

    } catch (NamingException e) {
        String error = "Can not access the directory service for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(error, e);
        }
        throw new UserStoreException(error, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(searchResults);
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

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

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

    String groupName = findGroupName(roleName);

    if (groupName == null) {
        log.warn("no group found for role '{}", roleName);
        groupName = roleName;/*from w w  w .ja  v a 2  s .co  m*/
    }

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

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

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

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

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

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

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

From source file:org.olat.ldap.LDAPLoginManagerImpl.java

/**
 * Creates User in OLAT and ads user to LDAP securityGroup Required Attributes have to be checked before this method.
 * //  w ww.  j a  v  a  2 s. c o  m
 * @param userAttributes Set of LDAP Attribute of User to be created
 */
@SuppressWarnings("unchecked")
public void createAndPersistUser(final Attributes userAttributes) {
    // Get and Check Config
    final String[] reqAttrs = LDAPLoginModule.checkReqAttr(userAttributes);
    if (reqAttrs != null) {
        logWarn("Can not create and persist user, the following attributes are missing::"
                + ArrayUtils.toString(reqAttrs), null);
        return;
    }

    final String uid = getAttributeValue(userAttributes
            .get(LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER)));
    final String email = getAttributeValue(
            userAttributes.get(LDAPLoginModule.mapOlatPropertyToLdapAttribute(UserConstants.EMAIL)));
    // Lookup user
    if (securityManager.findIdentityByName(uid) != null) {
        logError("Can't create user with username='" + uid + "', does already exist in OLAT database", null);
        return;
    }
    if (!MailHelper.isValidEmailAddress(email)) {
        // needed to prevent possibly an AssertException in findIdentityByEmail breaking the sync!
        logError("Cannot try to lookup user " + uid + " by email with an invalid email::" + email, null);
        return;
    }
    if (userManager.findIdentityByEmail(email) != null) {
        logError("Can't create user with email='" + email + "', does already exist in OLAT database", null);
        return;
    }

    // Create User (first and lastname is added in next step)
    final User user = userManager.createUser(null, null, email);
    // Set User Property's (Iterates over Attributes and gets OLAT Property out
    // of olatexconfig.xml)
    final NamingEnumeration<Attribute> neAttr = (NamingEnumeration<Attribute>) userAttributes.getAll();
    try {
        while (neAttr.hasMore()) {
            final Attribute attr = neAttr.next();
            final String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (attr.get() != uid) {
                final String ldapValue = getAttributeValue(attr);
                if (olatProperty == null || ldapValue == null) {
                    continue;
                }
                user.setProperty(olatProperty, ldapValue);
            }
        }
        // Add static user properties from the configuration
        final Map<String, String> staticProperties = LDAPLoginModule.getStaticUserProperties();
        if (staticProperties != null && staticProperties.size() > 0) {
            for (final Entry<String, String> staticProperty : staticProperties.entrySet()) {
                user.setProperty(staticProperty.getKey(), staticProperty.getValue());
            }
        }
    } catch (final NamingException e) {
        logError("NamingException when trying to create and persist LDAP user with username::" + uid, e);
        return;
    } catch (final Exception e) {
        // catch any exception here to properly log error
        logError("Unknown exception when trying to create and persist LDAP user with username::" + uid, e);
        return;
    }

    // Create Identity
    final Identity identity = securityManager.createAndPersistIdentityAndUser(uid, user,
            LDAPAuthenticationController.PROVIDER_LDAP, uid, null);
    // Add to SecurityGroup LDAP
    SecurityGroup secGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    // Add to SecurityGroup OLATUSERS
    secGroup = securityManager.findSecurityGroupByName(Constants.GROUP_OLATUSERS);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    logInfo("Created LDAP user username::" + uid);

}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Fetches the supplied user DN./*from w  w w .  j a v  a  2s  . c  o m*/
 *
 * @param uid the user id
 * @return the user DN for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 */
protected String selectUserDN(InitialLdapContext ctx, String uid) throws NamingException {

    String dn = null;

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :

        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(principalUidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'");
                continue;
            }

            String uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                dn = sr.getName() + "," + usersCtxDN;
                if (logger.isDebugEnabled())
                    logger.debug("Found user '" + principalUidAttrName + "=" + uidValue + "' for user '" + uid
                            + "' DN=" + dn);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for user '" + uid + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    }

    return dn;

}

From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java

protected void updateRootDN(DirContext dirContext, SearchControls controls) {
    String ldapRootDN = getRootDN();
    NamingEnumeration<SearchResult> namingEnum = null;
    try {// w  w w.  j a v a  2  s  . co m
        boolean schemaExists = false;
        String name = null;
        String base = null;
        try {
            int index = ldapRootDN.indexOf(",");
            if (index == -1) {
                throw new RuntimeException("Expected to find at least one comma in the rootDN");
            } else {
                name = ldapRootDN.substring(0, index);
                base = ldapRootDN.substring(index + 1);
            }
            namingEnum = dirContext.search(base, name, controls);
            schemaExists = namingEnum.hasMore();
        } catch (NamingException ex) {
            throw new RuntimeException("Could find rootDN schema", ex);
        }
        if (schemaExists) {
            logger.info("LDAP schema for " + ldapRootDN + " already exists");
        } else {
            String dn = name + "," + base;
            Attributes attributes = new BasicAttributes();
            Attribute objclass = new BasicAttribute("objectclass");
            objclass.add("organizationalRole");
            attributes.put(objclass);
            attributes.put(name.substring(0, name.indexOf("=")), name.substring(name.indexOf("=") + 1));
            try {
                dirContext.createSubcontext(dn, attributes);
            } catch (NamingException ex) {
                throw new RuntimeException("Could not create rootDN schema", ex);
            }
            logger.info("Created LDAP schema for " + ldapRootDN);
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } catch (NamingException ex) {
                throw new RuntimeException("Could not close the naming enumeration for the ldap rootDN schema",
                        ex);
            }
        }
    }
}