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:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public List<Map<String, Object>> search(Class<?> clazz, String filter, String[] returningAttrs) {
    if (null == filter) {
        return null;
    }/*from   www  .j  a v a 2  s .c o  m*/

    LogUtils.debug(LOG, String.format("search %s with filter=%s, returningAttrs=%s", clazz.getName(), filter,
            Arrays.toString(returningAttrs)));

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(returningAttrs);

    try {
        List<Map<String, Object>> retVal = new ArrayList<Map<String, Object>>();
        NamingEnumeration<SearchResult> results = ctx.search(EntityMetaData.get(clazz).context(), filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                retVal.add(fromAttributesToMap(clazz, result.getAttributes()));
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the map", e);
            }
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

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

private boolean isPagedResultControlSupported(final LdapContext ctx) {
    try {/*w ww. jav a 2  s . c o m*/
        final SearchControls ctl = new SearchControls();
        ctl.setReturningAttributes(new String[] { "supportedControl" });
        ctl.setSearchScope(SearchControls.OBJECT_SCOPE);

        /* search for the rootDSE object */
        final NamingEnumeration<SearchResult> results = ctx.search("", "(objectClass=*)", ctl);

        while (results.hasMore()) {
            final SearchResult entry = results.next();
            final NamingEnumeration<? extends Attribute> attrs = entry.getAttributes().getAll();
            while (attrs.hasMore()) {
                final Attribute attr = attrs.next();
                final NamingEnumeration<?> vals = attr.getAll();
                while (vals.hasMore()) {
                    final String value = (String) vals.next();
                    if (value.equals(PAGED_RESULT_CONTROL_OID)) {
                        return true;
                    }
                }
            }
        }
        return false;
    } catch (final Exception e) {
        logError("Exception when trying to know if the server support paged results.", e);
        return false;
    }
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public <T> List<T> searchIndirections(Class<T> clazz, String filter) {
    if (null == filter) {
        return null;
    }/*ww w.j a v  a2s .  c om*/

    LogUtils.debug(LOG, String.format("search %s with filter=%s", clazz.getName(), filter));

    OneMetaData oneMetaData = IndirectionsMetaData.get(clazz).getOne();

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(new String[] { oneMetaData.getIdAttr(), oneMetaData.getIndirectionAttr() });

    try {
        List<T> retVal = new ArrayList<T>();
        NamingEnumeration<SearchResult> results = ctx.search(oneMetaData.getContext(), filter, ctrl);
        while (results.hasMore()) {
            SearchResult result = results.next();
            retVal.add(fromAttributesToIndirections(clazz, result.getAttributes()));
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

protected Set<String> rolesFor(PrincipalCollection principals, String userNameIn, final LdapContext ldapCtx,
        final LdapContextFactory ldapContextFactory, Session session) throws NamingException {
    final Set<String> roleNames = new HashSet<>();
    final Set<String> groupNames = new HashSet<>();
    final String userName;
    if (getUserLowerCase()) {
        log.debug("userLowerCase true");
        userName = userNameIn.toLowerCase();
    } else {//from   w  w w. j a va2 s  .  c o  m
        userName = userNameIn;
    }

    String userDn = getUserDnForSearch(userName);

    // Activate paged results
    int pageSize = getPagingSize();
    if (log.isDebugEnabled()) {
        log.debug("Ldap PagingSize: " + pageSize);
    }
    int numResults = 0;
    byte[] cookie = null;
    try {
        ldapCtx.addToEnvironment(Context.REFERRAL, "ignore");

        ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });

        do {
            // ldapsearch -h localhost -p 33389 -D
            // uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w guest-password
            // -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)'
            NamingEnumeration<SearchResult> searchResultEnum = null;
            SearchControls searchControls = getGroupSearchControls();
            try {
                if (groupSearchEnableMatchingRuleInChain) {
                    searchResultEnum = ldapCtx.search(getGroupSearchBase(), String
                            .format(MATCHING_RULE_IN_CHAIN_FORMAT, groupObjectClass, memberAttribute, userDn),
                            searchControls);
                    while (searchResultEnum != null && searchResultEnum.hasMore()) {
                        // searchResults contains all the groups in search scope
                        numResults++;
                        final SearchResult group = searchResultEnum.next();

                        Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
                        String groupName = attribute.get().toString();

                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                    }
                } else {
                    // Default group search filter
                    String searchFilter = String.format("(objectclass=%1$s)", groupObjectClass);

                    // If group search filter is defined in Shiro config, then use it
                    if (groupSearchFilter != null) {
                        searchFilter = expandTemplate(groupSearchFilter, userName);
                        //searchFilter = String.format("%1$s", groupSearchFilter);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Group SearchBase|SearchFilter|GroupSearchScope: " + getGroupSearchBase()
                                + "|" + searchFilter + "|" + groupSearchScope);
                    }
                    searchResultEnum = ldapCtx.search(getGroupSearchBase(), searchFilter, searchControls);
                    while (searchResultEnum != null && searchResultEnum.hasMore()) {
                        // searchResults contains all the groups in search scope
                        numResults++;
                        final SearchResult group = searchResultEnum.next();
                        addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory);
                    }
                }
            } catch (PartialResultException e) {
                log.debug("Ignoring PartitalResultException");
            } finally {
                if (searchResultEnum != null) {
                    searchResultEnum.close();
                }
            }
            // Re-activate paged results
            ldapCtx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
        } while (cookie != null);
    } catch (SizeLimitExceededException e) {
        log.info("Only retrieved first " + numResults + " groups due to SizeLimitExceededException.");
    } catch (IOException e) {
        log.error("Unabled to setup paged results");
    }
    // save role names and group names in session so that they can be
    // easily looked up outside of this object
    session.setAttribute(SUBJECT_USER_ROLES, roleNames);
    session.setAttribute(SUBJECT_USER_GROUPS, groupNames);
    if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) {
        ((MutablePrincipalCollection) principals).addAll(groupNames, getName());
    }
    if (log.isDebugEnabled()) {
        log.debug("User RoleNames: " + userName + "::" + roleNames);
    }
    return roleNames;
}

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

/**
 * Obtain the properties for the user associated with the given uid using the
 * configured user properties query string.
 *
 * @param uid the user id of the user for whom its user properties are required.
 * @return the hash map containing user properties as name/value pairs.
 * @throws NamingException LDAP error obtaining user properties.
 *///  w  w w  .j  a  v  a  2s  .  com
protected HashMap selectUserProperties(String uid) throws NamingException {
    HashMap userPropertiesResultSet = new HashMap();

    InitialLdapContext ctx = createLdapInitialContext();

    BasicAttributes matchAttrs = new BasicAttributes(true);

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

    matchAttrs.put(principalUidAttrName, uid);

    String userPropertiesQueryString = getUserPropertiesQueryString();
    HashMap userPropertiesQueryMap = parseQueryString(userPropertiesQueryString);

    Iterator i = userPropertiesQueryMap.keySet().iterator();
    List propertiesAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        propertiesAttrList.add(o);
    }

    String[] propertiesAttr = (String[]) propertiesAttrList.toArray(new String[propertiesAttrList.size()]);

    try {

        // 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();

            for (int j = 0; j < propertiesAttr.length; j++) {

                Attribute attribute = attrs.get(propertiesAttr[j]);

                if (attribute == null) {
                    logger.warn("Invalid user property attribute '" + propertiesAttr[j] + "'");
                    continue;
                }

                Object propertyObject = attrs.get(propertiesAttr[j]).get();

                if (propertyObject == null) {
                    logger.warn("Found a 'null' value for user property '" + propertiesAttr[j] + "'");
                    continue;
                }

                String propertyValue = propertyObject.toString();
                String propertyName = (String) userPropertiesQueryMap.get(propertiesAttr[j]);

                userPropertiesResultSet.put(propertyName, propertyValue);

                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user property '" + propertyName + "' with value '" + propertyValue + "'");
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return userPropertiesResultSet;
}

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

/**
 * Obtains the roles for the given user.
 *
 * @param username the user name to fetch user data.
 * @return the list of roles to which the user is associated to.
 * @throws NamingException LDAP error obtaining roles fro the given user
 *///from w  w w .  j av a2  s  .co m
protected String[] selectRolesByUsername(String username) throws NamingException, NoSuchUserException {
    List userRoles = new ArrayList();

    InitialLdapContext ctx = createLdapInitialContext();

    String rolesCtxDN = getRolesCtxDN();

    // Search for any roles associated with the user
    if (rolesCtxDN != null) {

        // The attribute where user DN is stored in roles :
        String uidAttributeID = getUidAttributeID();
        if (uidAttributeID == null)
            uidAttributeID = "uniquemember";

        // The attribute that identifies the role name 
        String roleAttrName = getRoleAttributeID();
        if (roleAttrName == null)
            roleAttrName = "roles";

        String userDN;
        if ("UID".equals(getRoleMatchingMode())) {
            // Use User ID to match the role
            userDN = username;
        } else if ("PRINCIPAL".equals(getRoleMatchingMode())) {
            // Use User ID to match the role
            userDN = _principalUidAttributeID + "=" + username;
        } else {
            // Default behaviour: Match the role using the User DN, not just the username :
            userDN = selectUserDN(username);
        }

        if (logger.isDebugEnabled())
            logger.debug(
                    "Searching Roles for user '" + userDN + "' in Uid attribute name '" + uidAttributeID + "'");

        if (userDN == null)
            throw new NoSuchUserException(username);

        try {
            if (userDN.contains("\\")) {
                logger.debug("Escaping '\\' character");
                userDN = userDN.replace("\\", "\\\\\\");
            }

            NamingEnumeration answer = ctx.search(rolesCtxDN, "(&(" + uidAttributeID + "=" + userDN + "))",
                    getSearchControls());

            if (logger.isDebugEnabled())
                logger.debug("Search Name:  " + rolesCtxDN);

            if (logger.isDebugEnabled())
                logger.debug("Search Filter:  (&(" + uidAttributeID + "=" + userDN + "))");

            if (!answer.hasMore())
                logger.info("No roles found for user " + username);

            while (answer.hasMore()) {
                SearchResult sr = (SearchResult) answer.next();
                Attributes attrs = sr.getAttributes();
                Attribute roles = attrs.get(roleAttrName);
                for (int r = 0; r < roles.size(); r++) {
                    Object value = roles.get(r);
                    String roleName = null;
                    // The role attribute value is the role name
                    roleName = value.toString();

                    if (roleName != null) {
                        if (logger.isDebugEnabled())
                            logger.debug("Saving role '" + roleName + "' for user '" + username + "'");
                        userRoles.add(roleName);
                    }
                }
            }
        } catch (NamingException e) {
            if (logger.isDebugEnabled())
                logger.debug("Failed to locate roles", e);
        }
    }
    // Close the context to release the connection
    ctx.close();
    return (String[]) userRoles.toArray(new String[userRoles.size()]);
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

private void writeSearchResult(final SearchResult sr, final XMLBuffer xmlb) throws NamingException {
    final Attributes attrs = sr.getAttributes();
    final int size = attrs.size();
    final ArrayList<Attribute> sortedAttrs = new ArrayList<>(size);

    xmlb.openTag("searchresult"); // $NON-NLS-1$
    xmlb.tag("dn", sr.getName()); // $NON-NLS-1$
    xmlb.tag("returnedattr", Integer.toString(size)); // $NON-NLS-1$
    xmlb.openTag("attributes"); // $NON-NLS-1$

    try {//  ww  w.  ja va  2s  .  c  om
        for (NamingEnumeration<? extends Attribute> en = attrs.getAll(); en.hasMore();) {
            final Attribute attr = en.next();
            sortedAttrs.add(attr);
        }
        sortAttributes(sortedAttrs);
        for (final Attribute attr : sortedAttrs) {
            StringBuilder sb = new StringBuilder();
            if (attr.size() == 1) {
                sb.append(getWriteValue(attr.get()));
            } else {
                final ArrayList<String> sortedVals = new ArrayList<>(attr.size());
                boolean first = true;

                for (NamingEnumeration<?> ven = attr.getAll(); ven.hasMore();) {
                    final Object value = getWriteValue(ven.next());
                    sortedVals.add(value.toString());
                }

                Collections.sort(sortedVals);

                for (final String value : sortedVals) {
                    if (first) {
                        first = false;
                    } else {
                        sb.append(", "); // $NON-NLS-1$
                    }
                    sb.append(value);
                }
            }
            xmlb.tag(attr.getID(), sb);
        }
    } finally {
        xmlb.closeTag("attributes"); // $NON-NLS-1$
        xmlb.closeTag("searchresult"); // $NON-NLS-1$
    }
}

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

/**
 * Fetch the Ldap user attributes to be used as credentials.
 *
 * @param uid the user id for whom credentials are required
 * @return the hash map containing user credentials as name/value pairs
 * @throws NamingException LDAP error obtaining user credentials.
 *//*from  w ww .j a va2 s  .c om*/
protected HashMap selectCredentials(String uid) throws NamingException {
    HashMap credentialResultSet = new HashMap();

    InitialLdapContext ctx = createLdapInitialContext();

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

    // BasicAttributes matchAttrs = new BasicAttributes(true);
    // matchAttrs.put(principalUidAttrName, uid);

    String credentialQueryString = getCredentialQueryString();
    HashMap credentialQueryMap = parseQueryString(credentialQueryString);

    Iterator i = credentialQueryMap.keySet().iterator();
    List credentialAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        credentialAttrList.add(o);
    }

    String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]);

    try {

        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr);

        // 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();

            for (int j = 0; j < credentialAttr.length; j++) {

                Object credentialObject = attrs.get(credentialAttr[j]).get();
                String credentialName = (String) credentialQueryMap.get(credentialAttr[j]);
                String credentialValue = null;

                if (logger.isDebugEnabled())
                    logger.debug("Found user credential '" + credentialName + "' of type '"
                            + credentialObject.getClass().getName() + ""
                            + (credentialObject.getClass().isArray()
                                    ? "[" + Array.getLength(credentialObject) + "]"
                                    : "")
                            + "'");

                // if the attribute value is an array, cast it to byte[] and then convert to
                // String using proper encoding
                if (credentialObject.getClass().isArray()) {

                    try {
                        // Try to create a UTF-8 String, we use java.nio to handle errors in a better way.
                        // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is.
                        byte[] credentialData = (byte[]) credentialObject;
                        ByteBuffer in = ByteBuffer.allocate(credentialData.length);
                        in.put(credentialData);
                        in.flip();

                        Charset charset = Charset.forName("UTF-8");
                        CharsetDecoder decoder = charset.newDecoder();
                        CharBuffer charBuffer = decoder.decode(in);

                        credentialValue = charBuffer.toString();

                    } catch (CharacterCodingException e) {
                        if (logger.isDebugEnabled())
                            logger.debug("Can't convert credential value to String using UTF-8");
                    }

                } else if (credentialObject instanceof String) {
                    // The credential value must be a String ...
                    credentialValue = (String) credentialObject;

                }

                // Check what do we have ...
                if (credentialValue != null) {
                    // Remove any schema information from the credential value, like the {md5} prefix for passwords.
                    credentialValue = getSchemeFreeValue(credentialValue);
                    credentialResultSet.put(credentialName, credentialValue);
                } else {
                    // We have a binary credential, leave it as it is ... probably binary value.
                    credentialResultSet.put(credentialName, credentialObject);
                }

                if (logger.isDebugEnabled())
                    logger.debug("Found user credential '" + credentialName + "' with value '"
                            + (credentialValue != null ? credentialValue : credentialObject) + "'");
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return credentialResultSet;
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

protected Organisation convertLdapGroupsToOrganizationPrivileges(Organisation pOrg,
        NamingEnumeration<SearchResult> pPrivilegesResult) throws ExecutionException {
    try {/*from  w  w  w .  j  a v a  2 s .co  m*/
        if (pPrivilegesResult != null) {
            PrivilegeEnum p;
            SearchResult sr;
            String vCnPrivileg;
            // construct privileges
            while (pPrivilegesResult.hasMore()) {
                sr = pPrivilegesResult.next();
                vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get();
                p = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn);
                if (p != null) {
                    pOrg.addPrivileges(p);
                } else {
                    LOG.log(Level.WARNING,
                            "Die Organisation ''{0}'' verfgt ber einen nicht existierende Privileg: ''{1}''!",
                            new Object[] { pOrg.getId(), vCnPrivileg });
                }
            }
            // -- releases this context's resources immediately, instead of waiting for the garbage collector
            pPrivilegesResult.close();
        }
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        // -- releases this context's resources immediately, instead of waiting for the garbage collector
        if (pPrivilegesResult != null) {
            try {
                pPrivilegesResult.close();
            } catch (NamingException ex) {
            }
        }
    }
    return pOrg;
}

From source file:com.wfp.utils.LDAPUtils.java

@SuppressWarnings("unchecked")
public static void parseData(NamingEnumeration searchResults) {

    int totalResultLogger = 0;
    if (searchResults == null) {
        return;/*from   ww  w.  j  av a 2s .  c  o  m*/
    }
    // Loop through the search results
    while (searchResults.hasMoreElements()) {
        SearchResult sr = null;
        try {
            sr = (SearchResult) searchResults.next();
        } catch (NamingException e1) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
        }
        if (sr == null) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
            return;
        }

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {

            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) {
                    }
                }
            } catch (NamingException e) {
                Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e);
            }

        } else {
            Logger.info("No attributes found on LDAP", LDAPUtils.class);
        }
    }
}