Example usage for javax.naming.directory SearchResult getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Retrieves the name of this binding.

Usage

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

@Override
public void doSyncSingleUser(Identity ident) {
    LdapContext ctx = bindSystem();
    if (ctx == null) {
        log.error("could not bind to ldap", null);
    }/*w  ww  . j  a va 2 s  .  c o m*/
    String userDN = ldapDao.searchUserDN(ident.getName(), ctx);

    final List<Attributes> ldapUserList = new ArrayList<Attributes>();
    // TODO: use userDN instead of filter to get users attribs
    ldapDao.searchInLdap(new LDAPVisitor() {
        @Override
        public void visit(SearchResult result) {
            Attributes resAttribs = result.getAttributes();
            log.debug("        found : " + resAttribs.size() + " attributes in result " + result.getName());
            ldapUserList.add(resAttribs);
        }
    }, userDN, syncConfiguration.getUserAttributes(), ctx);

    Attributes attrs = ldapUserList.get(0);
    Map<String, String> olatProToSync = prepareUserPropertyForSync(attrs, ident);
    if (olatProToSync != null) {
        syncUser(olatProToSync, ident);
    }
}

From source file:org.openadaptor.auxil.connector.jndi.JNDISearch.java

/**
 * Retrieve the next match from the array of NamingEnumerations (the call to hasMore() will automagically bump it to
 * the next enumeration in the array if necessary.
 * //from  ww  w. ja  v  a 2  s.c o  m
 * @return Next Entry if available.
 * @throws NoSuchElementException
 *           if no more matches remain (i.e. hasMore() would have failed).
 * @throws NamingException
 *           if any other JNDI exception occurs.
 */
public Object next() throws NamingException {
    SearchResult result = null;
    if (hasMore()) { // Something to return!
        result = (SearchResult) searchResults[current].next();
        if (dnAttributeName != null) {// Stuff in the DN
            String rdn = result.getName(); // Get the relative dn for this match
            String dn = rdn + "," + executedSearch.getSearchBases()[current]; // Construct a full dn.
            Attributes attrs = result.getAttributes();
            attrs.put(dnAttributeName, dn);
            result.setAttributes(attrs);
        }
    } else {
        throw new NoSuchElementException();
    }
    return result;
}

From source file:org.orbeon.oxf.processor.LDAPProcessor.java

private void serialize(List results, Config config, ContentHandler ch) {
    try {//  w w  w .  j a v  a2s  .  com
        ch.startDocument();
        ch.startElement("", "results", "results", SAXUtils.EMPTY_ATTRIBUTES);
        for (Iterator i = results.iterator(); i.hasNext();) {
            SearchResult sr = (SearchResult) i.next();

            ch.startElement("", "result", "result", SAXUtils.EMPTY_ATTRIBUTES);
            addElement(ch, "name", sr.getName());
            try {
                addElement(ch, "fullname", sr.getNameInNamespace());
            } catch (UnsupportedOperationException e) {
                // This seems to be the only  way to know if sr contains a name!
            }
            Attributes attr = sr.getAttributes();
            NamingEnumeration attrEn = attr.getAll();
            while (attrEn.hasMoreElements()) {
                Attribute a = (Attribute) attrEn.next();
                if (config.getAttributes().isEmpty() || config.getAttributes().contains(a.getID())) {
                    ch.startElement("", "attribute", "attribute", SAXUtils.EMPTY_ATTRIBUTES);
                    addElement(ch, "name", a.getID());
                    NamingEnumeration aEn = a.getAll();
                    while (aEn.hasMoreElements()) {
                        Object o = aEn.next();
                        addElement(ch, "value", o.toString());
                    }
                    ch.endElement("", "attribute", "attribute");
                }
            }
            ch.endElement("", "result", "result");
        }
        ch.endElement("", "results", "results");
        ch.endDocument();
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.projectforge.business.ldap.LdapDao.java

public List<T> findAll(final DirContext ctx, final String organizationalUnit) throws NamingException {
    final LinkedList<T> list = new LinkedList<T>();
    NamingEnumeration<?> results = null;
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchBase = getSearchBase(organizationalUnit);
    results = ctx.search(searchBase, "(objectclass=" + getObjectClass() + ")", controls);
    while (results.hasMore()) {
        final SearchResult searchResult = (SearchResult) results.next();
        final String dn = searchResult.getName();
        final Attributes attributes = searchResult.getAttributes();
        list.add(mapToObject(dn, searchBase, attributes));
    }/*from   w  ww  .  ja v a  2  s  .  com*/
    return list;
}

From source file:org.projectforge.business.ldap.LdapDao.java

public T findById(final DirContext ctx, final Object id, final String... organizationalUnits)
        throws NamingException {
    NamingEnumeration<?> results = null;
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchBase = getSearchBase(organizationalUnits);
    final String args = "(&(objectClass=" + getObjectClass() + ")(" + getIdAttrId() + "=" + buildId(id) + "))";
    results = ctx.search(searchBase, args, controls);
    if (results.hasMore() == false) {
        return null;
    }/*from  ww w  .  j a va 2  s  .  co m*/
    final SearchResult searchResult = (SearchResult) results.next();
    final String dn = searchResult.getName();
    final Attributes attributes = searchResult.getAttributes();
    if (results.hasMore() == true) {
        log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + id);
    }
    return mapToObject(dn, searchBase, attributes);
}

From source file:org.projectforge.business.ldap.LdapUserDao.java

public LdapUser findByUsername(final Object username, final String... organizationalUnits) {
    return (LdapUser) new LdapTemplate(ldapConnector) {
        @Override/*from   w w w  .  ja  v a 2  s. co  m*/
        protected Object call() throws NameNotFoundException, Exception {
            NamingEnumeration<?> results = null;
            final SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            final String searchBase = getSearchBase(organizationalUnits);
            results = ctx.search(searchBase, "(&(objectClass=" + getObjectClass() + ")(uid=" + username + "))",
                    controls);
            if (results.hasMore() == false) {
                return null;
            }
            final SearchResult searchResult = (SearchResult) results.next();
            final String dn = searchResult.getName();
            final Attributes attributes = searchResult.getAttributes();
            if (results.hasMore() == true) {
                log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + username);
            }
            return mapToObject(dn, searchBase, attributes);
        }
    }.excecute();
}

From source file:org.rhq.enterprise.server.core.jaas.LdapLoginModule.java

/**
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String)
 *///from w  ww.j  a va2 s .  c  o m
protected boolean validatePassword(String inputPassword, String expectedPassword) {
    // Load our LDAP specific properties
    Properties env = getProperties();

    // Load the BaseDN
    String baseDN = (String) options.get("BaseDN");
    if (baseDN == null) {
        // If the BaseDN is not specified, log an error and refuse the login attempt
        log.info("BaseDN is not set, refusing login");
        return false;
    }

    // Many LDAP servers allow bind's with an emtpy password. We will deny all requests with empty passwords
    if ((inputPassword == null) || inputPassword.equals("")) {
        log.debug("Empty password, refusing login");
        return false;
    }

    // Load the LoginProperty
    String loginProperty = (String) options.get("LoginProperty");
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }

    // Load any search filter
    String searchFilter = (String) options.get("Filter");

    // Find the user that is calling us
    String userName = getUsername();

    // Load any information we may need to bind
    String bindDN = (String) options.get("BindDN");
    String bindPW = (String) options.get("BindPW");
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();

        // Add the search filter if specified.  This only allows for a single search filter.. i.e. foo=bar.
        String filter;
        if ((searchFilter != null) && (searchFilter.length() != 0)) {
            filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))";
        } else {
            filter = "(" + loginProperty + "=" + userName + ")";
        }

        log.debug("Using LDAP filter=" + filter);

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);
        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration answer = ctx.search(baseDNs[x], filter, searchControls);
            boolean ldapApiNpeFound = false;
            if (!answer.hasMoreElements()) {//BZ:582471- ldap api bug
                log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]);

                // Nothing found for this DN, move to the next one if we have one.
                continue;
            }

            // We use the first match
            SearchResult si = (SearchResult) answer.next();

            // Construct the UserDN
            String userDN = si.getName() + "," + baseDNs[x];

            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inputPassword);
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");

            //if successful then verified that user and pw are valid ldap credentials
            ctx.reconnect(null);

            return true;
        }

        // If we try all the BaseDN's and have not found a match, return false
        return false;
    } catch (Exception e) {
        log.info("Failed to validate password: " + e.getMessage());
        return false;
    }
}

From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

public Map<String, String> findLdapUserDetails(String userName) {
    Properties systemConfig = systemManager.getSystemConfiguration(subjectManager.getOverlord());
    HashMap<String, String> userDetails = new HashMap<String, String>();
    // Load our LDAP specific properties
    Properties env = getProperties(systemConfig);

    // Load the BaseDN
    String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN);

    // Load the LoginProperty
    String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty);
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }/* w  w  w .  j av a 2  s  . c o m*/
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);

    // Load any search filter
    String searchFilter = (String) systemConfig.get(RHQConstants.LDAPFilter);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();

        // Add the search filter if specified.  This only allows for a single search filter.. i.e. foo=bar.
        String filter;
        if ((searchFilter != null) && (searchFilter.length() != 0)) {
            filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))";
        } else {
            filter = "(" + loginProperty + "=" + userName + ")";
        }

        log.debug("Using LDAP filter [" + filter + "] to locate user details for " + userName);

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);
        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls);
            if (!answer.hasMoreElements()) { //BZ:582471- ldap api bug change
                log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]);
                // Nothing found for this DN, move to the next one if we have one.
                continue;
            }

            // We use the first match
            SearchResult si = answer.next();
            //generate the DN
            String userDN = null;
            try {
                userDN = si.getNameInNamespace();
            } catch (UnsupportedOperationException use) {
                userDN = si.getName();
                if (userDN.startsWith("\"")) {
                    userDN = userDN.substring(1, userDN.length());
                }
                if (userDN.endsWith("\"")) {
                    userDN = userDN.substring(0, userDN.length() - 1);
                }
                userDN = userDN + "," + baseDNs[x];
            }
            userDetails.put("dn", userDN);

            // Construct the UserDN
            NamingEnumeration<String> keys = si.getAttributes().getIDs();
            while (keys.hasMore()) {
                String key = keys.next();
                Attribute value = si.getAttributes().get(key);
                if ((value != null) && (value.get() != null)) {
                    userDetails.put(key, value.get().toString());
                }
            }
            return userDetails;
        }
        return userDetails;
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapRowInserter.java

/**
 * Initial implementation will just print all attributes...
 *//*from   w  ww.  j a v a 2 s. c o  m*/
@Override
protected String dataToString(SearchResult sr) {
    return sr.getName();
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.UserMapper.java

public Collection<String> getGroupNames(SearchResult sr) throws NamingException {
    Set<String> groupNames = new HashSet<String>();
    // group names in the current entry
    Attributes attrs = sr.getAttributes();
    Set<String> entryGroups = replaceWhitespace(getValues(attrs, Index.USER_GROUP));
    if (entryGroups != null) {
        groupNames.addAll(entryGroups);/*w  w w  .ja  v  a 2s .co  m*/
    }

    // group names found in distinguished name
    if (sr.isRelative()) {
        String name = sr.getName();
        LdapName ldapName = new LdapName(name);
        List<Rdn> rdns = ldapName.getRdns();
        for (Rdn rdn : rdns) {
            Attributes rdnsAttributes = rdn.toAttributes();
            Set<String> rdnsGroups = replaceWhitespace(getValues(rdnsAttributes, Index.USER_GROUP));
            if (rdnsGroups != null) {
                groupNames.addAll(rdnsGroups);
            }

        }
    }
    //only if there is no already defined group, add the default user group
    if (groupNames.isEmpty()) {
        String defaultGroupName = getAttrMap().getDefaultGroupName();
        if (defaultGroupName != null) {
            groupNames.add(defaultGroupName);
        }
    }
    return groupNames;
}