Example usage for javax.naming.ldap LdapName LdapName

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

Introduction

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

Prototype

public LdapName(List<Rdn> rdns) 

Source Link

Document

Constructs an LDAP name given its parsed RDN components.

Usage

From source file:org.glite.slcs.pki.bouncycastle.X509PrincipalUtil.java

/**
 * Creates a {@link X509Principal} with the given name.
 * <p>//from w w w.java  2s .  c  om
 * In the <code>name</code> the RDNs, like <code>CN=B+CN=A</code>, will
 * be sorted alphabetically. Literal characters like <code>+</code>,
 * <code>=</code> must be escaped.
 * 
 * @param name
 *            The {@link X509Principal} name.
 * @return the {@link X509Principal}.
 * @throws GeneralSecurityException
 *             if an error occurs.
 */
public X509Principal createX509Principal(String name) throws GeneralSecurityException {
    Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>();
    Vector<Object> values = new Vector<Object>();
    Vector<Boolean> added = new Vector<Boolean>();
    start_ = false;
    try {
        LdapName ldapName = new LdapName(name);
        LOG.debug("RDNs: " + ldapName.getRdns());
        Rdn[] rdnArray = new Rdn[ldapName.getRdns().size()];
        ldapName.getRdns().toArray(rdnArray);
        for (int i = rdnArray.length - 1; i >= 0; i--) {
            readRdn(rdnArray[i], oids, values, added);
            start_ = false;
        }
        X509Principal principal = buildX509Principal(oids, values, added);
        return principal;
    } catch (Exception e) {
        // NamingException or IOException
        LOG.error("Fail to create X509Principal(" + name + ")", e);
        throw new GeneralSecurityException("Fail to create X509Principal(" + name + "): " + e.getMessage(), e);
    }
}

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

private boolean doApply(final JndiModifications jm) throws CommunicationException {
    if (jm == null) {
        return true;
    }//from w w  w .j a v  a 2s . co  m

    try {
        switch (jm.getOperation()) {

        case ADD_ENTRY:
            ctx.createSubcontext(new LdapName(rewriteBase(jm.getDistinguishName())),
                    getAttributes(jm.getModificationItems(), true));
            break;

        case DELETE_ENTRY:
            if (recursiveDelete) {
                deleteChildrenRecursively(rewriteBase(jm.getDistinguishName()));
            } else {
                ctx.destroySubcontext(new LdapName(rewriteBase(jm.getDistinguishName())));
            }
            break;

        case MODIFY_ENTRY:
            Object[] table = jm.getModificationItems().toArray();
            ModificationItem[] mis = new ModificationItem[table.length];
            System.arraycopy(table, 0, mis, 0, table.length);
            ctx.modifyAttributes(new LdapName(rewriteBase(jm.getDistinguishName())), mis);
            break;

        case MODRDN_ENTRY:
            //We do not display this warning if we do not apply the modification with the option modrdn = false
            LOGGER.warn(
                    "WARNING: updating the RDN of the entry will cancel other modifications! Relaunch synchronization to complete update.");
            ctx.rename(new LdapName(rewriteBase(jm.getDistinguishName())),
                    new LdapName(rewriteBase(jm.getNewDistinguishName())));
            break;

        default:
            LOGGER.error("Unable to identify the right modification type: {}", jm.getOperation());
            return false;
        }
        return true;

    } catch (ContextNotEmptyException e) {
        LOGGER.error(
                "Object {} not deleted because it has children (LDAP error code 66 received). To delete this entry and it's subtree, set the dst.java.naming.recursivedelete property to true",
                jm.getDistinguishName());
        return false;

    } catch (NamingException ne) {
        if (LOGGER.isErrorEnabled()) {
            StringBuilder errorMessage = new StringBuilder("Error while ");
            switch (jm.getOperation()) {
            case ADD_ENTRY:
                errorMessage.append("adding");
                break;
            case MODIFY_ENTRY:
                errorMessage.append("modifying");
                break;
            case MODRDN_ENTRY:
                errorMessage.append("renaming");
                break;
            case DELETE_ENTRY:
                if (recursiveDelete) {
                    errorMessage.append("recursively ");
                }
                errorMessage.append("deleting");
                break;
            }
            errorMessage.append(" entry ").append(jm.getDistinguishName());
            errorMessage.append(" in directory :").append(ne.toString());

            LOGGER.error(errorMessage.toString());
        }

        if (ne instanceof CommunicationException) {
            // we lost the connection to the source or destination, stop everything!
            throw (CommunicationException) ne;
        }
        if (ne instanceof ServiceUnavailableException) {
            // we lost the connection to the source or destination, stop everything!
            CommunicationException ce = new CommunicationException(ne.getExplanation());
            ce.setRootCause(ne);
            throw ce;
        }

        return false;
    }
}

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

private void doDeleteChildrenRecursively(String distinguishName) throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    NamingEnumeration<SearchResult> ne = ctx.search(distinguishName, DEFAULT_FILTER, sc);
    while (ne.hasMore()) {
        SearchResult sr = (SearchResult) ne.next();
        String childrenDn = rewriteBase(sr.getName() + "," + distinguishName);
        deleteChildrenRecursively(childrenDn);
    }//  ww  w. j  a  v  a 2 s . c  om
    ctx.destroySubcontext(new LdapName(distinguishName));
}

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 w  ww. j  a v a  2 s  .c o 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.lsc.utils.output.LdifLayout.java

public static String format(LscModifications lm) {
    StringBuilder msgBuffer = new StringBuilder();

    printHeader(msgBuffer);/*from   w w w .  ja  v  a 2 s . c  o m*/

    String dn = "";
    if (lm.getMainIdentifier() != null && lm.getMainIdentifier().length() > 0) {
        dn = lm.getMainIdentifier();
    }

    // print dn and base64 encode if it's not a SAFE-STRING
    msgBuffer.append("dn");
    if (isLdifSafeString(dn)) {
        msgBuffer.append(": ").append(dn);
    } else {
        msgBuffer.append(":: ").append(toBase64(dn));
    }
    msgBuffer.append("\n");

    switch (lm.getOperation()) {
    case CREATE_OBJECT:
        msgBuffer.append("changetype: add\n");
        msgBuffer.append(listToLdif(lm.getLscAttributeModifications(), true));
        break;
    case CHANGE_ID:
        LdapName ln;
        try {
            ln = new LdapName(lm.getNewMainIdentifier());
            msgBuffer.append("changetype: modrdn\nnewrdn: ");
            msgBuffer.append(ln.get(ln.size() - 1));
            msgBuffer.append("\ndeleteoldrdn: 1\nnewsuperior: ");
            if (ln.size() > 1) {
                msgBuffer.append(ln.getPrefix(ln.size() - 1));
            }
            msgBuffer.append("\n");
        } catch (InvalidNameException e) {
            msgBuffer.append("changetype: modrdn\nnewrdn: ");
            msgBuffer.append(lm.getNewMainIdentifier());
            msgBuffer.append("\ndeleteoldrdn: 1\nnewsuperior: ");
            msgBuffer.append(lm.getNewMainIdentifier());
            msgBuffer.append("\n");
        }
        break;
    case UPDATE_OBJECT:
        msgBuffer.append("changetype: modify\n");
        msgBuffer.append(listToLdif(lm.getLscAttributeModifications(), false));
        break;
    case DELETE_OBJECT:
        msgBuffer.append("changetype: delete\n");
        break;
    default:
    }
    msgBuffer.append("\n");
    return msgBuffer.toString();
}

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

/**
 * Fetch both statically and dynamically defined references and merge the results.
 *
 * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String)
 *///from w  w w.  j  a v a2 s . c  o m
@Override
public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException {

    // container to hold merged references
    Set<String> sourceIds = new TreeSet<>();
    SearchResult targetLdapEntry = null;
    String targetDn = null;

    // step #1: resolve static references
    String staticAttributeId = getStaticAttributeId();
    if (staticAttributeId != null) {
        // step #1.1: fetch the dn of the targetId entry in the target
        // directory by the static dn valued strategy
        LDAPDirectory targetDir = getTargetLDAPDirectory();

        if (staticAttributeIdIsDn) {
            try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) {
                targetLdapEntry = targetSession.getLdapEntry(targetId, false);
                if (targetLdapEntry == null) {
                    String msg = String.format(
                            "Failed to perform inverse lookup on LDAPReference"
                                    + " resolving field '%s' of '%s' to entries of '%s'"
                                    + " using the static content of attribute '%s':"
                                    + " entry '%s' cannot be found in '%s'",
                            fieldName, sourceDirectory, targetDirectoryName, staticAttributeId, targetId,
                            targetDirectoryName);
                    throw new DirectoryEntryNotFoundException(msg);
                }
                targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());

            } catch (NamingException e) {
                throw new DirectoryException(
                        "error fetching " + targetId + " from " + targetDirectoryName + ": " + e.getMessage(),
                        e);
            }
        }

        // step #1.2: search for entries that reference that dn in the
        // source directory and collect their ids
        LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory();

        String filterExpr = String.format("(&(%s={0})%s)", staticAttributeId,
                ldapSourceDirectory.getBaseFilter());
        String[] filterArgs = new String[1];

        if (staticAttributeIdIsDn) {
            filterArgs[0] = targetDn;
        } else {
            filterArgs[0] = targetId;
        }

        String searchBaseDn = ldapSourceDirectory.getDescriptor().getSearchBaseDn();
        SearchControls sctls = ldapSourceDirectory.getSearchControls();
        try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'"
                                + " filter='%s' args='%s' scope='%s' [%s]",
                        targetId, searchBaseDn, filterExpr, StringUtils.join(filterArgs, ", "),
                        sctls.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(searchBaseDn, filterExpr,
                    filterArgs, sctls);

            try {
                while (results.hasMore()) {
                    Attributes attributes = results.next().getAttributes();
                    // NXP-2461: check that id field is filled
                    Attribute attr = attributes.get(sourceSession.idAttribute);
                    if (attr != null) {
                        Object value = attr.get();
                        if (value != null) {
                            sourceIds.add(value.toString());
                        }
                    }
                }
            } finally {
                results.close();
            }
        } catch (NamingException e) {
            throw new DirectoryException("error during reference search for " + filterArgs[0], e);
        }
    }
    // step #2: resolve dynamic references
    String dynamicAttributeId = this.dynamicAttributeId;
    if (dynamicAttributeId != null) {

        LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory();
        LDAPDirectory ldapTargetDirectory = getTargetLDAPDirectory();
        String searchBaseDn = ldapSourceDirectory.getDescriptor().getSearchBaseDn();

        try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession();
                LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) {
            // step #2.1: fetch the target entry to apply the ldap url
            // filters of the candidate sources on it
            if (targetLdapEntry == null) {
                // only fetch the entry if not already fetched by the
                // static
                // attributes references resolution
                targetLdapEntry = targetSession.getLdapEntry(targetId, false);
            }
            if (targetLdapEntry == null) {
                String msg = String.format(
                        "Failed to perform inverse lookup on LDAPReference"
                                + " resolving field '%s' of '%s' to entries of '%s'"
                                + " using the dynamic content of attribute '%s':"
                                + " entry '%s' cannot be found in '%s'",
                        fieldName, ldapSourceDirectory, targetDirectoryName, dynamicAttributeId, targetId,
                        targetDirectoryName);
                throw new DirectoryException(msg);
            }
            targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());
            Attributes targetAttributes = targetLdapEntry.getAttributes();

            // step #2.2: find the list of entries that hold candidate
            // dynamic links in the source directory
            SearchControls sctls = ldapSourceDirectory.getSearchControls();
            sctls.setReturningAttributes(new String[] { sourceSession.idAttribute, dynamicAttributeId });
            String filterExpr = String.format("%s=*", dynamicAttributeId);

            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'"
                                + " filter='%s' scope='%s' [%s]",
                        targetId, searchBaseDn, filterExpr, sctls.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(searchBaseDn, filterExpr,
                    sctls);
            try {
                while (results.hasMore()) {
                    // step #2.3: for each sourceId and each ldapUrl test
                    // whether the current target entry matches the
                    // collected
                    // URL
                    Attributes sourceAttributes = results.next().getAttributes();

                    NamingEnumeration<?> ldapUrls = sourceAttributes.get(dynamicAttributeId).getAll();
                    try {
                        while (ldapUrls.hasMore()) {
                            LdapURL ldapUrl = new LdapURL(ldapUrls.next().toString());
                            String candidateDN = pseudoNormalizeDn(ldapUrl.getDN());
                            // check base URL
                            if (!targetDn.endsWith(candidateDN)) {
                                continue;
                            }

                            // check onelevel scope constraints
                            if ("onelevel".equals(ldapUrl.getScope())) {
                                int targetDnSize = new LdapName(targetDn).size();
                                int urlDnSize = new LdapName(candidateDN).size();
                                if (targetDnSize - urlDnSize > 1) {
                                    // target is not a direct child of the
                                    // DN of the
                                    // LDAP URL
                                    continue;
                                }
                            }

                            // check that the target entry matches the
                            // filter
                            if (getFilterMatcher().match(targetAttributes, ldapUrl.getFilter())) {
                                // the target match the source url, add it
                                // to the
                                // collected ids
                                sourceIds.add(sourceAttributes.get(sourceSession.idAttribute).get().toString());
                            }
                        }
                    } finally {
                        ldapUrls.close();
                    }
                }
            } finally {
                results.close();
            }
        } catch (NamingException e) {
            throw new DirectoryException("error during reference search for " + targetId, e);
        }
    }

    /*
     * This kind of reference is not supported because Active Directory use filter expression not yet supported by
     * LDAPFilterMatcher. See NXP-4562
     */
    if (dynamicReferences != null && dynamicReferences.length > 0) {
        log.error("This kind of reference is not supported.");
    }

    return new ArrayList<>(sourceIds);
}

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

/**
 * Simple helper that replaces ", " by "," in the provided dn and returns the lower case version of the result for
 * comparison purpose.//from  ww w.  ja va 2s. com
 *
 * @param dn the raw unnormalized dn
 * @return lowercase version without whitespace after commas
 * @throws InvalidNameException
 */
protected static String pseudoNormalizeDn(String dn) throws InvalidNameException {
    LdapName ldapName = new LdapName(dn);
    List<String> rdns = new ArrayList<>();
    for (Rdn rdn : ldapName.getRdns()) {
        String value = rdn.getValue().toString().toLowerCase().replaceAll(",", "\\\\,");
        String rdnStr = rdn.getType().toLowerCase() + "=" + value;
        rdns.add(0, rdnStr);
    }
    return StringUtils.join(rdns, ',');
}

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

/**
 * Optimized method to spare a LDAP request when the caller is a LDAPSession object that has already fetched the
 * LDAP Attribute instances./*  w ww.j  av  a 2s.com*/
 * <p>
 * This method should return the same results as the sister method: org.nuxeo
 * .ecm.directory.Reference#getTargetIdsForSource(java.lang.String)
 *
 * @return target reference ids
 * @throws DirectoryException
 */
public List<String> getLdapTargetIds(Attributes attributes) throws DirectoryException {

    Set<String> targetIds = new TreeSet<>();

    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectoryDescriptor targetDirconfig = getTargetDirectoryDescriptor();
    String emptyRefMarker = ldapTargetDirectory.getDescriptor().getEmptyRefMarker();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) {
        String baseDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn());

        // step #1: fetch ids referenced by static attributes
        String staticAttributeId = getStaticAttributeId();
        Attribute staticAttribute = null;
        if (staticAttributeId != null) {
            staticAttribute = attributes.get(staticAttributeId);
        }

        if (staticAttribute != null && !staticAttributeIdIsDn) {
            NamingEnumeration<?> staticContent = staticAttribute.getAll();
            try {
                while (staticContent.hasMore()) {
                    String value = staticContent.next().toString();
                    if (!emptyRefMarker.equals(value)) {
                        targetIds.add(value);
                    }
                }
            } finally {
                staticContent.close();
            }
        }

        if (staticAttribute != null && staticAttributeIdIsDn) {
            NamingEnumeration<?> targetDns = staticAttribute.getAll();
            try {
                while (targetDns.hasMore()) {
                    String targetDn = targetDns.next().toString();

                    if (!pseudoNormalizeDn(targetDn).endsWith(baseDn)) {
                        // optim: avoid network connections when obvious
                        if (log.isTraceEnabled()) {
                            log.trace(String.format("ignoring: dn='%s' (does not match '%s') for '%s'",
                                    targetDn, baseDn, this));
                        }
                        continue;
                    }
                    // find the id of the referenced entry
                    String id = null;

                    if (targetSession.rdnMatchesIdField()) {
                        // optim: do not fetch the entry to get its true id
                        // but
                        // guess it by reading the targetDn
                        LdapName name = new LdapName(targetDn);
                        String rdn = name.get(name.size() - 1);
                        int pos = rdn.indexOf("=");
                        id = rdn.substring(pos + 1);
                    } else {
                        id = getIdForDn(targetSession, targetDn);
                        if (id == null) {
                            log.warn(String.format(
                                    "ignoring target '%s' (missing attribute '%s') while resolving reference '%s'",
                                    targetDn, targetSession.idAttribute, this));
                            continue;
                        }
                    }
                    if (forceDnConsistencyCheck) {
                        // check that the referenced entry is actually part
                        // of
                        // the target directory (takes care of the filters
                        // and
                        // the scope)
                        // this check can be very expensive on large groups
                        // and thus not enabled by default
                        if (!targetSession.hasEntry(id)) {
                            if (log.isTraceEnabled()) {
                                log.trace(String.format(
                                        "ignoring target '%s' when resolving '%s' (not part of target"
                                                + " directory by forced DN consistency check)",
                                        targetDn, this));
                            }
                            continue;
                        }
                    }
                    // NXP-2461: check that id field is filled
                    if (id != null) {
                        targetIds.add(id);
                    }
                }
            } finally {
                targetDns.close();
            }
        }
        // step #2: fetched dynamically referenced ids
        String dynamicAttributeId = this.dynamicAttributeId;
        Attribute dynamicAttribute = null;
        if (dynamicAttributeId != null) {
            dynamicAttribute = attributes.get(dynamicAttributeId);
        }
        if (dynamicAttribute != null) {
            NamingEnumeration<?> rawldapUrls = dynamicAttribute.getAll();
            try {
                while (rawldapUrls.hasMore()) {
                    LdapURL ldapUrl = new LdapURL(rawldapUrls.next().toString());
                    String linkDn = pseudoNormalizeDn(ldapUrl.getDN());
                    String directoryDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn());
                    int scope = SearchControls.ONELEVEL_SCOPE;
                    String scopePart = ldapUrl.getScope();
                    if (scopePart != null && scopePart.toLowerCase().startsWith("sub")) {
                        scope = SearchControls.SUBTREE_SCOPE;
                    }
                    if (!linkDn.endsWith(directoryDn) && !directoryDn.endsWith(linkDn)) {
                        // optim #1: if the dns do not match, abort
                        continue;
                    } else if (directoryDn.endsWith(linkDn) && linkDn.length() < directoryDn.length()
                            && scope == SearchControls.ONELEVEL_SCOPE) {
                        // optim #2: the link dn is pointing to elements
                        // that at
                        // upperlevel than directory elements
                        continue;
                    } else {

                        // Search for references elements
                        targetIds.addAll(getReferencedElements(attributes, directoryDn, linkDn,
                                ldapUrl.getFilter(), scope));

                    }
                }
            } finally {
                rawldapUrls.close();
            }
        }

        if (dynamicReferences != null && dynamicReferences.length > 0) {

            // Only the first Dynamic Reference is used
            LDAPDynamicReferenceDescriptor dynAtt = dynamicReferences[0];

            Attribute baseDnsAttribute = attributes.get(dynAtt.baseDN);
            Attribute filterAttribute = attributes.get(dynAtt.filter);

            if (baseDnsAttribute != null && filterAttribute != null) {

                NamingEnumeration<?> baseDns = null;
                NamingEnumeration<?> filters = null;

                try {
                    // Get the BaseDN value from the descriptor
                    baseDns = baseDnsAttribute.getAll();
                    String linkDnValue = baseDns.next().toString();
                    baseDns.close();
                    linkDnValue = pseudoNormalizeDn(linkDnValue);

                    // Get the filter value from the descriptor
                    filters = filterAttribute.getAll();
                    String filterValue = filters.next().toString();
                    filters.close();

                    // Get the scope value from the descriptor
                    int scope = "subtree".equalsIgnoreCase(dynAtt.type) ? SearchControls.SUBTREE_SCOPE
                            : SearchControls.ONELEVEL_SCOPE;

                    String directoryDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn());

                    // if the dns match, and if the link dn is pointing to
                    // elements that at upperlevel than directory elements
                    if ((linkDnValue.endsWith(directoryDn) || directoryDn.endsWith(linkDnValue))
                            && !(directoryDn.endsWith(linkDnValue)
                                    && linkDnValue.length() < directoryDn.length()
                                    && scope == SearchControls.ONELEVEL_SCOPE)) {

                        // Correct the filter expression
                        filterValue = FilterExpressionCorrector.correctFilter(filterValue,
                                FilterJobs.CORRECT_NOT);

                        // Search for references elements
                        targetIds.addAll(getReferencedElements(attributes, directoryDn, linkDnValue,
                                filterValue, scope));

                    }
                } finally {
                    if (baseDns != null) {
                        baseDns.close();
                    }

                    if (filters != null) {
                        filters.close();
                    }
                }

            }

        }
        // return merged attributes
        return new ArrayList<String>(targetIds);
    } catch (NamingException e) {
        throw new DirectoryException("error computing LDAP references", e);
    }
}

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

protected String getParentDn(String dn) {
    LdapName ldapName;//from w ww. ja  va2 s . c  om
    String parentDn;

    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.security4java.X509SubjectDnRetriever.java

public String getUserName(X509Certificate clientCert) {
    if (log.isDebugEnabled()) {
        log.debug("getUserName(X509Certificate) - start");
    }/*from   w w  w  .  j ava2 s  .  com*/
    String subject = getSubjectDN(clientCert);
    String userName = null;

    if (subject != null) {
        if (log.isDebugEnabled()) {
            log.debug("Subject is [" + subject + "].");
        }
        if (subjectDnAttribute == null) {
            if (log.isDebugEnabled()) {
                log.debug("subjectDnAttribute is null, so return the whole subject.");
            }
            userName = subject;
        } else {
            boolean foundUserName = false;
            try {
                LdapName ldapName = new LdapName(subject);
                List<Rdn> list = ldapName.getRdns();
                if (list != null) {
                    for (Rdn rdn : list) {
                        String type = rdn.getType();
                        if (subjectDnAttribute.equalsIgnoreCase(type.toString())) {
                            Object value = rdn.getValue();
                            if (value instanceof String) {
                                userName = (String) value;
                                foundUserName = true;
                                if (log.isDebugEnabled()) {
                                    log.debug("Success to retreive userName [" + userName + "].");
                                }
                                break;
                            }
                        }
                    }
                }
            } catch (InvalidNameException e) {
                log.info("subject [" + subject + "] is not valid name : [" + e.getMessage() + "].");
            }
            if (!foundUserName) {
                log.info("subject [" + subject + "] does not contain the required attribute ["
                        + subjectDnAttributeConfiguration + "]. Return the whole subject.");
                userName = subject;
            }
        }

    }

    if (log.isDebugEnabled()) {
        log.debug("getUserName(X509Certificate) - end; Ret is [" + userName + "].");
    }
    return userName;
}