Example usage for javax.naming.directory SearchResult getNameInNamespace

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

Introduction

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

Prototype

public String getNameInNamespace() 

Source Link

Document

Retrieves the full name of this binding.

Usage

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Retrieves a list of all groups the user is a member of.
 * @param dirContext a DirContext/*from  w ww. ja v  a2s .  c  o m*/
 * @param ldapUser the LdapUser to retrieve group membership for
 * @return A list of Strings representing the fully qualified DN of each group
 * @throws NamingException if an exception is thrown
 * @since 1.4.0
 */
public List<String> getGroups(DirContext dirContext, LdapUser ldapUser) throws NamingException {
    final List<String> groupDns = new ArrayList<>();
    final String searchFilter = variableSubstitution(USER_GROUPS_FILTER, ldapUser);
    final SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, searchFilter, sc);
    while (hasMoreEnum(ne)) {
        final SearchResult result = ne.next();
        groupDns.add(result.getNameInNamespace());
    }
    closeQuietly(ne);
    return groupDns;
}

From source file:com.hs.mail.security.login.JndiLoginModule.java

@SuppressWarnings("unchecked")
protected boolean authenticate(String username, String password) throws Exception {
    DirContext context = null;//from   w w  w.ja  v a  2  s.c om
    try {
        context = open();
        searchFilterFormat.format(new String[] { username });
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(subtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
        if (returnAttribute != null) {
            String[] attribs = StringUtils.split(returnAttribute, ",");
            constraints.setReturningAttributes(attribs);
        }
        NamingEnumeration ne = context.search(base, searchFilter, constraints);
        if (ne == null || !ne.hasMore()) {
            return false;
        }
        SearchResult sr = (SearchResult) ne.next();
        if (ne.hasMore()) {
            // Ignore for now
        }
        // Check the credentials by binding to server
        if (bindUser(context, sr.getNameInNamespace(), password)) {
            return true;
        } else {
            return true;
        }
    } catch (NamingException e) {
        close(context);
        return false;
    }
}

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

/**
 * Search for this mapping./*from  www  . j a  v  a 2 s .co m*/
 */
public LdapSearch createSearch(LdapContextFactory contextFactory, SearchResult user) {
    String[] attrs = getRequiredUserAttributes();
    String[] parameters = new String[attrs.length];
    for (int i = 0; i < parameters.length; i++) {
        String attr = attrs[i];
        if ("dn".equals(attr)) {
            parameters[i] = user.getNameInNamespace();
        } else {
            parameters[i] = getAttributeValue(user, attr);
        }
    }
    return new LdapSearch(contextFactory).setBaseDn(getBaseDn()).setRequest(getRequest())
            .setParameters(parameters).returns(getIdAttribute());
}

From source file:org.apache.hadoop.security.LdapGroupsMapping.java

List<String> doGetGroups(String user) throws NamingException {
    List<String> groups = new ArrayList<String>();

    DirContext ctx = getDirContext();

    // Search for the user. We'll only ever need to look at the first result
    NamingEnumeration<SearchResult> results = ctx.search(baseDN, userSearchFilter, new Object[] { user },
            SEARCH_CONTROLS);//from   w  ww  .j  a  v  a2s .c  o m
    if (results.hasMoreElements()) {
        SearchResult result = results.nextElement();
        String userDn = result.getNameInNamespace();

        NamingEnumeration<SearchResult> groupResults = null;

        if (isPosix) {
            String gidNumber = null;
            String uidNumber = null;
            Attribute gidAttribute = result.getAttributes().get(posixGidAttr);
            Attribute uidAttribute = result.getAttributes().get(posixUidAttr);
            if (gidAttribute != null) {
                gidNumber = gidAttribute.get().toString();
            }
            if (uidAttribute != null) {
                uidNumber = uidAttribute.get().toString();
            }
            if (uidNumber != null && gidNumber != null) {
                groupResults = ctx.search(
                        baseDN, "(&" + groupSearchFilter + "(|(" + posixGidAttr + "={0})" + "("
                                + groupMemberAttr + "={1})))",
                        new Object[] { gidNumber, uidNumber }, SEARCH_CONTROLS);
            }
        } else {
            groupResults = ctx.search(baseDN, "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
                    new Object[] { userDn }, SEARCH_CONTROLS);
        }
        if (groupResults != null) {
            while (groupResults.hasMoreElements()) {
                SearchResult groupResult = groupResults.nextElement();
                Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
                groups.add(groupName.get().toString());
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("doGetGroups(" + user + ") return " + groups);
    }
    return groups;
}

From source file:net.officefloor.plugin.jndi.ldap.CredentialStoreTest.java

/**
 * Ensure able to obtain the roles.//w w w.  j  a va  2 s .c o m
 */
public void testObtainRoles() throws Exception {

    // Obtain the context
    DirContext context = this.ldap.getDirContext();

    // Obtain the People context
    DirContext people = (DirContext) context.lookup("ou=People,dc=officefloor,dc=net");
    assertNotNull("Should have People context", people);

    // Search for person
    NamingEnumeration<SearchResult> personResults = people.search("",
            "(&(objectClass=inetOrgPerson)(uid=daniel))", null);
    assertTrue("Expecting to find daniel entry", personResults.hasMore());
    SearchResult daniel = personResults.next();
    assertFalse("Should only have the daniel entry", personResults.hasMore());

    // Obtain the Groups context
    DirContext groups = (DirContext) context.lookup("ou=Groups,dc=officefloor,dc=net");
    assertNotNull("Should have Groups context", groups);

    // Search for groups containing daniel
    String danielDn = daniel.getNameInNamespace();
    NamingEnumeration<SearchResult> groupResults = groups.search("",
            "(&(objectClass=groupOfNames)(member=" + danielDn + "))", null);

    // Obtain the listing of roles for daniel
    List<String> roles = new ArrayList<String>(2);
    for (; groupResults.hasMore();) {
        SearchResult group = groupResults.next();

        // Obtain the role from the group
        String role = (String) group.getAttributes().get("ou").get();

        // Add role to listing
        roles.add(role);
    }

    // Ensure the correct roles
    assertEquals("Incorrect number of roles", 2, roles.size());
    assertTrue("Missing user role", roles.contains("developer"));
    assertTrue("Missing developer role", roles.contains("committer"));
}

From source file:org.wso2.carbon.connector.ldap.SearchEntry.java

private OMElement prepareNode(SearchResult entityResult, OMFactory factory, OMNamespace ns,
        String returnAttributes[]) throws NamingException {
    Attributes attributes = entityResult.getAttributes();
    Attribute attribute;/*from ww w  .j  a  v a  2s .com*/
    OMElement entry = factory.createOMElement(LDAPConstants.ENTRY, ns);
    OMElement dnattr = factory.createOMElement(LDAPConstants.DN, ns);
    dnattr.setText(entityResult.getNameInNamespace());
    entry.addChild(dnattr);

    for (int i = 0; i < returnAttributes.length; i++) {
        attribute = attributes.get(returnAttributes[i]);
        if (attribute != null) {
            NamingEnumeration ne = null;
            ne = attribute.getAll();
            while (ne.hasMoreElements()) {
                String value = (String) ne.next();
                OMElement attr = factory.createOMElement(returnAttributes[i], ns);
                attr.setText(value);
                entry.addChild(attr);
            }
        }
    }
    return entry;
}

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

/**
 * Converts the given {@link SearchResult} to an {@link AddRequestDsml}.
 *
 * @param searchResult//from w  w w  .java 2s .  co  m
 *      the {@link SearchResult}
 * @return
 *      the associated {@link AddRequestDsml}
 * @throws LdapException
 */
private AddRequestDsml convertToAddRequestDsml(SearchResult searchResult) throws LdapException {
    AddRequestDsml ar = new AddRequestDsml(codec);
    Entry entry = AttributeUtils.toEntry(searchResult.getAttributes(),
            new Dn(searchResult.getNameInNamespace()));
    ar.setEntry(entry);

    return ar;
}

From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java

private String findPrincipalDN(String normalizedPrincipal) throws NamingException, KerberosOperationException {
    String dn = null;//from   w  ww.j ava 2 s  .c om

    if (normalizedPrincipal != null) {
        NamingEnumeration<SearchResult> results = null;

        try {
            results = ldapContext.search(principalContainerDn,
                    String.format("(userPrincipalName=%s)", normalizedPrincipal), searchControls);

            if ((results != null) && results.hasMore()) {
                SearchResult result = results.next();
                dn = result.getNameInNamespace();
            }
        } finally {
            try {
                if (results != null) {
                    results.close();
                }
            } catch (NamingException ne) {
                // ignore, we can not do anything about it
            }
        }
    }

    return dn;
}

From source file:org.wso2.carbon.appfactory.userstore.AppFactoryTenantManager.java

protected String getNameInSpaceForUserName(String userName) throws UserStoreException {
    DirContext dirContext;// w w w.  j a  v  a 2  s .c  o  m
    String usernameSearchFilter = realmConfig.getUserStoreProperty("UserNameListFilter");
    String userNameProperty = realmConfig.getUserStoreProperty("UserNameAttribute");
    String searchFilter = getSearchFilter(usernameSearchFilter, userNameProperty, userName);
    if (log.isDebugEnabled()) {
        log.debug((new StringBuilder()).append("Searching for ").append(searchFilter).toString());
    }
    dirContext = ldapConnectionSource.getContext();
    NamingEnumeration answer = null;
    String userDn;
    try {
        String name = null;
        answer = searchForObject(searchFilter, null, dirContext,
                realmConfig.getUserStoreProperty("UserSearchBase"));
        int count = 0;
        SearchResult userObj;
        SearchResult sr;
        for (userObj = null; answer.hasMoreElements(); userObj = sr) {
            sr = (SearchResult) answer.next();
            if (count > 0) {
                log.error("More than one user exist for the same name");
            }
            count++;
        }

        if (userObj != null) {
            name = userObj.getNameInNamespace();
        }
        userDn = name;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return userDn;
}