Example usage for javax.naming NamingEnumeration hasMoreElements

List of usage examples for javax.naming NamingEnumeration hasMoreElements

Introduction

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

Prototype

boolean hasMoreElements();

Source Link

Document

Tests if this enumeration contains more elements.

Usage

From source file:openscim.restful.server.resources.group.ldap.GroupAttributesMapper.java

public Object mapFromAttributes(Attributes attributes) throws NamingException {
    // create a group resource
    Group group = ResourceUtilities.FACTORY.createGroup();

    // get the gid attribute name
    String gidAtttributeName = properties.getProperty(GID_ATTRIBUTE, DEFAULT_GID_ATTRIBUTE);

    // get the gid      
    Attribute gidAttribute = attributes.get(gidAtttributeName);
    if (gidAttribute != null)
        group.setId((String) gidAttribute.get());

    // get the member attribute name
    String memberAtttributeName = properties.getProperty(MEMBER_ATTRIBUTE, DEFAULT_MEMBER_ATTRIBUTE);

    // get the members
    NamingEnumeration memberEnumeration = attributes.get(memberAtttributeName).getAll();
    if (memberEnumeration != null) {
        // create a members resource
        List<PluralAttribute> members = new ArrayList<PluralAttribute>();

        while (memberEnumeration.hasMoreElements()) {
            // get the next member
            String memberAttribute = (String) memberEnumeration.next();
            if (memberAttribute != null) {
                PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute();

                // check if the member dns need to be concealed 
                if (properties
                        .getProperty(GroupAttributesMapper.CONCEAL_GROUP_DNS,
                                GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)
                        .equalsIgnoreCase(GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)) {
                    Matcher matcher = pattern.matcher(memberAttribute);
                    if (matcher.matches()) {
                        memberAttribute = matcher.group(1);
                    }/*from w  w w.j av  a2  s .co m*/
                }

                pluralAttribute.setValue(memberAttribute);
                members.add(pluralAttribute);
            }
        }

        // add the members to the group resource
        group.setAny(members);
    }

    return group;
}

From source file:com.healthcit.cacure.businessdelegates.LdapUserManager.java

public List<UserCredentials> getAllUsers() {

    List<UserCredentials> userCredentials = new ArrayList<UserCredentials>();

    try {/*w  w w  . ja va  2  s.c  o  m*/

        SearchControls searchCtls = new SearchControls();
        String returnedAtts[] = { "uid" };
        searchCtls.setReturningAttributes(returnedAtts);
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchFilter = "(&(objectClass=person))";

        NamingEnumeration<SearchResult> elements = contextSource.getReadOnlyContext().search("", searchFilter,
                searchCtls);

        while (elements.hasMoreElements()) {
            DistinguishedName dn = new DistinguishedName(elements.nextElement().getName());
            String userName = dn.getValue("uid");
            userCredentials.add(getUserFromDatabase(userName));
        }

    } catch (org.springframework.ldap.NamingException e) {
        e.printStackTrace();
        return null;
    } catch (NamingException e) {
        e.printStackTrace();
        return null;
    }

    return userCredentials;

}

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

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);//from ww  w  .ja  v  a  2s  .  c o m
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

From source file:eu.uqasar.util.ldap.LdapManager.java

private LdapUser getUserByDNAndFilter(final String userDN, final String filter) throws NamingException {
    final String dnFilter = "(distinguishedName=" + userDN + ")";
    boolean conjunction = filter.startsWith("(&(") && filter.endsWith("))");
    String endFilter;/*from w  w w  .  ja v  a  2  s.  co  m*/
    if (conjunction) {
        endFilter = filter.substring(0, filter.length() - 1) + dnFilter + ")";
    } else {
        endFilter = dnFilter;
    }
    NamingEnumeration<SearchResult> answer = getContext().search(settings.getUserFilterBaseDN(), endFilter,
            getDefaultSearchControls());
    while (answer.hasMoreElements()) {
        Attributes attr = answer.next().getAttributes();
        if (hasRequiredUserAttributesFilled(attr, settings)) {
            return new LdapUser(attr, settings);
        }
    }
    return null;
}

From source file:net.identio.server.service.authentication.ldap.LdapAuthenticationProvider.java

public AuthenticationResult validate(AuthMethod authMethod, Authentication authentication,
        TransactionData transactionData) {

    LdapAuthMethod ldapAuthMethod = (LdapAuthMethod) authMethod;
    UserPasswordAuthentication userPwAuthentication = (UserPasswordAuthentication) authentication;

    boolean validation;

    String userId = userPwAuthentication.getUserId();
    String password = userPwAuthentication.getPassword();

    GenericObjectPool<InitialLdapContext> pool = pools.get(authMethod.getName());

    InitialLdapContext ctx = null;

    try {// w  w  w .j a v a 2 s  .co  m
        ctx = pool.borrowObject();

        // First we search the user
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = ldapAuthMethod.getUserSearchFilter().replace("#UID",
                SecurityUtils.escapeLDAPSearchFilter(userId));

        NamingEnumeration<SearchResult> results = ctx.search(ldapAuthMethod.getBaseDn(), searchFilter,
                controls);

        SearchResult result;

        if (results.hasMoreElements()) {
            result = results.next();

            if (results.hasMoreElements()) {
                LOG.error("User ID {} is not unique in LDAP {}", userId, authMethod.getName());
                return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                        .setErrorStatus(AuthenticationErrorStatus.USER_NOT_UNIQUE);
            }
        } else {
            LOG.error("User ID {} does not exist in LDAP {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                    .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS);
        }

        // Try to bind with the found user id
        validation = ((LdapConnectionFactory) pool.getFactory()).authenticate(authMethod.getName(),
                result.getNameInNamespace(), password);

        pool.returnObject(ctx);

        if (validation) {
            LOG.info("User {} successfully authenticated with {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.SUCCESS).setUserId(userId)
                    .setAuthMethod(authMethod).setAuthLevel(authMethod.getAuthLevel());
        } else {
            LOG.error("Authentication failed for user {} with {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                    .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS);
        }

    } catch (Exception ex) {

        // Discard context
        try {
            if (ctx != null) {
                pool.invalidateObject(ctx);
            }
        } catch (Exception ex2) {
            LOG.error("An error occurend when authenticating user");
        }

        return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                .setErrorStatus(AuthenticationErrorStatus.TECHNICAL_ERROR);
    }

}

From source file:eu.uqasar.util.ldap.LdapManager.java

private LdapUser getUserByDN(final String userDN) throws NamingException {
    NamingEnumeration<SearchResult> answer = getContext().search(settings.getUserFilterBaseDN(),
            "(distinguishedName=" + userDN + ")", getDefaultSearchControls());
    while (answer.hasMoreElements()) {
        Attributes attr = answer.next().getAttributes();
        if (hasRequiredUserAttributesFilled(attr, settings)) {
            return new LdapUser(attr, settings);
        }//w ww  .  j a v a  2 s .  co m
    }
    return null;
}

From source file:eu.uqasar.util.ldap.LdapManager.java

private LdapUser getUserBySAMAccountName(final String sAMAccountName) throws NamingException {
    NamingEnumeration<SearchResult> answer = getContext().search(settings.getUserFilterBaseDN(),
            "(sAMAccountName=" + sAMAccountName + ")", getDefaultSearchControls());
    while (answer.hasMoreElements()) {
        Attributes attr = answer.next().getAttributes();
        if (hasRequiredUserAttributesFilled(attr, settings)) {
            return new LdapUser(attr, settings);
        }//  ww  w  .  j  a  v a 2 s  .com
    }
    return null;
}

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

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);/*  w  w w  .  j a  v  a 2s  .com*/
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);
    // NamingEnumeration<SearchResult> results = context.search( suffix, "(" + attribute + "=" + value + ")", ctls
    // );

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

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

/**
 * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#userExists(String, javax.naming.directory.DirContext)
 *///from   www.ja va 2s  .  co m
public boolean userExists(String key, DirContext context) throws LdapControllerException {
    NamingEnumeration<SearchResult> results = null;
    try {
        results = searchUsers(key, context);
        return results.hasMoreElements();
    } catch (NamingException e) {
        throw new LdapControllerException("Error searching for the existence of user: " + key, e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (NamingException e) {
                log.warn("Error closing search results", e);
            }
        }
    }
}

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

/**
 * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#getUser(String, javax.naming.directory.DirContext)
 *///from  w  w w .j  a  va2s  .  co  m
public LdapUser getUser(String username, DirContext context) throws LdapControllerException, MappingException {

    log.debug("Searching for user: {}", username);

    LdapUserQuery query = new LdapUserQuery();
    query.setUsername(username);

    NamingEnumeration<SearchResult> result = null;
    try {
        result = searchUsers(context, null, query);

        if (result.hasMoreElements()) {
            SearchResult next = result.nextElement();

            log.info("Found user: {}", username);

            return mapper.getUser(next.getAttributes());
        } else {
            return null;
        }
    } catch (NamingException e) {
        String message = "Failed to retrieve information for user: " + username;

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