Example usage for javax.naming.ldap LdapName toString

List of usage examples for javax.naming.ldap LdapName toString

Introduction

In this page you can find the example usage for javax.naming.ldap LdapName toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of this LDAP name in a format defined by <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a> and described in the class description.

Usage

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn//from w ww.  j a v a  2 s. c  o m
 * @param subContextName
 * @param modifications
 */
public void updateSubContext(LdapName rootDn, LdapName subContextName, ModificationItem[] modifications) {
    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());
        ctx.modifyAttributes(subContextName, modifications);
    } catch (NamingException e) {
        throw new RuntimeException(subContextName.toString() + "," + rootDn, e);
    } finally {
        if (contextFactory != null)
            contextFactory.closeContext(ctx);
    }

}

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn/*from   w  ww  .j  a va  2  s. c  o  m*/
 * @param attributesToMatch
 * @return
 */
public NamingEnumeration<SearchResult> findAll(LdapName rootDn, Attributes attributesToMatch) {
    NamingEnumeration<SearchResult> result = null;

    DirContext ctx = null;
    try {
        ctx = contextFactory.createContext(rootDn.toString());
        result = ctx.search("", attributesToMatch);
    } catch (NamingException e) {
        throw new RuntimeException(rootDn.toString(), e);
    } finally {
        if (contextFactory != null)
            contextFactory.closeContext(ctx);
    }

    return result;
}

From source file:org.ligoj.app.plugin.id.ldap.dao.UserLdapRepository.java

@Override
public void move(final UserOrg user, final CompanyOrg company) {
    final LdapName newDn = org.springframework.ldap.support.LdapUtils
            .newLdapName(buildDn(user.getId(), company.getDn()));
    final LdapName oldDn = org.springframework.ldap.support.LdapUtils.newLdapName(user.getDn());
    template.rename(oldDn, newDn);/*  www  .  j  ava 2  s .c om*/
    user.setDn(newDn.toString());
    user.setCompany(company.getId());
    cacheRepository.update(user);

    // Also, update the groups of this user
    user.getGroups().forEach(g -> groupLdapRepository.updateMemberDn(g, oldDn.toString(), newDn.toString()));
}

From source file:org.lsc.jndi.JndiServices.java

public List<String> sup(String dn, int level) throws NamingException {
    int ncLevel = (new LdapName(contextDn.toString())).size();

    LdapName lName = new LdapName(dn);
    List<String> cList = new ArrayList<String>();
    if (level > 0) {
        if (lName.size() > level) {
            for (int i = 0; i < level; i++) {
                lName.remove(lName.size() - 1);
            }/*from ww w . j a v a  2  s.co  m*/
            cList.add(lName.toString());
        }
    } else if (level == 0) {
        cList.add(lName.toString());
        int size = lName.size();
        for (int i = 0; i < size - 1 && i < size - ncLevel; i++) {
            lName.remove(lName.size() - 1);
            cList.add(lName.toString());
        }
    } else {
        return null;
    }
    return cList;
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java

protected String getParentDn(String dn) {
    LdapName ldapName;
    String parentDn;//from  w w w .j a  v a  2s.  c  o m

    if (dn != null) {
        try {
            ldapName = new LdapName(dn);
            ldapName.remove(ldapName.size() - 1);
            parentDn = ldapName.toString();
            return parentDn;

        } catch (InvalidNameException ex) {
            return null;
        }
    }
    return null;
}

From source file:org.springframework.ldap.support.LdapUtilsTest.java

@Test
public void testEmptyLdapName() {
    LdapName ldapName = LdapUtils.emptyLdapName();
    assertThat(ldapName.toString()).isEqualTo("");
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * This method escapes the special characters in a LdapName
 * according to the ldap filter escaping standards.
 * @param ldn LDAP name which the special characters should be escaped.
 * @return - LDAP name with special characters removed.
 *//*from   w  ww.j a va2  s.  co m*/
private String escapeLdapNameForFilter(LdapName ldn) {

    if (ldn == null) {
        if (log.isDebugEnabled()) {
            log.debug("Received null value to escape special characters. Returning null");
        }
        return null;
    }

    boolean replaceEscapeCharacters = true;

    String replaceEscapeCharactersAtUserLoginString = userStoreProperties
            .get(CommonConstants.PROPERTY_REPLACE_ESCAPE_CHARACTERS_AT_USER_LOGIN);

    if (replaceEscapeCharactersAtUserLoginString != null) {
        replaceEscapeCharacters = Boolean.parseBoolean(replaceEscapeCharactersAtUserLoginString);
        if (log.isDebugEnabled()) {
            log.debug("Replace escape characters configured to: " + replaceEscapeCharactersAtUserLoginString);
        }
    }

    if (replaceEscapeCharacters) {
        StringBuilder escapedDN = new StringBuilder();
        for (int i = ldn.size() - 1; i > -1; i--) { //escaping the rdns separately and re-constructing the DN
            escapedDN = escapedDN.append(escapeSpecialCharactersForFilterWithStarAsRegex(ldn.get(i)));
            if (i != 0) {
                escapedDN.append(",");
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Escaped DN value for filter : " + escapedDN);
        }
        return escapedDN.toString();
    } else {
        return ldn.toString();
    }
}

From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 *
 *///from w  w  w  .jav a 2  s .  c  om
public boolean doAuthenticate(String userName, Object credential) throws UserStoreException {

    boolean debug = log.isDebugEnabled();

    String failedUserDN = null;

    if (userName == null || credential == null) {
        return false;
    }

    userName = userName.trim();

    String password = (String) credential;
    password = password.trim();

    if (userName.equals("") || password.equals("")) {
        return false;
    }

    if (debug) {
        log.debug("Authenticating user " + userName);
    }

    boolean bValue = false;
    // check cached user DN first.
    String name = null;
    LdapName ldn = (LdapName) userCache.get(userName);
    if (ldn != null) {
        name = ldn.toString();
        try {
            if (debug) {
                log.debug("Cache hit. Using DN " + name);
            }
            bValue = this.bindAsUser(userName, name, (String) credential);
        } catch (NamingException e) {
            // do nothing if bind fails since we check for other DN
            // patterns as well.
            if (log.isDebugEnabled()) {
                log.debug("Checking authentication with UserDN " + name + "failed " + e.getMessage(), e);
            }
        }

        if (bValue) {
            return bValue;
        }
        // we need not check binding for this name again, so store this and check
        failedUserDN = name;

    }
    // read DN patterns from user-mgt.xml
    String patterns = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN);

    if (patterns != null && !patterns.isEmpty()) {

        if (debug) {
            log.debug("Using UserDNPatterns " + patterns);
        }

        // if the property is present, split it using # to see if there are
        // multiple patterns specified.
        String[] userDNPatternList = patterns.split("#");
        if (userDNPatternList.length > 0) {
            for (String userDNPattern : userDNPatternList) {
                name = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName));
                // check if the same name is found and checked from cache
                if (failedUserDN != null && failedUserDN.equalsIgnoreCase(name)) {
                    continue;
                }

                if (debug) {
                    log.debug("Authenticating with " + name);
                }
                try {
                    if (name != null) {
                        bValue = this.bindAsUser(userName, name, (String) credential);
                        if (bValue) {
                            LdapName ldapName = new LdapName(name);
                            userCache.put(userName, ldapName);
                            break;
                        }
                    }
                } catch (NamingException e) {
                    // do nothing if bind fails since we check for other DN
                    // patterns as well.
                    if (log.isDebugEnabled()) {
                        log.debug("Checking authentication with UserDN " + userDNPattern + "failed "
                                + e.getMessage(), e);
                    }
                }
            }
        }
    } else {
        name = getNameInSpaceForUserName(userName);
        try {
            if (name != null) {
                if (debug) {
                    log.debug("Authenticating with " + name);
                }
                bValue = this.bindAsUser(userName, name, (String) credential);
                if (bValue) {
                    LdapName ldapName = new LdapName(name);
                    userCache.put(userName, ldapName);
                }
            }
        } catch (NamingException e) {
            String errorMessage = "Cannot bind user : " + userName;
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
            throw new UserStoreException(errorMessage, e);
        }
    }

    return bValue;
}

From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 *
 *//* www. j  a va 2  s  . c o  m*/
public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames, String profileName)
        throws UserStoreException {

    String userAttributeSeparator = ",";
    String userDN = null;
    LdapName ldn = (LdapName) userCache.get(userName);

    if (ldn == null) {
        // read list of patterns from user-mgt.xml
        String patterns = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN);

        if (patterns != null && !patterns.isEmpty()) {

            if (log.isDebugEnabled()) {
                log.debug("Using User DN Patterns " + patterns);
            }

            if (patterns.contains("#")) {
                userDN = getNameInSpaceForUserName(userName);
            } else {
                userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName));
            }
        }
    } else {
        userDN = ldn.toString();
    }

    Map<String, String> values = new HashMap<String, String>();
    // if user name contains domain name, remove domain name
    String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR);
    if (userNames.length > 1) {
        userName = userNames[1];
    }

    DirContext dirContext = this.connectionSource.getContext();
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    NamingEnumeration<?> answer = null;
    NamingEnumeration<?> attrs = null;
    try {
        if (userDN != null) {
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            if (propertyNames != null && propertyNames.length > 0) {
                searchCtls.setReturningAttributes(propertyNames);
            }
            if (log.isDebugEnabled()) {
                try {
                    log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: "
                            + dirContext.getNameInNamespace());
                } catch (NamingException e) {
                    log.debug("Error while getting DN of search base", e);
                }
                if (propertyNames == null) {
                    log.debug("No attributes requested");
                } else {
                    for (String attribute : propertyNames) {
                        log.debug("Requesting attribute :" + attribute);
                    }
                }
            }
            try {
                answer = dirContext.search(escapeDNForSearch(userDN), searchFilter, searchCtls);
            } catch (PartialResultException e) {
                // can be due to referrals in AD. so just ignore error
                String errorMessage = "Error occurred while searching directory context for user : " + userDN
                        + " searchFilter : " + searchFilter;
                if (isIgnorePartialResultException()) {
                    if (log.isDebugEnabled()) {
                        log.debug(errorMessage, e);
                    }
                } else {
                    throw new UserStoreException(errorMessage, e);
                }
            } catch (NamingException e) {
                String errorMessage = "Error occurred while searching directory context for user : " + userDN
                        + " searchFilter : " + searchFilter;
                if (log.isDebugEnabled()) {
                    log.debug(errorMessage, e);
                }
                throw new UserStoreException(errorMessage, e);
            }
        } else {
            answer = this.searchForUser(searchFilter, propertyNames, dirContext);
        }
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attributes = sr.getAttributes();
            if (attributes != null) {
                for (String name : propertyNames) {
                    if (name != null) {
                        Attribute attribute = attributes.get(name);
                        if (attribute != null) {
                            StringBuffer attrBuffer = new StringBuffer();
                            for (attrs = attribute.getAll(); attrs.hasMore();) {
                                Object attObject = attrs.next();
                                String attr = null;
                                if (attObject instanceof String) {
                                    attr = (String) attObject;
                                } else if (attObject instanceof byte[]) {
                                    //if the attribute type is binary base64 encoded string will be returned
                                    attr = new String(Base64.encodeBase64((byte[]) attObject));
                                }

                                if (attr != null && attr.trim().length() > 0) {
                                    String attrSeparator = realmConfig
                                            .getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                                    if (attrSeparator != null && !attrSeparator.trim().isEmpty()) {
                                        userAttributeSeparator = attrSeparator;
                                    }
                                    attrBuffer.append(attr + userAttributeSeparator);
                                }
                                String value = attrBuffer.toString();

                                /*
                                 * Length needs to be more than userAttributeSeparator.length() for a valid
                                 * attribute, since we
                                 * attach userAttributeSeparator
                                 */
                                if (value != null && value.trim().length() > userAttributeSeparator.length()) {
                                    value = value.substring(0,
                                            value.length() - userAttributeSeparator.length());
                                    values.put(name, value);
                                }

                            }
                        }
                    }
                }
            }
        }

    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting user property values for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        // close the naming enumeration and free up resources
        JNDIUtil.closeNamingEnumeration(attrs);
        JNDIUtil.closeNamingEnumeration(answer);
        // close directory context
        JNDIUtil.closeContext(dirContext);
    }
    return values;
}

From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

public boolean doCheckExistingUser(String userName) throws UserStoreException {

    if (log.isDebugEnabled()) {
        log.debug("Searching for user " + userName);
    }//from  w  ww.  ja  v a  2  s . co m
    boolean bFound = false;
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));
    try {
        String searchBase = null;
        String userDN = null;
        LdapName ldn = (LdapName) userCache.get(userName);
        if (ldn == null) {
            String userDNPattern = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN);
            if (userDNPattern != null && userDNPattern.trim().length() > 0) {
                String[] patterns = userDNPattern.split("#");
                for (String pattern : patterns) {
                    searchBase = MessageFormat.format(pattern, escapeSpecialCharactersForDN(userName));
                    userDN = getNameInSpaceForUserName(userName, searchBase, userSearchFilter);
                    if (userDN != null && userDN.length() > 0) {
                        bFound = true;
                        LdapName ldapName = new LdapName(userDN);
                        userCache.put(userName, ldapName);
                        break;
                    }
                }
            }
        } else {
            userDN = ldn.toString();
            searchBase = MessageFormat.format(userDN, escapeSpecialCharactersForDN(userName));
            userDN = getNameInSpaceForUserName(userName, searchBase, userSearchFilter);
            if (userDN != null && userDN.length() > 0) {
                bFound = true;
            } else {
                userCache.remove(userName);
            }
        }
        if (!bFound) {
            searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
            userDN = getNameInSpaceForUserName(userName, searchBase, userSearchFilter);
            if (userDN != null && userDN.length() > 0) {
                bFound = true;
            }
        }
    } catch (Exception e) {
        String errorMessage = "Error occurred while checking existence of user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    if (log.isDebugEnabled()) {
        log.debug("User: " + userName + " exist: " + bFound);
    }
    return bFound;
}