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:LdapSearch.java

public static void main(String[] args) throws Exception {
    Hashtable env = new Hashtable();

    String sp = "com.sun.jndi.ldap.LdapCtxFactory";
    env.put(Context.INITIAL_CONTEXT_FACTORY, sp);

    String ldapUrl = "ldap://localhost:389/dc=yourName, dc=com";
    env.put(Context.PROVIDER_URL, ldapUrl);

    DirContext dctx = new InitialDirContext(env);

    String base = "ou=People";

    SearchControls sc = new SearchControls();
    String[] attributeFilter = { "cn", "mail" };
    sc.setReturningAttributes(attributeFilter);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "(&(sn=W*)(l=Criteria*))";

    NamingEnumeration results = dctx.search(base, filter, sc);
    while (results.hasMore()) {
        SearchResult sr = (SearchResult) results.next();
        Attributes attrs = sr.getAttributes();

        Attribute attr = attrs.get("cn");
        System.out.print(attr.get() + ": ");
        attr = attrs.get("mail");
        System.out.println(attr.get());
    }//from   w  ww. j  av a2 s. c o  m
    dctx.close();
}

From source file:AttributeExample.java

public static void main(String[] argc) throws Exception {
    Hashtable env = new Hashtable(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, "ldap://MyHost/o=JNDIExample");
    DirContext dctx = new InitialDirContext(env);
    Attributes attrs = new BasicAttributes(true);
    attrs.put(new BasicAttribute("email"));
    attrs.put(new BasicAttribute("website", "www.pri.com"));

    NamingEnumeration result = dctx.search("ou=People", attrs);

    while (result.hasMore()) {
        SearchResult sr = (SearchResult) result.next();
        System.out.println("Result = " + sr.getName());
        Attributes srchAttrs = sr.getAttributes();

        NamingEnumeration attributes = srchAttrs.getAll();

        while (attributes.hasMore()) {
            Attribute attr = (Attribute) attributes.next();
            System.out.println("Attribute: " + attr.getID());
            NamingEnumeration values = attr.getAll();
            while (values.hasMore()) {
                Object value = values.next();
                System.out.println("Value = " + value);
            }/*from  www . ja va  2 s.  co m*/
        }
    }
}

From source file:org.sonar.plugins.ldap.LdapGroupMapping.java

private static String getAttributeValue(SearchResult user, String attributeId) {
    Attribute attribute = user.getAttributes().get(attributeId);
    if (attribute == null) {
        return null;
    }//from  ww  w  .j  a  v a 2  s  . co  m
    try {
        return (String) attribute.get();
    } catch (NamingException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.jaeksoft.searchlib.util.ActiveDirectory.java

public static final Attributes getAttributes(NamingEnumeration<SearchResult> result) throws NamingException {
    if (result == null)
        return null;
    if (!result.hasMore())
        return null;
    SearchResult rs = (SearchResult) result.next();
    return rs.getAttributes();
}

From source file:org.ballerinalang.stdlib.ldap.nativeimpl.GetLdapScopesOfUser.java

private static List<String> getListOfNames(List<String> searchBases, String searchFilter,
        SearchControls searchCtls, String property, DirContext ldapConnectionContext) throws NamingException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Result for searchBase: " + searchBases + " searchFilter: " + searchFilter + " property:"
                + property + " appendDN: false");
    }//from ww w  .  j ava 2  s  .  c  o m

    List<String> names = new ArrayList<>();
    NamingEnumeration<SearchResult> answer = null;
    try {
        // handle multiple search bases
        for (String searchBase : searchBases) {
            answer = ldapConnectionContext.search(LdapUtils.escapeDNForSearch(searchBase), searchFilter,
                    searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult searchResult = answer.next();
                if (searchResult.getAttributes() == null) {
                    continue;
                }
                Attribute attr = searchResult.getAttributes().get(property);
                if (attr == null) {
                    continue;
                }
                for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
                    String name = (String) vals.nextElement();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Found user: " + name);
                    }
                    names.add(name);
                }
            }

            if (LOG.isDebugEnabled()) {
                for (String name : names) {
                    LOG.debug("Result  :  " + name);
                }
            }
        }
    } finally {
        LdapUtils.closeNamingEnumeration(answer);
    }
    return names;
}

From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ExportDsmlRunnable.java

/**
 * Converts the given {@link SearchResult} to a {@link SearchResultEntryDsml}.
 *
 * @param searchResult the search result
 * @return the associated search result entry DSML
 * @throws org.apache.directory.api.ldap.model.exception.LdapException
 *//*from w w  w.ja  v  a  2 s. c om*/
private static DsmlDecorator<? extends Response> convertSearchResultToDsml(SearchResult searchResult)
        throws LdapException {
    Entry entry = AttributeUtils.toEntry(searchResult.getAttributes(),
            new Dn(searchResult.getNameInNamespace()));

    if (isReferral(entry)) {
        // The search result is a referral
        SearchResultReferenceDsml srr = new SearchResultReferenceDsml(codec);

        // Getting the 'ref' attribute
        Attribute refAttribute = entry.get(ExportDsmlRunnable.REF_ATTRIBUTETYPE_NAME);
        if (refAttribute == null) {
            // If we did not get it by its name, let's get it by its OID
            refAttribute = entry.get(ExportDsmlRunnable.REF_ATTRIBUTETYPE_OID);
        }

        // Adding references
        if (refAttribute != null) {
            for (Value value : refAttribute) {
                srr.addSearchResultReference(new LdapUrl((String) value.getValue()));
            }
        }

        return srr;
    } else {
        // The search result is NOT a referral
        SearchResultEntryDsml sre = new SearchResultEntryDsml(codec);
        sre.setEntry(entry);

        return sre;
    }
}

From source file:org.wso2.carbon.appfactory.userstore.internal.OTLDAPUtil.java

public static String getEmailFromUserId(String uid, LDAPConnectionContext connectionSource,
        String userSearchBase) throws UserStoreException {

    // check from cache
    String email = otEmailCache.getValueFromCache(uid);
    if (email != null && !email.isEmpty()) {
        return email;
    }/* w ww .  jav a 2  s  .  c o m*/

    // check from ldap and update the cache
    StringBuffer buff = new StringBuffer();
    buff.append("(&(objectClass=inetOrgPerson)(uid=").append(uid).append("))");
    if (log.isDebugEnabled()) {
        log.debug("Searching for " + buff.toString());
    }
    DirContext dirContext = connectionSource.getContext();
    NamingEnumeration<SearchResult> answer = null;
    try {
        String[] returnedAttributes = { "mail" };
        answer = searchForUser(buff.toString(), returnedAttributes, dirContext, userSearchBase);
        int count = 0;
        SearchResult userObj = null;
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            if (count > 0) {
                log.error("More than one user exist for the same name");
            }
            count++;
            userObj = sr;
        }
        if (userObj != null) {

            Attributes attributes = userObj.getAttributes();
            Attribute mailAttribute = attributes.get("mail");
            if (mailAttribute != null) {
                email = mailAttribute.getID();
            }
        }
        otEmailCache.addToCache(uid, email);
        return email;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }

}

From source file:org.jkcsoft.java.util.JndiHelper.java

public static Map getUserInfo(BehavioralContext ctx, String userName) throws NamingException {
    Map infoMap = null;/*w w  w  .  ja v a  2 s. com*/

    Configuration cfg = ctx.getConfig();
    // 
    String searchRelativeDc = cfg.getString(Constants.KEY_AD_USER_NODE_DN);
    String theFilter = LDAP_USER_SAMACCOUNTNAME + "=" + userName;
    List theAttrsList = new Vector(Arrays.asList(ldapUserAttrs));
    theAttrsList.addAll(Arrays.asList(ldapTopAttrs));

    int countLimit = 1000;
    int timeLimitMillis = 30000;
    boolean returnObject = false;
    boolean derefObj = true;

    SearchControls scs = new SearchControls(SearchControls.SUBTREE_SCOPE, countLimit, timeLimitMillis,
            (String[]) theAttrsList.toArray(new String[0]), returnObject, derefObj);

    DirContext rootCtx = getTsessAccountContext(ctx);

    try {
        log.debug("Search params name[" + searchRelativeDc + "] " + "filter[" + theFilter + "] controls[" + scs
                + "]");

        NamingEnumeration results = rootCtx.search(searchRelativeDc, theFilter, scs);

        if (results == null || !results.hasMore())
            throw new NamingException("User LDAP entry not found");

        SearchResult searchResult = ((SearchResult) results.next());
        if (searchResult == null)
            throw new NamingException("User LDAP entry not found");

        if (log.isTraceEnabled()) {
            logLdap(log, 0, 0, searchResult);
        }

        Attributes userLdapAttrs = searchResult.getAttributes();
        infoMap = new HashMap();
        for (Iterator attrIter = theAttrsList.iterator(); attrIter.hasNext();) {
            loadMap(infoMap, userLdapAttrs, (String) attrIter.next());
        }
    } finally {
        safeClose(rootCtx);
    }

    return infoMap;
}

From source file:org.jkcsoft.java.util.JndiHelper.java

public static void logLdap(Log plog, int level, int nth, Object dirEntry) throws NamingException {
    try {//from  ww w  . ja  v a 2  s .c  o  m
        if (dirEntry instanceof NamingEnumeration) {
            NamingEnumeration nameEnum = (NamingEnumeration) dirEntry;
            JndiHelper.logLevel(plog, level, nth, "Naming Enumeration: " + nameEnum);
            try {
                int nthThis = 0;
                List nameList = new Vector(Collections.list(nameEnum));
                Collections.sort(nameList, new Comparator() {
                    public int compare(Object o1, Object o2) {
                        if (o1 instanceof Attribute) {
                            return String.CASE_INSENSITIVE_ORDER.compare(((Attribute) o1).getID(),
                                    ((Attribute) o2).getID());
                        }
                        return 0;
                    }
                });
                Iterator nameIter = nameList.iterator();
                while (nameIter.hasNext()) {
                    logLdap(plog, level + 1, nthThis++, nameIter.next());
                }
            } catch (NamingException ex) {
                plog.error("Exception iterating thru NamingEnumeration: " + ex.getMessage());
            }
        } else if (dirEntry instanceof Attribute) {
            Attribute dirAttr = (Attribute) dirEntry;
            JndiHelper.logLevel(plog, level, nth, "Attribute: [" + dirAttr + "]");
        } else if (dirEntry instanceof DirContext) {
            DirContext lctx = (DirContext) dirEntry;
            JndiHelper.logLevel(plog, level, nth,
                    "LDAP Context: DN [" + lctx.getNameInNamespace() + "]" + " Attributes ==>");
            logLdap(plog, level, nth, lctx.getAttributes("").getAll());
        } else if (dirEntry instanceof SearchResult) {
            SearchResult sr = (SearchResult) dirEntry;
            JndiHelper.logLevel(plog, level, nth, "SearchResult: ClassName of Bound Object ["
                    + sr.getClassName() + "]" + " Name: [" + sr.getName() + "]" + " Bound Object ==>");
            //                sr.s
            logLdap(plog, level, nth, sr.getObject());
            logLdap(plog, level, nth, sr.getAttributes().getAll());
        } else {
            JndiHelper.logLevel(plog, level, nth, "(?) class of entry: [" + dirEntry + "]");
        }
        nth++;
    } catch (NamingException e1) {
        plog.error("Naming Exception (will try to continue): " + e1.getMessage());
    }
}

From source file:fr.iphc.grid.jobmonitor.CeList.java

static public ArrayList<URL> AvailableLdapCe() throws Exception {
    ArrayList<URL> CeList = new ArrayList<URL>();
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://cclcgtopbdii01.in2p3.fr:2170");
    env.put("java.naming.ldap.attributes.binary", "objectSID");
    try {//from w  ww.j a  v a  2 s. co  m
        // Create initial context
        DirContext ctx = new InitialDirContext(env);
        SearchControls contraints = new SearchControls();
        contraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attributIDs = { "GlueCEUniqueID" };
        contraints.setReturningAttributes(attributIDs);
        String BASE_SEARCH = "Mds-Vo-name=local,o=grid";
        String filter = "(&(objectClass=GlueCE)(GlueCEImplementationName=CREAM)(GlueCEAccessControlBaseRule=VO:biomed))";
        NamingEnumeration<SearchResult> answer = ctx.search(BASE_SEARCH, filter, contraints);
        //         int index = 0;
        Random rand = new Random();
        while (answer.hasMore()) {
            //            index++;
            SearchResult result = answer.next();
            //            Attributes attrs = result.getAttributes();
            //            NamingEnumeration f = attrs.getAll();
            //            Attribute attr = (Attribute) f.next();
            String line = "cream://" + result.getAttributes().get("GlueCEUniqueID").get() + "?delegationId="
                    + rand.nextLong();
            URL serviceURL = URLFactory.createURL(line);
            CeList.add(serviceURL);
        }
        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    ;
    return CeList;
}