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.apereo.portal.groups.ldap.LDAPGroupStore.java

protected void processLdapResults(NamingEnumeration results, ArrayList keys) {
    //long time1 = System.currentTimeMillis();
    //long casting=0;
    //long getting=0;
    //long setting=0;
    //long looping=0;
    //long loop1=System.currentTimeMillis();
    try {// w  w  w  . j a  va  2 s  .  c  o m
        while (results.hasMore()) {
            //long loop2 = System.currentTimeMillis();
            //long cast1=System.currentTimeMillis();
            //looping=looping+loop2-loop1;
            SearchResult result = (SearchResult) results.next();
            //long cast2 = System.currentTimeMillis();
            //long get1 = System.currentTimeMillis();
            Attributes ldapattribs = result.getAttributes();
            //long get2 = System.currentTimeMillis();
            //long set1 = System.currentTimeMillis();
            Attribute attrib = ldapattribs.get(keyfield);
            if (attrib != null) {
                keys.add(String.valueOf(attrib.get()).toLowerCase());
            }
            //long set2 = System.currentTimeMillis();
            //loop1=System.currentTimeMillis();
            //casting=casting+cast2-cast1;
            //setting=setting+set2-set1;
            //getting=getting+get2-get1;
        }
    } catch (NamingException nex) {
        log.error("LDAPGroupStore: error processing results", nex);
    } finally {
        try {
            results.close();
        } catch (Exception e) {
        }
    }
    //long time5 = System.currentTimeMillis();
    //System.out.println("Result processing took "+(time5-time1)+": "+getting+" for getting, "
    //  +setting+" for setting, "+casting+" for casting, "+looping+" for looping,"
    //  +(time5-loop1)+" for closing");
}

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.j a  va2  s.  c om
 * @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:com.wfp.utils.LDAPUtils.java

public static String getUserImageAsString(String uid) {
    String base64String = null;
    if (uid != null && uid != "") {
        // Specify the attributes to return
        String searchFilter = "(&" + FILTER_LDAP_USERS + "((uid=" + uid + ")))";
        String searchBase = LDAP_FILTER_URL + "uid=" + uid + "," + LDAP_BASE;

        String returnedAtts[] = { "" + PROPERTY_IMAGE };
        // Specify the search scope
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchCtls.setReturningAttributes(returnedAtts);
        // Search for objects using the filter
        try {/*from ww w .j ava2s  .  com*/
            NamingEnumeration results = getSearchResults(getLDAPContext(), searchCtls, searchFilter,
                    searchBase);
            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();
                Attribute attr = attributes.get(PROPERTY_IMAGE);
                if (attr != null)
                    base64String = new String(
                            org.apache.commons.codec.binary.Base64.encodeBase64((byte[]) attr.get()));

            }
        } catch (NamingException e) {
            Logger.error(" Error occured while fetching user image 1334: getUserImageBytes(String uid):["
                    + e.getLocalizedMessage() + "]", LDAPUtils.class);
        }
    }
    return base64String;
}

From source file:ldap.ActiveLoginImpl.java

/**
 * Returns whether this user is listed in the admin users role
 *
 * @param login//from   ww  w  .j a v  a 2 s  .  c om
 * @return
 * @throws Exception
 */
public boolean isAdmin(String login, DirContext context, String DN) throws Exception {
    NamingEnumeration result = null;

    String[] returnAttributes = new String[] { "uniqueMember" };

    /* specify search constraints to search subtree */
    SearchControls constraints = new SearchControls();

    constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
    constraints.setCountLimit(0);
    constraints.setTimeLimit(0);

    constraints.setReturningAttributes(returnAttributes);
    /*
            Entry user = null;
            try {
    user = searcher.getUser(LdapConstants.ldapAttrLogin, login, context);
            } catch (NamingException e) {
               throw new LdapException("getUser NamingException" + e.getMessage(), e);
            }
       String DN = null;
            if (user == null) {
               logger.info("USER DOES NOT EXIST");
               return false;
            } else {
          DN = user.getName().toString();
               if (DN != null) {
      logger.info("DN = " + DN);
               }
       }
    */

    //result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember="+getUserDN(login)+")", constraints);
    result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember=" + DN + ")", constraints);

    if (result.hasMore()) {
        if (debug) {
            SearchResult sResult = (SearchResult) result.next();
            logger.info("Read Admin Roles Object with members: " + sResult.getAttributes().toString());
        }
        return true;
    } else if (debug)
        logger.info("Failed to find admin object with member " + DN);

    return false;
}

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

/**
 * @throws NamingException//from  w  ww  . ja  v  a2 s.c om
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String)
 */
protected Set<Map<String, String>> buildGroup(Properties systemConfig, String filter) {
    Set<Map<String, String>> ret = new HashSet<Map<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";
    }
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);
    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();
        /*String filter = "(&(objectclass=groupOfUniqueNames)(uniqueMember=uid=" + userName
        + ",ou=People, dc=rhndev, dc=redhat, dc=com))";*/

        // 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);
            boolean ldapApiEnumerationBugEncountered = false;
            while ((!ldapApiEnumerationBugEncountered) && answer.hasMoreElements()) {//BZ:582471- ldap api bug change
                // We use the first match
                SearchResult si = null;
                try {
                    si = answer.next();
                } catch (NullPointerException npe) {
                    ldapApiEnumerationBugEncountered = true;
                    break;
                }
                Map<String, String> entry = new HashMap<String, String>();
                String name = (String) si.getAttributes().get("cn").get();
                name = name.trim();
                Attribute desc = si.getAttributes().get("description");
                String description = desc != null ? (String) desc.get() : "";
                description = description.trim();
                entry.put("id", name);
                entry.put("name", name);
                entry.put("description", description);
                ret.add(entry);
            }
        }
    } catch (NamingException e) {
        if (e instanceof InvalidSearchFilterException) {
            InvalidSearchFilterException fException = (InvalidSearchFilterException) e;
            String message = "The ldap group filter defined is invalid ";
            log.error(message, fException);
            throw new LdapFilterException(message + " " + fException.getMessage());
        }
        //TODO: check for ldap connection/unavailable/etc. exceptions.
        else {
            log.error("LDAP communication error: " + e.getMessage(), e);
            throw new LdapCommunicationException(e);
        }
    }

    return ret;
}

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

public List<String> getGroups(String username, DirContext context) throws MappingException {

    List<String> userGroups = new ArrayList<String>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {//www .  j a  v  a  2  s.  c  o m

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String groupEntry = null;
        try {
            //try to look the user up
            User user = userManager.findUser(username);
            if (user instanceof LdapUser) {
                LdapUser ldapUser = LdapUser.class.cast(user);
                Attribute dnAttribute = ldapUser.getOriginalAttributes().get(getLdapDnAttribute());
                if (dnAttribute != null) {
                    groupEntry = String.class.cast(dnAttribute.get());
                }

            }
        } catch (UserNotFoundException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        } catch (UserManagerException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        }
        if (groupEntry == null) {
            //failed to look up the user's groupEntry directly
            StringBuilder builder = new StringBuilder();
            String posixGroup = "posixGroup";
            if (posixGroup.equals(getLdapGroupClass())) {
                builder.append(username);
            } else {
                builder.append(this.userIdAttribute).append("=").append(username).append(",")
                        .append(getBaseDn());
            }
            groupEntry = builder.toString();
        }

        String filter = new StringBuilder().append("(&").append("(objectClass=" + getLdapGroupClass() + ")")
                .append("(").append(getLdapGroupMember()).append("=").append(Rdn.escapeValue(groupEntry))
                .append(")").append(")").toString();

        log.debug("filter: {}", filter);

        namingEnumeration = context.search(getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            List<String> allMembers = new ArrayList<String>();

            Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember());

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {

                    String userName = allMembersEnum.next();
                    //the original dn
                    allMembers.add(userName);
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    allMembers.add(userName);
                }
                close(allMembersEnum);
            }

            if (allMembers.contains(username)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);

            } else if (allMembers.contains(groupEntry)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);
            }

        }

        return userGroups;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    } finally {
        close(namingEnumeration);
    }
}

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

protected Set<PrivilegeEnum> convertLdapGroupsToOrganizationPrivileges(
        NamingEnumeration<SearchResult> pPrivilegesResult) {
    Set<PrivilegeEnum> vResult = EnumSet.noneOf(PrivilegeEnum.class);
    NamingEnumeration<SearchResult> vSearchResults = pPrivilegesResult;
    try {//from   w ww .  j  a  v a  2s .  c o m
        if (pPrivilegesResult != null) {
            PrivilegeEnum p;
            SearchResult sr;
            String vCnPrivileg;
            // construct privileges
            while (vSearchResults.hasMore()) {
                sr = vSearchResults.next();
                vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get();
                p = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn);
                if (p != null) {
                    vResult.add(p);
                } else {
                    LOG.log(Level.WARNING,
                            "Es ist ein nicht existierende Privileg: ''{0}'' im LDAP gespeichert!",
                            new Object[] { vCnPrivileg });
                }
            }
            // -- releases this context's resources immediately, instead of
            // waiting for the garbage collector
            vSearchResults.close();
        }
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
    } finally {
        // -- releases this context's resources immediately, instead of
        // waiting for the garbage collector
        if (vSearchResults != null) {
            try {
                vSearchResults.close();
            } catch (NamingException ex) {
            }
        }
    }
    return vResult;
}

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

/**
 * get attribute values of given resource and attributes.
 * /*  w w  w  .j a  v  a2  s.  c  o  m*/
 * @param scope
 *            scope
 * @param id
 *            id of resource
 * @param attributeName
 *            attribute-name to retrieve
 * 
 * @return String attribute value
 * @throws NamingException
 * @throws IllegalAccessException
 */
public Map<String, String> getResourceAttributes(Scope scope, String id, String[] attributeNames)
        throws NamingException, IllegalAccessException {
    Map<String, String> returnMap = new HashMap<String, String>();
    String baseDn = null;
    String filter = getIdFilter(scope, id);
    int levelScope = 0;
    InitialLdapContext ctx = null;
    NamingEnumeration<SearchResult> results = null;
    if (scope == Scope.ORGANIZATION) {
        baseDn = LDAPConnector.getSingletonInstance().getInstitutionBaseDN();
        levelScope = SearchControls.SUBTREE_SCOPE;
    } else if (scope == Scope.PERSON) {
        baseDn = LDAPConnector.getSingletonInstance().getPersonBaseDN();
        levelScope = SearchControls.ONELEVEL_SCOPE;
    }
    try {
        ctx = LDAPConnector.getSingletonInstance().takeCtx();
        results = query(ctx, baseDn, filter, attributeNames, levelScope);
        if (results.hasMore()) {
            SearchResult searchResult = results.next();
            if (results.hasMore()) {
                throw new IllegalAccessException("found more than one object with id=" + id);
            }
            Attributes attributes = searchResult.getAttributes();
            for (int i = 0; i < attributeNames.length; i++) {
                Attribute attribute = attributes.get(attributeNames[i]);
                if (attribute == null) {
                    returnMap.put(attributeNames[i], (String) null);
                } else {
                    returnMap.put(attributeNames[i], (String) attribute.get());
                }
            }
            return returnMap;
        } else {
            throw new NameNotFoundException("id not found");
        }

    } finally {
        if (ctx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(ctx);
            } catch (IllegalAccessException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
        if (results != null) {
            try {
                results.close();
            } catch (NamingException e) {
                LOG.log(Level.WARNING, null, e);
            }
        }
    }
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * This method will perform multiple queries into Active Directory
 * in order to resolve what groups a user is a member of.  The
 * logic will identify nested groups and add them to the table.
 * <p>/*  w  w  w  .  java2 s .  co m*/
 * The LDAP_ACCOUNT_NAME field must be populated in the user bag
 * prior to invoking this method.  Any site specific fields can be
 * assigned to the user bag will be included in the attribute query.
 * </p>
 * <p>
 * Any site specific fields can be assigned to the group bag will
 * be included in the attribute query.
 * </p>
 *
 * @param aUserBag Active Directory user attributes.
 * @param aGroupBag Active Directory group attributes.
 *
 * @return Table of groups that the user is a member of.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 */
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public DataTable loadUserGroupsByAccountName(DataBag aUserBag, DataBag aGroupBag) throws NSException {
    byte[] objectSid;
    DataBag groupBag;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserGroupsByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    // First, we will populate our user bag so that we can obtain the distinguished name.

    loadUserByAccountName(aUserBag);

    // Now we will use the DN to find all of the groups the user is a member of.

    String distinguishedName = aUserBag.getValueAsString(LDAP_DISTINGUISHED_NAME);
    if (StringUtils.isEmpty(distinguishedName))
        distinguishedName = getPropertyValue("user_searchbasedn", null);

    // Next, we will initialize our group membership table.

    DataTable memberTable = new DataTable(aUserBag);
    memberTable.setName(String.format("%s Group Membership", aUserBag.getValueAsString(LDAP_COMMON_NAME)));

    // The next logic section will query AD for all of the groups the user is a member
    // of.  Because we are following tokenGroups, we will gain access to nested groups.

    String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null);

    SearchControls userSearchControls = new SearchControls();
    userSearchControls.setSearchScope(SearchControls.OBJECT_SCOPE);

    StringBuffer groupsSearchFilter = null;
    String ldapAttrNames[] = { "tokenGroups" };
    userSearchControls.setReturningAttributes(ldapAttrNames);

    try {
        NamingEnumeration<?> userSearchResponse = mLdapContext.search(distinguishedName, "(objectClass=user)",
                userSearchControls);
        if ((userSearchResponse != null) && (userSearchResponse.hasMoreElements())) {
            groupsSearchFilter = new StringBuffer();
            groupsSearchFilter.append("(|");

            SearchResult userSearchResult = (SearchResult) userSearchResponse.next();
            Attributes userResultAttributes = userSearchResult.getAttributes();
            if (userResultAttributes != null) {
                try {
                    for (NamingEnumeration<?> searchResultAttributesAll = userResultAttributes
                            .getAll(); searchResultAttributesAll.hasMore();) {
                        Attribute attr = (Attribute) searchResultAttributesAll.next();
                        for (NamingEnumeration<?> namingEnumeration = attr.getAll(); namingEnumeration
                                .hasMore();) {
                            objectSid = (byte[]) namingEnumeration.next();
                            groupsSearchFilter.append("(objectSid=" + objectSidToString2(objectSid) + ")");
                        }
                        groupsSearchFilter.append(")");
                    }
                } catch (NamingException e) {
                    String msgStr = String.format("LDAP Listing Member Exception: %s", e.getMessage());
                    appLogger.error(msgStr, e);
                    throw new NSException(msgStr);
                }
            }
            userSearchResponse.close();

            // Finally, we will query each group in the search filter and add it to the table.

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

            int field = 0;
            int attrCount = aGroupBag.count();
            String[] groupsReturnedAtts = new String[attrCount];
            for (DataField complexField : aGroupBag.getFields()) {
                fieldName = complexField.getName();
                groupsReturnedAtts[field++] = fieldName;
            }
            groupSearchControls.setReturningAttributes(groupsReturnedAtts);
            NamingEnumeration<?> groupSearchResponse = mLdapContext.search(groupSearchBaseDN,
                    groupsSearchFilter.toString(), groupSearchControls);
            while ((groupSearchResponse != null) && (groupSearchResponse.hasMoreElements())) {
                SearchResult groupSearchResult = (SearchResult) groupSearchResponse.next();
                Attributes groupResultAttributes = groupSearchResult.getAttributes();
                if (groupResultAttributes != null) {
                    groupBag = new DataBag(aGroupBag);
                    for (DataField complexField : groupBag.getFields()) {
                        fieldName = complexField.getName();
                        responseAttribute = groupResultAttributes.get(fieldName);
                        if (responseAttribute != null) {
                            if (fieldName.equals(LDAP_OBJECT_SID)) {
                                objectSid = (byte[]) responseAttribute.get();
                                fieldValue = objectSidToString2(objectSid);
                            } else
                                fieldValue = (String) responseAttribute.get();
                            if (StringUtils.isNotEmpty(fieldValue))
                                complexField.setValue(fieldValue);
                        }
                    }
                    memberTable.addRow(groupBag);
                }
            }
            if (groupSearchResponse != null)
                groupSearchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", distinguishedName, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return memberTable;
}

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

private void serialize(List results, Config config, ContentHandler ch) {
    try {// w  ww .j a va 2s  .  c o m
        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);
    }
}