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.user.ldap.UserAttributesMapper.java

public Object mapFromAttributes(Attributes attributes) throws NamingException {
    // create a user resource
    User user = ResourceUtilities.FACTORY.createUser();

    // get the uid attribute name
    String uidAtttributeName = properties.getProperty(UID_ATTRIBUTE, DEFAULT_UID_ATTRIBUTE);

    // get the uid
    //Attribute uidAttribute = attributes.get(uidAtttributeName);
    //if(uidAttribute != null) user.setId((String)uidAttribute.get());

    // get the display name attribute name
    String displayAtttributeName = properties.getProperty(DISPLAYNAME_ATTRIBUTE, DEFAULT_DISPLAYNAME_ATTRIBUTE);

    // get the display name
    Attribute displayNameAttribute = attributes.get(displayAtttributeName);
    if (displayNameAttribute != null)
        user.setDisplayName((String) displayNameAttribute.get());

    // create a user name resource
    Name name = ResourceUtilities.FACTORY.createName();

    // get the surname attribute name
    String surnameAtttributeName = properties.getProperty(FAMILYNAME_ATTRIBUTE, DEFAULT_FAMILYNAME_ATTRIBUTE);

    // get the surname name
    Attribute surnameAttribute = attributes.get(surnameAtttributeName);
    if (surnameAttribute != null)
        name.setFamilyName((String) surnameAttribute.get());

    // get the given name attribute name
    String givenAtttributeName = properties.getProperty(GIVENNAME_ATTRIBUTE, DEFAULT_GIVENNAME_ATTRIBUTE);

    // get the given name
    Attribute givenAttribute = attributes.get(givenAtttributeName);
    if (givenAttribute != null)
        name.setGivenName((String) givenAttribute.get());

    // add the name to the user resource
    user.setName(name);/* ww w  .  ja  v  a 2s  .c  om*/

    // get the email attribute name
    String mailAtttributeName = properties.getProperty(MAIL_ATTRIBUTE, DEFAULT_MAIL_ATTRIBUTE);

    // get the mails
    if (attributes.get(mailAtttributeName) != null) {
        NamingEnumeration mailEnumeration = attributes.get(mailAtttributeName).getAll();
        if (mailEnumeration != null) {
            // create a emails resource
            Emails emails = ResourceUtilities.FACTORY.createUserEmails();

            while (mailEnumeration.hasMoreElements()) {
                // get the next email
                String mailAttribute = (String) mailEnumeration.next();
                if (mailAttribute != null) {
                    PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute();
                    pluralAttribute.setValue(mailAttribute);

                    if (emails.getEmail().isEmpty())
                        pluralAttribute.setPrimary(true);
                    else
                        pluralAttribute.setPrimary(false);

                    emails.getEmail().add(pluralAttribute);
                }
            }

            // add the mails to the user resource
            user.setEmails(emails);
        }
    }

    // get the telephone attribute name
    String telephoneAtttributeName = properties.getProperty(TELEPHONE_ATTRIBUTE, DEFAULT_TELEPHONE_ATTRIBUTE);

    // get the telephones
    if (attributes.get(telephoneAtttributeName) != null) {
        NamingEnumeration telephoneEnumeration = attributes.get(telephoneAtttributeName).getAll();
        if (telephoneEnumeration != null) {
            // create a telephones resource
            PhoneNumbers telephones = ResourceUtilities.FACTORY.createUserPhoneNumbers();

            while (telephoneEnumeration.hasMoreElements()) {
                // get the next telephone
                String telephoneAttribute = (String) telephoneEnumeration.next();
                if (telephoneAttribute != null) {
                    PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute();
                    pluralAttribute.setValue(telephoneAttribute);

                    if (telephones.getPhoneNumber().isEmpty())
                        pluralAttribute.setPrimary(true);
                    else
                        pluralAttribute.setPrimary(false);

                    telephones.getPhoneNumber().add(pluralAttribute);
                }
            }

            // add the telephones to the user resource
            user.setPhoneNumbers(telephones);
        }
    }

    // get the password attribute name
    String passwordAtttributeName = properties.getProperty(PASSWORD_ATTRIBUTE, DEFAULT_PASSWORD_ATTRIBUTE);

    // get the password
    Attribute passwordAttribute = attributes.get(passwordAtttributeName);
    if (passwordAttribute != null)
        user.setPassword(new String((byte[]) passwordAttribute.get()));

    // get the memberOf attribute name
    String memberOfAtttributeName = properties.getProperty(MEMBEROF_ATTRIBUTE, DEFAULT_MEMBEROF_ATTRIBUTE);

    // get the memberOf
    if (attributes.get(memberOfAtttributeName) != null) {
        NamingEnumeration memberOfEnumeration = attributes.get(memberOfAtttributeName).getAll();
        if (memberOfEnumeration != null) {
            // create a memberof resource
            MemberOf memberof = ResourceUtilities.FACTORY.createUserMemberOf();

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

                    // check if the member dns need to be concealed 
                    if (properties
                            .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS,
                                    UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)
                            .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) {
                        Matcher matcher = pattern.matcher(memberOfAttribute);
                        if (matcher.matches()) {
                            memberOfAttribute = matcher.group(1);
                        }
                    }

                    pluralAttribute.setValue(memberOfAttribute);
                    memberof.getGroup().add(pluralAttribute);
                }
            }

            // add the memberOf to the user resource
            user.setMemberOf(memberof);
        }
    }

    return user;
}

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

/**
 * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#getUsers(javax.naming.directory.DirContext)
 *//*from w  w w  .  ja  v a  2 s. com*/
public Collection<User> getUsers(DirContext context) throws LdapControllerException, MappingException {
    NamingEnumeration<SearchResult> results = null;
    try {
        results = searchUsers(context, null, null);
        Set<User> users = new LinkedHashSet<User>();

        while (results.hasMoreElements()) {
            SearchResult result = results.nextElement();

            users.add(mapper.getUser(result.getAttributes()));
        }

        return users;
    } catch (NamingException e) {
        String message = "Failed to retrieve ldap information for users.";

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

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

/**
 * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#getUsersByQuery(org.apache.archiva.redback.users.ldap.LdapUserQuery, javax.naming.directory.DirContext)
 *//*from   w  ww  . j  a v  a 2 s.  co m*/
public List<User> getUsersByQuery(LdapUserQuery query, DirContext context)
        throws LdapControllerException, MappingException {
    NamingEnumeration<SearchResult> results = null;
    try {
        results = searchUsers(context, null, query);
        List<User> users = new LinkedList<User>();

        while (results.hasMoreElements()) {
            SearchResult result = results.nextElement();

            users.add(mapper.getUser(result.getAttributes()));
        }

        return users;
    } catch (NamingException e) {
        String message = "Failed to retrieve ldap information for users.";

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

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Retrieves the roles for the from the identity provider.
 *
 * @param username the user to get the roles for
 * @return the list of roles for the user
 * @throws PortalServiceException for any errors encountered
 *//*from w ww .j  a v a2  s. c o m*/
@SuppressWarnings("rawtypes")
public List<String> findRoles(String username) throws PortalServiceException {
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);

        // Search for groups the user belongs to in order to get their names
        // Create the search controls
        SearchControls groupsSearchCtls = new SearchControls();

        // Specify the search scope
        groupsSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Specify the attributes to return
        String groupsReturnedAtts[] = { "cn" };
        groupsSearchCtls.setReturningAttributes(groupsReturnedAtts);

        String userDn = MessageFormat.format(userDNPattern, username);
        // Search for objects using the filter
        NamingEnumeration groupsAnswer = ctx.search(groupsSearchBase,
                MessageFormat.format(groupsFilterPattern, userDn), groupsSearchCtls);

        List<String> groups = new ArrayList<String>();
        // Loop through the search results
        while (groupsAnswer.hasMoreElements()) {

            SearchResult sr = (SearchResult) groupsAnswer.next();
            Attributes attrs = sr.getAttributes();

            if (attrs != null) {
                groups.add((String) attrs.get("cn").get());
            }

            if (sr.getObject() instanceof Context) {
                closeContext((Context) sr.getObject());
            }
        }
        return groups;
    } catch (NamingException e) {
        throw new PortalServiceConfigurationException("Unable to get groups.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * check if User already exists on system.
 *
 * @param inLogin//from  w w  w. j  av a2  s.  c o  m
 *            String
 * @return path as string
 */
public boolean isUserAlreadyExists(String inLogin) {
    Hashtable<String, String> env = getLdapConnectionSettings();
    env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
    env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));
    DirContext ctx;
    boolean rueckgabe = false;
    try {
        ctx = new InitialDirContext(env);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search("ou=users,dc=gdz,dc=sub,dc=uni-goettingen,dc=de",
                matchAttrs);
        rueckgabe = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            if (logger.isDebugEnabled()) {
                logger.debug(">>>" + sr.getName());
            }
            Attributes attrs = sr.getAttributes();
            String givenName = " ";
            String surName = " ";
            String mail = " ";
            String cn = " ";
            String hd = " ";
            try {
                givenName = attrs.get("givenName").toString();
            } catch (Exception err) {
                givenName = " ";
            }
            try {
                surName = attrs.get("sn").toString();
            } catch (Exception e2) {
                surName = " ";
            }
            try {
                mail = attrs.get("mail").toString();
            } catch (Exception e3) {
                mail = " ";
            }
            try {
                cn = attrs.get("cn").toString();
            } catch (Exception e4) {
                cn = " ";
            }
            try {
                hd = attrs.get("homeDirectory").toString();
            } catch (Exception e4) {
                hd = " ";
            }
            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(hd);

        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

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

private ADUserDetails loadUserByUsername(DirContext context, String username, String password)
        throws UsernameNotFoundException {
    try {/*from   w w  w.j a  va2  s.  c  om*/
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // search for username
        NamingEnumeration<SearchResult> renum = context.search(userSearchBase,
                "(&(objectClass=user)(sAMAccountName={0}))", new Object[] { username }, controls);
        if (!renum.hasMoreElements()) {
            throw new UsernameNotFoundException("User '" + username + "' is not exist");
        }
        SearchResult result = renum.next();
        final Attributes attributes = result.getAttributes();

        // User's display name
        String displayName = null;
        Attribute attr = attributes.get(displayNameAttribute);
        if (attr != null) {
            displayName = attr.get().toString();
        }
        if (!StringUtils.hasText(displayName))
            displayName = username;
        logger.log(Level.FINE, "Display name: " + displayName);

        // User's email
        String email = null;
        attr = attributes.get(emailAttribute);
        if (attr != null) {
            email = attr.get().toString();
        }
        logger.log(Level.FINE, "E-mail: " + email);

        // User's phone number
        String phone = null;
        attr = attributes.get(phoneAttribute);
        if (attr != null) {
            phone = attr.get().toString();
        }
        logger.log(Level.FINE, "Phone: " + phone);

        // Is user blocked
        boolean blocked = false;
        attr = attributes.get("userAccountControl");
        if (attr != null) {
            blocked = (Long.parseLong(attr.get().toString()) & 2) != 0;
        }
        logger.log(Level.FINE, "Blocked: " + blocked);

        // describe roles and groups
        final Set<String> roles = new TreeSet<>();
        final Set<String> groups = new TreeSet<>();
        Attribute memberOf = attributes.get("memberOf");
        describeRoles(context, memberOf, groups, roles);

        // Describe user primary role
        Attribute attrPrimaryGroupId = attributes.get("primaryGroupId");
        Attribute attrObjectSid = attributes.get("objectSid");
        if (attrPrimaryGroupId != null && attrObjectSid != null) {
            int primaryGroupId = Integer.parseInt(attrPrimaryGroupId.get().toString());
            byte[] objectSid = (byte[]) attrObjectSid.get();
            // add primary group RID
            for (int i = 0; i < 4; i++) {
                objectSid[objectSid.length - 4 + i] = (byte) (primaryGroupId & 0xFF);
                primaryGroupId >>= 8;
            }
            StringBuilder tmp = new StringBuilder();
            for (int i = 2; i <= 7; i++) {
                tmp.append(Integer.toHexString(objectSid[i] & 0xFF));
            }
            // convert objectSid to String
            StringBuilder sidBuilder = new StringBuilder("S-").append(objectSid[0]).append("-")
                    .append(Long.parseLong(tmp.toString(), 16));
            // the sub authorities count
            int count = objectSid[1];
            // add authorities
            for (int i = 0; i < count; i++) {
                tmp.setLength(0);

                int offset = i * 4;
                tmp.append(String.format("%02X%02X%02X%02X", (objectSid[11 + offset] & 0xFF),
                        (objectSid[10 + offset] & 0xFF), (objectSid[9 + offset] & 0xFF),
                        (objectSid[8 + offset] & 0xFF)));
                sidBuilder.append('-').append(Long.parseLong(tmp.toString(), 16));
            }
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            renum = context.search(userSearchBase, "(&(objectClass=group)(objectSid={0}))",
                    new Object[] { sidBuilder.toString() }, searchControls);
            if (renum.hasMoreElements()) {
                result = renum.next();
                attr = result.getAttributes().get("distinguishedName");
                describeRoles(context, attr, groups, roles);
            }
        }
        return new ADUserDetails(username, password, displayName, email, phone, blocked, groups, roles);
    } catch (NamingException ex) {
        logger.log(Level.SEVERE, "Could not find user '" + username + "'", ex);
        throw new UsernameNotFoundException(ex.getMessage());
    }
}

From source file:it.webappcommon.lib.LDAPHelper.java

/**
 * @param args/*from   w  ww .ja v  a2s.  c om*/
 *            the command line arguments
 */
// public static void main(String[] args) {
private List<UserInfo> search(String filter) throws NamingException {
    DirContext ctx = null;
    SearchControls ctls = null;
    Properties env = new Properties();
    List<UserInfo> res = new ArrayList<UserInfo>();
    boolean trovatiRisultati = false;

    env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT);

    env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) {
        env.put(Context.SECURITY_PRINCIPAL, loginUserName);
    } else {
        env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName);
    }
    env.put(Context.SECURITY_CREDENTIALS, loginPassword);

    try {
        ctx = new InitialDirContext(env);

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

        // String filter = "";
        // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))";
        // filter = FILTER_USERS_ACTIVE;

        // Tutti i membri di un gruppo
        // (objectCategory=user)(memberOf=CN=QA Users,OU=Help
        // Desk,DC=dpetri,DC=net)

        // ESEMPI
        // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm

        // Account disabled
        // (UserAccountControl:1.2.840.113556.1.4.803:=2)

        NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls);

        UserInfo userInfo = null;
        while (answer.hasMoreElements()) {
            trovatiRisultati = true;

            SearchResult a = answer.nextElement();
            // logger.debug(a.getNameInNamespace());

            Attributes result = a.getAttributes();

            if (result == null) {
                // System.out.print("Attributi non presenti");
            } else {
                NamingEnumeration<? extends Attribute> attributi = result.getAll();

                userInfo = new UserInfo();
                while (attributi.hasMoreElements()) {
                    Attribute att = attributi.nextElement();
                    // logger.debug(att.getID());

                    String value = "";
                    // for (NamingEnumeration vals = att.getAll();
                    // vals.hasMoreElements(); logger.debug("\t" +
                    // vals.nextElement()))
                    // ;
                    NamingEnumeration<?> vals = att.getAll();
                    while (vals.hasMoreElements()) {
                        Object val = vals.nextElement();

                        // logger.debug("\t" + val);
                        value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString();
                    }

                    if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) {
                        // userInfo.setFIELD_ACCOUNT_NAME(value);
                        userInfo.setAccount(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) {
                        // userInfo.setFIELD_COGNOME(value);
                        userInfo.setCognome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) {
                        // userInfo.setFIELD_EMAIL(value);
                        userInfo.setEmail(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) {
                        // userInfo.setFIELD_GROUPS(value);
                        userInfo.setGruppi(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) {
                        // userInfo.setFIELD_NOME(value);
                        userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) {
                        // userInfo.setFIELD_NOME_COMPLETO(value);
                        userInfo.setNomeCompleto(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) {
                        // userInfo.setFIELD_NOME_VISUALIZZATO(value);
                        // userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) {
                        // userInfo.setFIELD_TEL(value);
                        userInfo.setTel(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) {
                        // userInfo.setFIELD_UFFICIO(value);
                        userInfo.setUfficio(value);
                    }
                    // res.put(att.getID(), value);
                }

                // Attribute attr = result.get("cn");
                // if (attr != null) {
                // logger.debug("cn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("sn");
                // if (attr != null) {
                // logger.debug("sn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("mail");
                // if (attr != null) {
                // logger.debug("mail:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // // attr = result.get("uid");
                // // if (attr != null) {
                // // logger.debug("uid:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }
                // //
                // // attr = result.get("userPassword");
                // // if (attr != null) {
                // // logger.debug("userPassword:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }

                if (userInfo != null) {
                    res.add(userInfo);
                }
            }
        }
    } catch (NamingException ne) {
        // ne.printStackTrace();
        logger.error(ne);
        throw ne;
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception e) {
        }
    }

    // Azzero l'hash map
    if (!trovatiRisultati) {
        res = null;
    }

    return res;
}

From source file:ldap.ActiveLoginImpl.java

/**
 * This does a light copy of an attributes list (such as a UserAccount, if we need to modify it but
 * want to keep the original userAccount)
 * @param oldAtts//from   w  ww. j a  va2s  .  c om
 * @return a light copy of the original attributes list.
 */
public Attributes copyAttributes(Attributes oldAtts) {
    BasicAttributes atts = new BasicAttributes();
    NamingEnumeration attList = oldAtts.getAll();
    while (attList.hasMoreElements()) // shouldn't throw an exception, so use normal enumeration methods
    {
        Attribute att = (Attribute) attList.nextElement();
        atts.put(att);
    }
    return atts;
}

From source file:org.apache.archiva.redback.authentication.ldap.LdapBindAuthenticator.java

public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException {
    PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s;

    if (!config.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ENABLED)
            || (!config.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ALLOW_EMPTY_PASSWORDS, false)
                    && StringUtils.isEmpty(source.getPassword()))) {
        return new AuthenticationResult(false, source.getUsername(), null);
    }/*from   w  w  w . j a  v  a2  s .c  om*/

    SearchControls ctls = new SearchControls();

    ctls.setCountLimit(1);

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

    String filter = "(&(objectClass=" + mapper.getUserObjectClass() + ")"
            + (mapper.getUserFilter() != null ? mapper.getUserFilter() : "") + "(" + mapper.getUserIdAttribute()
            + "=" + source.getUsername() + "))";

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

    LdapConnection ldapConnection = null;
    LdapConnection authLdapConnection = null;
    NamingEnumeration<SearchResult> results = null;
    try {
        ldapConnection = getLdapConnection();
        // check the cache for user's userDn in the ldap server
        String userDn = ldapCacheService.getLdapUserDn(source.getUsername());

        if (userDn == null) {
            log.debug("userDn for user {} not found in cache. Retrieving from ldap server..",
                    source.getUsername());

            DirContext context = ldapConnection.getDirContext();

            results = context.search(mapper.getUserBaseDn(), filter, ctls);

            log.debug("Found user '{}': {}", source.getUsername(), results.hasMoreElements());

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

                userDn = result.getNameInNamespace();

                log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getUsername());

                // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server
                ldapCacheService.addLdapUserDn(source.getUsername(), userDn);
            } else {
                return new AuthenticationResult(false, source.getUsername(), null);
            }
        }

        log.debug("Attempting Authenication: {}", userDn);

        authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword());

        log.info("user '{}' authenticated", source.getUsername());

        return new AuthenticationResult(true, source.getUsername(), null);
    } catch (LdapException e) {
        return new AuthenticationResult(false, source.getUsername(), e);
    } catch (NamingException e) {
        return new AuthenticationResult(false, source.getUsername(), e);
    } finally {
        closeNamingEnumeration(results);
        closeLdapConnection(ldapConnection);
        if (authLdapConnection != null) {
            closeLdapConnection(authLdapConnection);
        }
    }
}

From source file:com.funambol.LDAP.dao.impl.ContactDAO.java

/**
 * Convert a <i>Contact</i> into a LDAP inetOrgPerson set of attributes.
 * This method is used in from Client to Server
 * //from ww  w . j av  a 2s  . co m
 * @param contact
 *            contact to transform into Attributes
 * @return Attributes representation of the contact
 */
public Attributes createEntry(Contact contact) {

    if (logger.isTraceEnabled())
        logger.trace("Working on contact:" + contact.getUid());

    Attributes attributeSet = new BasicAttributes();
    Attribute objClass = new BasicAttribute("objectClass");
    if (logger.isDebugEnabled())
        logger.debug("Ok let's add objectclass");

    objClass.add("inetOrgPerson");
    objClass.add("person");

    attributeSet.put(objClass);
    try {

        if (contact.getUid() == null) {
            contact.setUid(createUniqueId(contact));
            logger.info("UID is now: " + contact.getUid());
        }

        // Split contact object into sub-objects
        Name name = contact.getName();
        PersonalDetail personal = contact.getPersonalDetail();
        BusinessDetail business = contact.getBusinessDetail();

        List phones = personal.getPhones();
        List businessPhones = business.getPhones();

        List mails = personal.getEmails();
        List note = contact.getNotes();

        // personal address
        Address addr = personal.getAddress();

        // if displayname doesn't exist and the firstname and the lastname
        // are not both defined, this will result in a NullPointerException
        // I don't want to support any other ways of doing this right now.
        // a solution could be to use an UID for the rdn
        if (name != null) {

            if (propertyCheck(name.getLastName())) {
                attributeSet.put(new BasicAttribute("sn", name.getLastName().getPropertyValueAsString()));
            } else {
                attributeSet.put(new BasicAttribute("sn", ""));
            }

            if (propertyCheck(name.getFirstName())) {
                attributeSet
                        .put(new BasicAttribute("givenName", name.getFirstName().getPropertyValueAsString()));
            } else {
                attributeSet.put(new BasicAttribute("givenName", ""));
            }

            attributeSet.put(new BasicAttribute("cn", name.getFirstName().getPropertyValueAsString() + " "
                    + name.getLastName().getPropertyValueAsString()));
        }

        // Company name
        if (business != null && propertyCheck(business.getCompany())) {
            attributeSet.put(new BasicAttribute("o", business.getCompany().getPropertyValueAsString()));
        }

        // Adding phones
        if (phones != null && !phones.isEmpty()) {

            Iterator iter2 = phones.iterator();
            while (iter2.hasNext()) {
                Phone phone = (Phone) iter2.next();

                // if empty, no need to check type
                if (!propertyCheck(phone))
                    continue;

                // Home phones
                if (phone.getPhoneType().equals("HomeTelephoneNumber")) {
                    attributeSet.put(new BasicAttribute("homePhone", phone.getPropertyValueAsString()));
                }

                // MobilePhones
                if (phone.getPhoneType().equals("MobileTelephoneNumber"))
                    attributeSet.put(new BasicAttribute("mobile", phone.getPropertyValueAsString()));

            }
        }

        // Adding business phones
        if (businessPhones != null && !businessPhones.isEmpty()) {

            Iterator iter2 = businessPhones.iterator();
            while (iter2.hasNext()) {
                Phone phone = (Phone) iter2.next();

                // if empty, no need to check type
                if (!propertyCheck(phone))
                    continue;

                // Business phones
                if (phone.getPhoneType().equals("BusinessTelephoneNumber")) {
                    attributeSet.put(new BasicAttribute("telephoneNumber", phone.getPropertyValueAsString()));
                }
                // Fax
                if (phone.getPhoneType().equals("BusinessFaxNumber")) {
                    attributeSet.put(
                            new BasicAttribute("facsimiletelephonenumber", phone.getPropertyValueAsString()));
                }
            }
        }

        if (mails != null && !mails.isEmpty()) {

            Iterator iter1 = mails.iterator();

            // For each email address, add it
            while (iter1.hasNext()) {
                Email mail = (Email) iter1.next();
                if (propertyCheck(mail))
                    attributeSet.put(new BasicAttribute("mail", mail.getPropertyValueAsString()));
            }
        }

        // Address
        if (addr != null) {
            if (propertyCheck(personal.getAddress().getPostalCode()))
                attributeSet.put(new BasicAttribute("postalCode",
                        personal.getAddress().getPostalCode().getPropertyValueAsString()));

            if (propertyCheck(personal.getAddress().getStreet()))
                attributeSet.put(new BasicAttribute("postalAddress",
                        personal.getAddress().getStreet().getPropertyValueAsString()));

            if (propertyCheck(personal.getAddress().getCity()))
                attributeSet.put(
                        new BasicAttribute("l", personal.getAddress().getCity().getPropertyValueAsString()));
        }

        // Notes
        if (note != null && !note.isEmpty()) {
            Iterator note1 = note.iterator();
            while (note1.hasNext()) {
                Note nota = (Note) note1.next();
                if (propertyCheck(nota))
                    attributeSet.put(new BasicAttribute("description", nota.getPropertyValueAsString()));
            }
        }

        logger.info("Resulting LDAPAttributeSet is:");

        NamingEnumeration<String> ids = attributeSet.getIDs();

        while (ids.hasMoreElements()) {
            String attrID = ids.nextElement();
            logger.info(attrID + ": " + ((String) attributeSet.get(attrID).get()));

        }

        // Create the LDAPEntry with dn and attributes
        // THE DN is the DisplayName
        return attributeSet;

    } catch (Exception e) {
        logger.warn("Unable to create LDAPEntry from Contact: " + e.toString(), e);
        return null;
    }
}