Example usage for javax.naming.directory SearchResult getAttributes

List of usage examples for javax.naming.directory SearchResult getAttributes

Introduction

In this page you can find the example usage for javax.naming.directory SearchResult getAttributes.

Prototype

public Attributes getAttributes() 

Source Link

Document

Retrieves the attributes in this search result.

Usage

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static LDAPUser findUserByMail(String mail) {
    NamingEnumeration results = null;
    DirContext ctx = null;/*w w  w.  j  a v  a2s  .  c o  m*/
    LDAPUser user = null;
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        String retAttrs[] = { "cn" };
        controls.setReturningAttributes(retAttrs);
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(mail=" + mail + ")", controls);
        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            user = new LDAPUser();

            if (attributes.get("cn") != null)
                user = getUser((String) attributes.get("cn").get());
        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return user;

}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static LDAPUser getIfValidUser(String cn, String password) {
    LDAPUser user = null;/*from  w ww . ja v  a  2 s.  co  m*/
    NamingEnumeration results = null;
    DirContext ctx = null;
    try {
        ctx = getAuthContext(cn, password);
        SearchControls controls = new SearchControls();
        String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf",
                "createTimestamp" };
        controls.setReturningAttributes(retAttrs);
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls);
        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            user = new LDAPUser();

            if (attributes.get("cn") != null)
                user.setUsername((String) attributes.get("cn").get());
            if (attributes.get("sn") != null)
                user.setSurname((String) attributes.get("sn").get());
            if (attributes.get("givenName") != null)
                user.setGivenname((String) attributes.get("givenName").get());
            if (attributes.get("title") != null)
                user.setTitle((String) attributes.get("title").get());
            if (attributes.get("registeredAddress") != null)
                user.setPreferredMail((String) attributes.get("registeredAddress").get(0));
            if (attributes.get("mail") != null) {
                String mails = "";
                for (int i = 0; i < attributes.get("mail").size(); i++) {
                    if (i != 0)
                        mails = mails + ", ";
                    mails = mails + (String) attributes.get("mail").get(i);
                }
                user.setAdditionalMails(mails);
            }
            if (attributes.get("memberOf") != null) {
                for (int i = 0; i < attributes.get("memberOf").size(); i++) {
                    user.addGroup((String) attributes.get("memberOf").get(i));
                }
            }
            if (attributes.get("createTimestamp") != null) {
                String time = (String) attributes.get("createTimestamp").get();
                DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss");
                user.setCreationTime(ldapData.parse(time));
            }

        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } catch (ParseException ex) {
        _log.error(ex);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return user;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static LDAPUser getUser(String cn) {
    LDAPUser user = null;/* w  ww  .j  a  va 2s.  c o m*/
    NamingEnumeration results = null;
    DirContext ctx = null;
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf",
                "createTimestamp" };
        controls.setReturningAttributes(retAttrs);
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls);
        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            user = new LDAPUser();

            if (attributes.get("cn") != null)
                user.setUsername((String) attributes.get("cn").get());
            if (attributes.get("sn") != null)
                user.setSurname((String) attributes.get("sn").get());
            if (attributes.get("givenName") != null)
                user.setGivenname((String) attributes.get("givenName").get());
            if (attributes.get("title") != null)
                user.setTitle((String) attributes.get("title").get());
            if (attributes.get("registeredAddress") != null)
                user.setPreferredMail((String) attributes.get("registeredAddress").get(0));
            if (attributes.get("mail") != null) {
                String mails = "";
                for (int i = 0; i < attributes.get("mail").size(); i++) {
                    if (i != 0)
                        mails = mails + ", ";
                    mails = mails + (String) attributes.get("mail").get(i);
                }
                user.setAdditionalMails(mails);
            }
            if (attributes.get("memberOf") != null) {
                for (int i = 0; i < attributes.get("memberOf").size(); i++) {
                    user.addGroup((String) attributes.get("memberOf").get(i));
                }
            }

            if (attributes.get("createTimestamp") != null) {
                String time = (String) attributes.get("createTimestamp").get();
                DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss");
                user.setCreationTime(ldapData.parse(time));
            }

        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } catch (ParseException ex) {
        _log.error(ex);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return user;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static List<Organization> getOrgList(String country) {
    List<Organization> OrgList = new ArrayList<Organization>();
    NamingEnumeration resultCountries = null;
    DirContext ctx = null;/*from   ww  w  .  j a v a  2 s . co  m*/
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        String filter;
        if (country == null) {
            filter = "(objectclass=country)";
        } else {
            filter = "(&(objectclass=country)(c=" + country + "))";
        }
        resultCountries = ctx.search(rb.getString("organisationsRoot"), filter, controls);

        while (resultCountries.hasMore()) {
            SearchResult searchResult = (SearchResult) resultCountries.next();
            Attributes attributes = searchResult.getAttributes();
            String countryCode = (String) attributes.get("c").get();
            String countryName = (String) attributes.get("co").get();

            NamingEnumeration resultsOrgs = ctx.search(
                    "c=" + countryCode + "," + rb.getString("organisationsRoot"), "(objectclass=organization)",
                    controls);
            while (resultsOrgs.hasMore()) {
                SearchResult srOrg = (SearchResult) resultsOrgs.next();
                Attributes orgAttrs = srOrg.getAttributes();
                String description = "";
                if ((orgAttrs.get("description")) != null) {
                    description = (String) orgAttrs.get("description").get();
                }

                OrgList.add(new Organization((String) orgAttrs.get("o").get(), countryName, countryCode,
                        description, srOrg.getNameInNamespace()));
            }
            resultsOrgs.close();

        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (resultCountries != null) {
            try {
                resultCountries.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    Collections.sort(OrgList, new Comparator<Organization>() {

        public int compare(Organization o1, Organization o2) {
            return o1.getKey().compareTo(o2.getKey());
        }

    });

    return OrgList;

}

From source file:com.seyren.core.security.ldap.LdapUserManagement.java

@Override
public String[] autoCompleteUsers(String name) {
    List<String> users = new ArrayList<String>();
    try {/*  www .  j ava  2 s .co  m*/
        DirContext readOnlyContext = contextSource.getReadOnlyContext();
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { USERNAME };
        ctls.setReturningAttributes(attrIDs);
        NamingEnumeration<SearchResult> results = readOnlyContext.search("", "(sAMAccountName=" + name + "*)",
                ctls);
        while (results.hasMore()) {
            SearchResult rslt = results.next();
            Attributes attrs = rslt.getAttributes();
            if (attrs.get(USERNAME) != null) {
                users.add((String) attrs.get(USERNAME).get());
            }
        }
    } catch (NamingException e) {

    }
    return users.toArray(new String[users.size()]);
}

From source file:com.marklogic.samplestack.integration.web.LDAPIT.java

@Test
public void testFinds() throws NamingException {
    SearchResult srLdapUser = findAccountByAccountName(contributor);

    assertEquals("joeUser@marklogic.com", srLdapUser.getAttributes().get("uid").get());

}

From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * {@inheritDoc}/*from  w w  w .j  a v a 2  s  .  c  o  m*/
 */
public Map<String, String> findByCommonNameStub(String stub, long maxCount) throws RepositoryException {
    Map<String, String> idNameMap = new LinkedHashMap<String, String>();
    String text = censorHumanoidSearchPhrase(stub);
    String filter = "(&(objectClass=" + getObjectClassName() + ")(cn=" + text + "*))";
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(maxCount);
    ctls.setReturningAttributes(new String[] { "cn", "uid" });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            idNameMap.put((String) attrs.get("uid").get(), (String) attrs.get("cn").get());
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }
    return idNameMap;
}

From source file:org.jamwiki.ldap.LdapUserHandler.java

/**
 *
 *///from www .ja v a 2s  . com
private WikiUserInfo initWikiUserInfo(NamingEnumeration answer) throws Exception {
    WikiUserInfo userInfo = new WikiUserInfo();
    SearchResult sr = (SearchResult) answer.next();
    Attributes attributes = sr.getAttributes();
    userInfo.setEmail((String) attributes.get(Environment.getValue(Environment.PROP_LDAP_FIELD_EMAIL)).get());
    userInfo.setFirstName(
            (String) attributes.get(Environment.getValue(Environment.PROP_LDAP_FIELD_FIRST_NAME)).get());
    userInfo.setLastName(
            (String) attributes.get(Environment.getValue(Environment.PROP_LDAP_FIELD_LAST_NAME)).get());
    return userInfo;
}

From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * Note that {@link User.getPassword()} will not give the password from the repository after 'unmarshalling'.
 * The user repository must be queried for this because the password is never retrieved from the repository 
 * and the User object does not contain it.  
 * // w  ww . j a va 2 s.  c o  m
 */
public boolean isPasswordStored(String userId) throws RepositoryException {
    if (StringUtils.isBlank(userId)) {
        logger.debug("Insufficient data for getting user info.");
        throw new IllegalArgumentException();
    }
    String filter = "(&(objectClass=" + getObjectClassName() + ")(uid=" + userId + "))";

    final String PASSWD_ATTR_NAME = "userPassword";
    boolean passwordStored = false;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(1);
    ctls.setReturningAttributes(new String[] { "uid", PASSWD_ATTR_NAME });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            if (attrs.get(PASSWD_ATTR_NAME) != null)
                passwordStored = true;
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }

    return passwordStored;
}

From source file:org.apache.cloudstack.ldap.ADLdapUserManagerImpl.java

protected boolean isUserDisabled(SearchResult result) throws NamingException {
    boolean isDisabledUser = false;
    String userAccountControl = LdapUtils.getAttributeValue(result.getAttributes(),
            _ldapConfiguration.getUserAccountControlAttribute());
    if (userAccountControl != null) {
        int control = Integer.parseInt(userAccountControl);
        // second bit represents disabled user flag in AD
        if ((control & 2) > 0) {
            isDisabledUser = true;/*from   w ww  .j  a  v  a  2s  . c o  m*/
        }
    }
    return isDisabledUser;
}