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:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

/**
 * Gets all the user entities taken from the LDAP server, as taken from the
 * search-context given by the value of the attribute {@link #userBase}.
 *
 * @return A set containing all the relevant users found in the LDAP
 *         directory./*from   ww w . j a  v  a 2 s. c om*/
 * @throws NamingException
 *             Propagated from the LDAP communication layer.
 */
private Set<String> getAllUsersFromLDAP() throws NamingException {
    Set<String> result = new HashSet<String>();

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { "distinguishedName" });
    NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, "(objectClass=" + userObjectClass + ")",
            sc);
    while (sr.hasMore()) {
        SearchResult r = sr.next();
        result.add(r.getNameInNamespace());
    }

    return result;
}

From source file:net.e2.bw.servicereg.ldap.ServiceInstanceLdapService.java

/** {@inheritDoc} */
@Override/*  w  w w . j a v a 2 s.  c o  m*/
public void removeServiceInstanceRole(String serviceInstanceId, String userId, String role) {
    Objects.requireNonNull(role);
    Objects.requireNonNull(userService.getUser(userId));
    CachedServiceInstance service = Objects.requireNonNull(getCachedServiceInstance(serviceInstanceId));
    String userDN = getUserDN(userId);
    String serviceDN = getServiceInstanceDN(service.getServiceInstanceId());

    // Check if the user does not hold the role
    if (!service.userHasRole(userId, role)) {
        return;
    }

    try {
        List<String> attrs = Collections.singletonList(getConfig().getRoleMemberAttribute());
        // NB: Do NOT create the role entry if it does not exist
        SearchResult roleEntry = searchRoleEntry(serviceDN, role, attrs, true);

        if (roleEntry == null) {
            // Should actually never happen, since the cached service had the corresponding role for the user
            return;
        }

        // Remove the user as a role member
        ldapServerService.removeAttributeValue(roleEntry.getNameInNamespace(),
                getConfig().getRoleMemberAttribute(), userDN, true);
        log.info("Removed " + userId + " as " + role + " for service " + serviceInstanceId);

        // Un-cache the organization
        ldapCache.getServiceInstanceCache().evict(serviceInstanceId);

    } catch (NamingException e) {
        throw new RuntimeException("Error removing service role ", e);
    }
}

From source file:org.apache.cloudstack.ldap.LdapUserManager.java

private LdapUser createUser(final SearchResult result) throws NamingException {
    final Attributes attributes = result.getAttributes();

    final String username = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getUsernameAttribute());
    final String email = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getEmailAttribute());
    final String firstname = LdapUtils.getAttributeValue(attributes,
            _ldapConfiguration.getFirstnameAttribute());
    final String lastname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getLastnameAttribute());
    final String principal = result.getNameInNamespace();

    String domain = principal.replace(
            "cn=" + LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getCommonNameAttribute()) + ",",
            "");// w  w w  .j ava2s. c o m
    domain = domain.replace("," + _ldapConfiguration.getBaseDn(), "");
    domain = domain.replace("ou=", "");

    return new LdapUser(username, email, firstname, lastname, principal, domain);
}

From source file:net.e2.bw.servicereg.ldap.ServiceInstanceLdapService.java

/** {@inheritDoc} */
@Override/*from   w ww .j a v  a  2s  .  c  om*/
public void assignServiceInstanceRole(String serviceInstanceId, String userId, String role) {
    Objects.requireNonNull(role);
    Objects.requireNonNull(userService.getUser(userId));
    CachedServiceInstance service = Objects.requireNonNull(getCachedServiceInstance(serviceInstanceId));
    String userDN = getUserDN(userId);
    String serviceDN = getServiceInstanceDN(service.getServiceInstanceId());

    // Check if the user already holds the role
    if (service.userHasRole(userId, role)) {
        return;
    }

    try {
        List<String> attrs = Collections.singletonList(getConfig().getRoleMemberAttribute());
        // NB: Create the role entry if it does not exist
        SearchResult roleEntry = searchRoleEntry(serviceDN, role, attrs, true);

        if (roleEntry == null) {
            // Failed looking up or creating the role entry
            throw new NamingException("Error getting role entry " + role + " for service " + serviceDN);
        }

        // Add the user as a role member
        ldapServerService.addUniqueAttributeValue(roleEntry.getNameInNamespace(),
                getConfig().getRoleMemberAttribute(), userDN);
        log.info("Added " + userId + " as " + role + " for service " + serviceDN);

        // Un-cache the organization
        ldapCache.getServiceInstanceCache().evict(serviceInstanceId);

    } catch (NamingException e) {
        throw new RuntimeException("Error assigning service role ", e);
    }
}

From source file:com.funambol.LDAP.security.LDAPMailUserProvisioningOfficer.java

/**
 * Return a S4J user if successful bind to ldap
 * null if user or password is wrong// w w  w .j  av a 2s . co  m
 *      
 * TODO if I don't need to provision user on ldap,  I could avoid some of that stuff.. 
 * when binding, it retrieves imap/smtp server data to provision mail push
 * @param username
 * @param password
 * @return the {@link Sync4jUser} created from ldap fields
 */
public LDAPUser bindUserToLdap(String username, String password) {
    LDAPUser ldapUser = null;
    LdapManagerInterface ldapInterface = null;
    LdapManagerInterface ldapBindInterface = null;
    String userDN = null;
    /* TODO
     * this is now done creating an eventually authenticated context specified in 
     *  configuration file.
     *  moreover this context is shared between all ldap connections,
     *  so could be better defined at application server level 
     */
    try {
        TempParams t = new TempParams();
        // if username  is an email substitute %u e %d in baseDn:  
        expandSearchAndBaseDn(username, t);

        // setup the default LdapInterface configured with bean data
        // use a bean configuration file
        ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapInterface.init(t.tmpLdapUrl, t.tmpBaseDn, getSearchBindDn(), getSearchBindPassword(),
                isFollowReferral(), isConnectionPooling(), null);

        // set the userDN when custom user search
        if (!StringUtils.isEmpty(getUserSearch())) {
            // search the user binding with default ldap credential defined in the Officer.xml
            ldapInterface.setBaseDn(t.tmpBaseDn);
            SearchResult sr = ldapInterface.searchOneEntry(t.tmpUserSearch, new String[] { "dn" },
                    SearchControls.SUBTREE_SCOPE);

            if (sr != null) {
                userDN = sr.getNameInNamespace().trim();
                log.info("binding with dn:" + userDN);
            } else {
                log.info("Username [" + username + "] not found");
                ldapInterface.close();
                return null;
            }
        } else { // use append
            userDN = "uid=" + username + "," + t.tmpBaseDn;
        }

        ldapInterface.close();
        ldapBindInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapBindInterface.init(t.tmpLdapUrl, userDN, userDN, password, false, false, null);
        SearchResult sr = ldapBindInterface.searchOneEntry("(objectclass=*)", getLdapAttributesToRetrieve(),
                SearchControls.OBJECT_SCOPE);

        if (sr != null) {
            ldapUser = new LDAPUser();
            ldapUser.setUsername(username);
            ldapUser.setPassword(password);

            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_EMAIL))) {
                ldapUser.setEmail(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_EMAIL)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_FIRSTNAME))) {
                ldapUser.setFirstname(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_FIRSTNAME)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_LASTNAME))) {
                ldapUser.setLastname(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_LASTNAME)));
            }

            // set attributes to be passed to LDAP and CalDAV connector
            ldapUser.setUserDn(userDN);
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_ADDRESSBOOK))) {
                ldapUser.setPsRoot(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_ADDRESSBOOK)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_CALENDAR))) {
                ldapUser.setCalUri(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_CALENDAR)));
            }

            // get server attributes from LDAP if not void
            if (getImapServer() == null && StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_IMAP))) {
                setImapServer(LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_IMAP)));
            }
            if (getSmtpServer() == null && StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_SMTP))) {
                setSmtpServer(LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_SMTP)));
            }

            if (Configuration.getConfiguration().isDebugMode()) {
                if (log.isTraceEnabled()) {
                    StringBuffer sb = new StringBuffer(64);
                    sb.append("psRoot: ").append(ldapUser.getPsRoot()).append("\n").append("calUri: ")
                            .append(ldapUser.getCalUri()).append("\n").append("imapServer: ")
                            .append(getImapServer()).append("\n").append("smtpServer: ")
                            .append(getSmtpServer());

                    log.trace(sb.toString());

                }
            }
        } else {
            ldapUser = null;
        }
        ldapBindInterface.close();

    } catch (SyncSourceException e1) {
        log.error("Can't instantiate context: " + e1.getMessage());
        ldapUser = null;
    } catch (NamingException e) {
        log.warn("Can't retrieve mailserver attributes from ldap: " + e.getMessage());
        ldapUser = null;
    } catch (LDAPAccessException e) {
        log.error("Can't instantiate context: " + e.getMessage());
        ldapUser = null;
    } finally {
        if (ldapInterface != null) {
            ldapInterface.close();
        }
        if (ldapBindInterface != null) {
            ldapBindInterface.close();
        }
    }
    return ldapUser;
}

From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

/**
 * For a given name, this method makes ldap search in userBase with filter {@link #userIdAttribute}=name and objectClass={@link #userObjectClass}
 * and builds {@link User} based on search result.
 *
 * @param name/*from  ww w. j a v  a2 s .  c  o m*/
 *            The userId which should be value of the field {@link #userIdAttribute}
 * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the
 *         userId of this user and ldap connection information with which
 *         the user was searched. Return null if such a user was not found.
 * @throws NamingException
 *             Propagated by the underlying LDAP communication layer.
 */
private ReadOnlyLDAPUser searchAndBuildUser(String name) throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { userIdAttribute });
    sc.setCountLimit(1);

    StringBuilder builderFilter = new StringBuilder("(&(");
    builderFilter.append(userIdAttribute).append("=").append(name).append(")").append("(objectClass=")
            .append(userObjectClass).append(")");

    if (StringUtils.isNotEmpty(filter)) {
        builderFilter.append(filter).append(")");
    } else {
        builderFilter.append(")");
    }

    NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, builderFilter.toString(), sc);

    if (!sr.hasMore())
        return null;

    SearchResult r = sr.next();
    Attribute userName = r.getAttributes().get(userIdAttribute);

    if (!restriction.isActivated() || userInGroupsMembershipList(r.getNameInNamespace(),
            restriction.getGroupMembershipLists(ldapContext)))
        return new ReadOnlyLDAPUser(userName.get().toString(), r.getNameInNamespace(), ldapContext);

    return null;
}

From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

protected LdapUser createUser(final SearchResult result) throws NamingException {
    final Attributes attributes = result.getAttributes();

    final String username = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getUsernameAttribute());
    final String email = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getEmailAttribute());
    final String firstname = LdapUtils.getAttributeValue(attributes,
            _ldapConfiguration.getFirstnameAttribute());
    final String lastname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getLastnameAttribute());
    final String principal = result.getNameInNamespace();

    String domain = principal.replace(
            "cn=" + LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getCommonNameAttribute()) + ",",
            "");/*  ww  w .j a va  2 s.co  m*/
    domain = domain.replace("," + _ldapConfiguration.getBaseDn(), "");
    domain = domain.replace("ou=", "");

    boolean disabled = isUserDisabled(result);

    return new LdapUser(username, email, firstname, lastname, principal, domain, disabled);
}

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java

private void loadRoles(String filter, InitialLdapContext context, boolean removeMissingEntries)
        throws Exception {
    final Collection<String> groupNames = groupContainer.retrievePrincipalNames();
    PagedResultMapper mapper = new AbstractPagedResultMapper() {
        public void mapSearchResult(SearchResult searchResult) throws NamingException {
            String dn = searchResult.getNameInNamespace();
            Attributes attributes = searchResult.getAttributes();
            String commonName = getAttributeValue(attributes, COMMON_NAME_ATTRIBUTE);
            if (commonName.length() != 0) {
                Long rid = ActiveDirectoryGroup
                        .getRIDFromSID((byte[]) attributes.get(OBJECT_SID_ATTRIBUTE).get());
                ActiveDirectoryGroup group = new ActiveDirectoryGroup(commonName, dn, getEscapedDn(dn), rid,
                        getRealm());/*from w w  w .  j a v  a 2s . c  om*/
                String[] parents = getParents(attributes);
                String key = groupContainer.storeGroup(group, parents);
                groupNames.remove(key);
            }
        }
    };

    try {
        String replacedFilter = buildGroupFilter(filter);
        PagedResultTemplate pagedResultTemplate = configuration.getPagedResultTemplate();
        pagedResultTemplate.search(context, replacedFilter, GROUP_ATTRS, mapper);
    } finally {
        if (removeMissingEntries) {
            groupContainer.updateRemovedGroups(groupNames);
        }
    }
}

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java

private Collection<ActiveDirectoryGroup> getGroupsForUser(final ActiveDirectoryUser user)
        throws UserDatabaseException {
    final Collection<String> groupDns = new HashSet<String>();
    configuration.doAs(new RetryPrivilegedAction() {
        @Override/*  w  w  w .  ja  v  a 2  s  .c om*/
        protected Object doIt(InitialLdapContext context) throws Exception {
            PagedResultMapper mapper = new AbstractPagedResultMapper() {
                public void mapSearchResult(SearchResult searchResult) throws NamingException {
                    groupDns.add(searchResult.getNameInNamespace());
                }
            };

            String replacedFilter = USER_GROUPS_FILTER.replaceAll(GROUPNAME_FILTER_ATTRIBUTE, user.getDn());
            PagedResultTemplate pagedResultTemplate = configuration.getPagedResultTemplate();
            pagedResultTemplate.search(context, replacedFilter, GROUP_ATTRS, mapper);
            return null;
        }
    });

    Collection<ActiveDirectoryGroup> groups = new ArrayList<ActiveDirectoryGroup>();
    for (String groupDn : groupDns) {
        groups.addAll(getGroupsByDn(groupDn));
    }
    return groups;
}

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java

private void loadUsers(final String filter, InitialLdapContext context, final boolean removeMissingEntries)
        throws NamingException {
    final Collection<String> usernames = userContainer.retrievePrincipalNames();
    PagedResultMapper mapper = new AbstractPagedResultMapper() {
        public void mapSearchResult(SearchResult searchResult) throws NamingException, UserDatabaseException {
            String dn = searchResult.getNameInNamespace();
            ActiveDirectoryUser user = populateActiveDirectoryUser(dn, searchResult.getAttributes());
            String key = userContainer.storePrincipal(user);
            usernames.remove(key);//  w  w w  .  j  ava 2 s.co m
            if (logger.isDebugEnabled()) {
                logger.debug("Found user " + user);
            }
        }
    };

    try {
        String replacedFilter = buildUserFilter(filter);
        PagedResultTemplate pagedResultTemplate = configuration.getPagedResultTemplate();
        pagedResultTemplate.search(context, replacedFilter, USER_ATTRS, mapper);
    } finally {
        if (removeMissingEntries) {
            userContainer.updateRemovedPrincipals(usernames);
        }
    }
}